• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ETSparser.h"
17 #include "ETSNolintParser.h"
18 
19 #include "util/es2pandaMacros.h"
20 #include "parser/parserFlags.h"
21 #include "util/errorRecovery.h"
22 #include "util/helpers.h"
23 #include "utils/arena_containers.h"
24 #include "varbinder/varbinder.h"
25 #include "varbinder/ETSBinder.h"
26 #include "lexer/lexer.h"
27 #include "ir/astNode.h"
28 #include "ir/base/classDefinition.h"
29 #include "ir/base/decorator.h"
30 #include "ir/base/catchClause.h"
31 #include "ir/base/classProperty.h"
32 #include "ir/base/scriptFunction.h"
33 #include "ir/base/methodDefinition.h"
34 #include "ir/base/classStaticBlock.h"
35 #include "ir/base/spreadElement.h"
36 #include "ir/expressions/identifier.h"
37 #include "ir/expressions/functionExpression.h"
38 #include "ir/statements/functionDeclaration.h"
39 #include "ir/statements/expressionStatement.h"
40 #include "ir/statements/classDeclaration.h"
41 #include "ir/statements/variableDeclarator.h"
42 #include "ir/statements/variableDeclaration.h"
43 #include "ir/expressions/dummyNode.h"
44 #include "ir/expressions/callExpression.h"
45 #include "ir/expressions/thisExpression.h"
46 #include "ir/expressions/typeofExpression.h"
47 #include "ir/expressions/memberExpression.h"
48 #include "ir/expressions/updateExpression.h"
49 #include "ir/expressions/arrowFunctionExpression.h"
50 #include "ir/expressions/unaryExpression.h"
51 #include "ir/expressions/yieldExpression.h"
52 #include "ir/expressions/awaitExpression.h"
53 #include "ir/expressions/literals/nullLiteral.h"
54 #include "ir/expressions/literals/numberLiteral.h"
55 #include "ir/expressions/literals/stringLiteral.h"
56 #include "ir/expressions/literals/undefinedLiteral.h"
57 #include "ir/module/importDeclaration.h"
58 #include "ir/module/importDefaultSpecifier.h"
59 #include "ir/module/importSpecifier.h"
60 #include "ir/module/exportSpecifier.h"
61 #include "ir/module/exportNamedDeclaration.h"
62 #include "ir/statements/annotationDeclaration.h"
63 #include "ir/statements/annotationUsage.h"
64 #include "ir/statements/blockStatement.h"
65 #include "ir/statements/ifStatement.h"
66 #include "ir/statements/labelledStatement.h"
67 #include "ir/statements/switchStatement.h"
68 #include "ir/statements/throwStatement.h"
69 #include "ir/statements/tryStatement.h"
70 #include "ir/statements/whileStatement.h"
71 #include "ir/statements/forOfStatement.h"
72 #include "ir/statements/doWhileStatement.h"
73 #include "ir/statements/breakStatement.h"
74 #include "ir/statements/debuggerStatement.h"
75 #include "ir/ets/etsClassLiteral.h"
76 #include "ir/ets/etsPrimitiveType.h"
77 #include "ir/ets/etsPackageDeclaration.h"
78 #include "ir/ets/etsReExportDeclaration.h"
79 #include "ir/ets/etsWildcardType.h"
80 #include "ir/ets/etsNewArrayInstanceExpression.h"
81 #include "ir/ets/etsTuple.h"
82 #include "ir/ets/etsFunctionType.h"
83 #include "ir/ets/etsNewClassInstanceExpression.h"
84 #include "ir/ets/etsNewMultiDimArrayInstanceExpression.h"
85 #include "ir/ets/etsModule.h"
86 #include "ir/ets/etsTypeReference.h"
87 #include "ir/ets/etsTypeReferencePart.h"
88 #include "ir/ets/etsNullishTypes.h"
89 #include "ir/ets/etsUnionType.h"
90 #include "ir/ets/etsImportDeclaration.h"
91 #include "ir/ets/etsStructDeclaration.h"
92 #include "ir/ets/etsParameterExpression.h"
93 #include "ir/module/importNamespaceSpecifier.h"
94 #include "ir/ts/tsAsExpression.h"
95 #include "ir/ts/tsInterfaceDeclaration.h"
96 #include "ir/ts/tsEnumDeclaration.h"
97 #include "ir/ts/tsTypeParameterInstantiation.h"
98 #include "ir/ts/tsInterfaceBody.h"
99 #include "ir/ts/tsImportEqualsDeclaration.h"
100 #include "ir/ts/tsArrayType.h"
101 #include "ir/ts/tsQualifiedName.h"
102 #include "ir/ts/tsTypeReference.h"
103 #include "ir/ts/tsTypeParameter.h"
104 #include "ir/ts/tsInterfaceHeritage.h"
105 #include "ir/ts/tsFunctionType.h"
106 #include "ir/ts/tsClassImplements.h"
107 #include "ir/ts/tsEnumMember.h"
108 #include "ir/ts/tsTypeAliasDeclaration.h"
109 #include "ir/ts/tsTypeParameterDeclaration.h"
110 #include "ir/ts/tsNonNullExpression.h"
111 #include "ir/ts/tsThisType.h"
112 #include "generated/signatures.h"
113 #include "generated/diagnostic.h"
114 
115 namespace ark::es2panda::parser {
116 class FunctionContext;
117 
118 using namespace std::literals::string_literals;
119 
ParseTopLevelStatements()120 ArenaVector<ir::Statement *> ETSParser::ParseTopLevelStatements()
121 {
122     ArenaVector<ir::Statement *> statements(Allocator()->Adapter());
123     while (Lexer()->GetToken().Type() != lexer::TokenType::EOS) {
124         util::ErrorRecursionGuard infiniteLoopBlocker(Lexer());
125 
126         if (Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_SEMI_COLON)) {
127             continue;
128         }
129         auto stmt = ParseTopLevelStatement();
130         GetContext().Status() &= ~ParserStatus::IN_AMBIENT_CONTEXT;
131         if (stmt != nullptr) {
132             statements.emplace_back(stmt);
133         }
134     }
135 
136     return statements;
137 }
138 
ValidateExportableStatement(ETSParser * parser,ir::Statement * stmt,ark::es2panda::ir::ModifierFlags memberModifiers,lexer::SourcePosition pos)139 static ir::Statement *ValidateExportableStatement(ETSParser *parser, ir::Statement *stmt,
140                                                   ark::es2panda::ir::ModifierFlags memberModifiers,
141                                                   lexer::SourcePosition pos)
142 {
143     if (stmt != nullptr) {
144         if (stmt->IsETSModule()) {
145             return stmt;
146         }
147         if (stmt->IsAnnotationDeclaration()) {
148             if ((memberModifiers & ir::ModifierFlags::DEFAULT_EXPORT) != 0U) {
149                 parser->LogError(diagnostic::INVALID_EXPORT_DEFAULT, {}, stmt->Start());
150             }
151         }
152         stmt->AddModifier(memberModifiers);
153     } else {
154         if ((memberModifiers & (ir::ModifierFlags::EXPORT | ir::ModifierFlags::DEFAULT_EXPORT)) != 0U) {
155             parser->LogError(diagnostic::EXPORT_NON_DECLARATION, {}, pos);
156         }
157     }
158 
159     return stmt;
160 }
IsExportedDeclaration(ir::ModifierFlags memberModifiers)161 bool ETSParser::IsExportedDeclaration(ir::ModifierFlags memberModifiers)
162 {
163     return (memberModifiers & ir::ModifierFlags::EXPORTED) != 0U;
164 }
165 
IsInitializerBlockStart() const166 bool ETSParser::IsInitializerBlockStart() const
167 {
168     if (Lexer()->GetToken().Type() != lexer::TokenType::KEYW_STATIC) {
169         return false;
170     }
171 
172     auto savedPos = Lexer()->Save();
173     Lexer()->NextToken();
174     const bool validStart = Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LEFT_BRACE &&
175                             ((GetContext().Status() & ParserStatus::IN_NAMESPACE) != 0 ||
176                              (GetContext().Status() & ParserStatus::IN_PACKAGE) != 0);
177     Lexer()->Rewind(savedPos);
178     return validStart;
179 }
180 
ParseTopLevelDeclStatement(StatementParsingFlags flags)181 ir::Statement *ETSParser::ParseTopLevelDeclStatement(StatementParsingFlags flags)
182 {
183     auto [memberModifiers, startLoc] = ParseMemberModifiers();
184 
185     if (CheckAccessorDeclaration(memberModifiers)) {
186         return ParseAccessorWithReceiver(memberModifiers);
187     }
188 
189     ir::Statement *result = nullptr;
190     auto token = Lexer()->GetToken();
191     switch (token.Type()) {
192         case lexer::TokenType::KEYW_FUNCTION: {
193             result = ParseFunctionDeclaration(false, memberModifiers);
194             ES2PANDA_ASSERT(result != nullptr);
195             result->SetStart(startLoc);
196             break;
197         }
198         case lexer::TokenType::KEYW_CONST:
199             memberModifiers |= ir::ModifierFlags::CONST;
200             [[fallthrough]];
201         case lexer::TokenType::KEYW_LET:
202             result = ParseStatement(flags);
203             break;
204         case lexer::TokenType::KEYW_STATIC:
205         case lexer::TokenType::KEYW_ABSTRACT:
206         case lexer::TokenType::KEYW_FINAL:
207         case lexer::TokenType::KEYW_ENUM:
208         case lexer::TokenType::KEYW_INTERFACE:
209         case lexer::TokenType::KEYW_CLASS:
210             result = ParseTypeDeclaration(IsInitializerBlockStart());
211             break;
212         case lexer::TokenType::PUNCTUATOR_AT:
213             result = ParseTopLevelAnnotation(memberModifiers);
214             break;
215         case lexer::TokenType::LITERAL_IDENT: {
216             if (IsNamespaceDecl()) {
217                 return ParseNamespaceStatement(memberModifiers);
218             }
219             result = ParseIdentKeyword();
220             if (result == nullptr && (memberModifiers & (ir::ModifierFlags::EXPORTED)) != 0U) {
221                 return ParseExport(startLoc, memberModifiers);
222             }
223             break;
224         }
225         default: {
226         }
227     }
228 
229     if (result == nullptr && IsExportedDeclaration(memberModifiers)) {
230         return ParseExport(startLoc, memberModifiers);
231     }
232 
233     return ValidateExportableStatement(this, result, memberModifiers, startLoc);
234 }
235 
ParseTopLevelStatement()236 ir::Statement *ETSParser::ParseTopLevelStatement()
237 {
238     const auto flags = StatementParsingFlags::ALLOW_LEXICAL;
239     ArenaVector<ir::JsDocInfo> jsDocInformation(Allocator()->Adapter());
240     if (Lexer()->TryEatTokenType(lexer::TokenType::JS_DOC_START)) {
241         jsDocInformation = ParseJsDocInfos();
242     }
243 
244     if (Lexer()->GetToken().Type() == lexer::TokenType::EOS ||
245         ((GetContext().Status() & ParserStatus::IN_NAMESPACE) != 0 &&
246          Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_BRACE)) {
247         return nullptr;
248     }
249     GetContext().Status() |= ParserStatus::ALLOW_JS_DOC_START;
250     auto result = ParseTopLevelDeclStatement(flags);
251     GetContext().Status() ^= ParserStatus::ALLOW_JS_DOC_START;
252     if (result != nullptr) {
253         ApplyJsDocInfoToSpecificNodeType(result, std::move(jsDocInformation));
254     }
255 
256     if (result == nullptr) {
257         result = ParseStatement(flags);
258     }
259     return result;
260 }
261 
ParseAnnotationsInStatement(StatementParsingFlags flags)262 ir::Statement *ETSParser::ParseAnnotationsInStatement(StatementParsingFlags flags)
263 {
264     Lexer()->NextToken();  // eat '@'
265 
266     auto annotations = ParseAnnotations(false);
267     auto savePos = Lexer()->GetToken().Start();
268     ir::Statement *result = ParseStatement(flags);
269     if (result != nullptr) {
270         ApplyAnnotationsToNode(result, std::move(annotations), savePos);
271     }
272     return result;
273 }
274 
ParseTopLevelDeclaration()275 ArenaVector<ir::Statement *> ETSParser::ParseTopLevelDeclaration()
276 {
277     auto topStatements = ParseTopLevelStatements();
278     Lexer()->NextToken();
279     return topStatements;
280 }
281 
ValidateLabeledStatement(lexer::TokenType type)282 bool ETSParser::ValidateLabeledStatement(lexer::TokenType type)
283 {
284     if (type != lexer::TokenType::KEYW_DO && type != lexer::TokenType::KEYW_WHILE &&
285         type != lexer::TokenType::KEYW_FOR && type != lexer::TokenType::KEYW_SWITCH) {
286         LogError(diagnostic::MISSING_LOOP_AFTER_LABEL, {}, Lexer()->GetToken().Start());
287         return false;
288     }
289 
290     return true;
291 }
292 
ValidateForInStatement()293 bool ETSParser::ValidateForInStatement()
294 {
295     LogUnexpectedToken(lexer::TokenType::KEYW_IN);
296     return false;
297 }
298 
ParseDebuggerStatement()299 ir::Statement *ETSParser::ParseDebuggerStatement()
300 {
301     LogError(diagnostic::ERROR_ARKTS_NO_DEBUGGER_STATEMENT);
302     return AllocBrokenStatement(Lexer()->GetToken().Loc());
303 }
304 
ParseFunctionStatement(const StatementParsingFlags flags)305 ir::Statement *ETSParser::ParseFunctionStatement(const StatementParsingFlags flags)
306 {
307     ES2PANDA_ASSERT((flags & StatementParsingFlags::GLOBAL) == 0);
308     LogError(diagnostic::NESTED_FUNCTIONS_NOT_ALLOWED);
309     ParserImpl::ParseFunctionStatement(flags);  // Try to parse function body but skip result.
310     return AllocBrokenStatement(Lexer()->GetToken().Loc());
311 }
312 
ParseTryStatement()313 ir::Statement *ETSParser::ParseTryStatement()
314 {
315     lexer::SourcePosition startLoc = Lexer()->GetToken().Start();
316     Lexer()->NextToken();  // eat the 'try' keyword
317 
318     ir::BlockStatement *body = ParseBlockStatement();
319 
320     ArenaVector<ir::CatchClause *> catchClauses(Allocator()->Adapter());
321 
322     while (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_CATCH) {
323         catchClauses.push_back(ParseCatchClause());
324     }
325 
326     ir::BlockStatement *finalizer = nullptr;
327     if (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_FINALLY) {
328         Lexer()->NextToken();  // eat 'finally' keyword
329 
330         finalizer = ParseBlockStatement();
331     }
332 
333     if (catchClauses.empty() && finalizer == nullptr) {
334         LogError(diagnostic::MISSING_CATCH_OR_FINALLY_AFTER_TRY, {}, startLoc);
335         return AllocBrokenStatement(startLoc);
336     }
337 
338     lexer::SourcePosition endLoc = finalizer != nullptr ? finalizer->End() : catchClauses.back()->End();
339 
340     ArenaVector<std::pair<compiler::LabelPair, const ir::Statement *>> finalizerInsertions(Allocator()->Adapter());
341 
342     auto *tryStatement = AllocNode<ir::TryStatement>(body, std::move(catchClauses), finalizer, finalizerInsertions);
343     ES2PANDA_ASSERT(tryStatement != nullptr);
344     tryStatement->SetRange({startLoc, endLoc});
345     ConsumeSemicolon(tryStatement);
346 
347     return tryStatement;
348 }
349 
350 // NOLINTNEXTLINE(google-default-arguments)
ParseClassStatement(StatementParsingFlags flags,ir::ClassDefinitionModifiers modifiers,ir::ModifierFlags modFlags)351 ir::Statement *ETSParser::ParseClassStatement([[maybe_unused]] StatementParsingFlags flags,
352                                               ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags)
353 {
354     modFlags |= ParseClassModifiers();
355     const auto &rangeClass = Lexer()->GetToken().Loc();
356     LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"CLASS"}, rangeClass.start);
357     // Try to parse class and drop the result.
358     ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED |
359                               ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL,
360                           modFlags);
361     return AllocBrokenStatement(rangeClass);
362 }
363 
364 // NOLINTNEXTLINE(google-default-arguments)
ParseStructStatement(StatementParsingFlags flags,ir::ClassDefinitionModifiers modifiers,ir::ModifierFlags modFlags)365 ir::Statement *ETSParser::ParseStructStatement([[maybe_unused]] StatementParsingFlags flags,
366                                                ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags)
367 {
368     const auto &rangeStruct = Lexer()->GetToken().Loc();
369     LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"STRUCT"}, rangeStruct.start);
370     // Try to parse struct and drop the result.
371     ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED |
372                               ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL,
373                           modFlags);
374     return AllocBrokenStatement(rangeStruct);
375 }
376 
377 // NOLINTNEXTLINE(google-default-arguments)
ParseInterfaceStatement(StatementParsingFlags flags)378 ir::Statement *ETSParser::ParseInterfaceStatement([[maybe_unused]] StatementParsingFlags flags)
379 {
380     auto &rangeClass = Lexer()->GetToken().Loc();
381     LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"INTERFACE"}, Lexer()->GetToken().Start());
382     ParseInterfaceDeclaration(false);
383     return AllocBrokenStatement(rangeClass);
384 }
385 
386 }  // namespace ark::es2panda::parser
387