• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2024 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 #include <utility>
19 
20 #include "macros.h"
21 #include "parser/parserFlags.h"
22 #include "parser/parserStatusContext.h"
23 #include "util/helpers.h"
24 #include "util/language.h"
25 #include "utils/arena_containers.h"
26 #include "varbinder/varbinder.h"
27 #include "varbinder/ETSBinder.h"
28 #include "lexer/lexer.h"
29 #include "lexer/ETSLexer.h"
30 #include "checker/types/ets/etsEnumType.h"
31 #include "ir/astNode.h"
32 #include "ir/base/classDefinition.h"
33 #include "ir/base/decorator.h"
34 #include "ir/base/catchClause.h"
35 #include "ir/base/classProperty.h"
36 #include "ir/base/scriptFunction.h"
37 #include "ir/base/methodDefinition.h"
38 #include "ir/base/classStaticBlock.h"
39 #include "ir/base/spreadElement.h"
40 #include "ir/expressions/identifier.h"
41 #include "ir/expressions/functionExpression.h"
42 #include "ir/statements/functionDeclaration.h"
43 #include "ir/statements/expressionStatement.h"
44 #include "ir/statements/classDeclaration.h"
45 #include "ir/statements/variableDeclarator.h"
46 #include "ir/statements/variableDeclaration.h"
47 #include "ir/expressions/dummyNode.h"
48 #include "ir/expressions/callExpression.h"
49 #include "ir/expressions/thisExpression.h"
50 #include "ir/expressions/typeofExpression.h"
51 #include "ir/expressions/memberExpression.h"
52 #include "ir/expressions/updateExpression.h"
53 #include "ir/expressions/arrowFunctionExpression.h"
54 #include "ir/expressions/unaryExpression.h"
55 #include "ir/expressions/yieldExpression.h"
56 #include "ir/expressions/awaitExpression.h"
57 #include "ir/expressions/literals/nullLiteral.h"
58 #include "ir/expressions/literals/numberLiteral.h"
59 #include "ir/expressions/literals/stringLiteral.h"
60 #include "ir/expressions/literals/undefinedLiteral.h"
61 #include "ir/module/importDeclaration.h"
62 #include "ir/module/importDefaultSpecifier.h"
63 #include "ir/module/importSpecifier.h"
64 #include "ir/module/exportSpecifier.h"
65 #include "ir/module/exportNamedDeclaration.h"
66 #include "ir/statements/assertStatement.h"
67 #include "ir/statements/blockStatement.h"
68 #include "ir/statements/ifStatement.h"
69 #include "ir/statements/labelledStatement.h"
70 #include "ir/statements/switchStatement.h"
71 #include "ir/statements/throwStatement.h"
72 #include "ir/statements/tryStatement.h"
73 #include "ir/statements/whileStatement.h"
74 #include "ir/statements/forOfStatement.h"
75 #include "ir/statements/doWhileStatement.h"
76 #include "ir/statements/breakStatement.h"
77 #include "ir/statements/debuggerStatement.h"
78 #include "ir/ets/etsLaunchExpression.h"
79 #include "ir/ets/etsClassLiteral.h"
80 #include "ir/ets/etsPrimitiveType.h"
81 #include "ir/ets/etsPackageDeclaration.h"
82 #include "ir/ets/etsReExportDeclaration.h"
83 #include "ir/ets/etsWildcardType.h"
84 #include "ir/ets/etsNewArrayInstanceExpression.h"
85 #include "ir/ets/etsTuple.h"
86 #include "ir/ets/etsFunctionType.h"
87 #include "ir/ets/etsNewClassInstanceExpression.h"
88 #include "ir/ets/etsNewMultiDimArrayInstanceExpression.h"
89 #include "ir/ets/etsScript.h"
90 #include "ir/ets/etsTypeReference.h"
91 #include "ir/ets/etsTypeReferencePart.h"
92 #include "ir/ets/etsNullishTypes.h"
93 #include "ir/ets/etsUnionType.h"
94 #include "ir/ets/etsImportSource.h"
95 #include "ir/ets/etsImportDeclaration.h"
96 #include "ir/ets/etsStructDeclaration.h"
97 #include "ir/ets/etsParameterExpression.h"
98 #include "ir/module/importNamespaceSpecifier.h"
99 #include "ir/ts/tsAsExpression.h"
100 #include "ir/ts/tsInterfaceDeclaration.h"
101 #include "ir/ts/tsEnumDeclaration.h"
102 #include "ir/ts/tsTypeParameterInstantiation.h"
103 #include "ir/ts/tsInterfaceBody.h"
104 #include "ir/ts/tsImportEqualsDeclaration.h"
105 #include "ir/ts/tsArrayType.h"
106 #include "ir/ts/tsQualifiedName.h"
107 #include "ir/ts/tsTypeReference.h"
108 #include "ir/ts/tsTypeParameter.h"
109 #include "ir/ts/tsInterfaceHeritage.h"
110 #include "ir/ts/tsFunctionType.h"
111 #include "ir/ts/tsClassImplements.h"
112 #include "ir/ts/tsEnumMember.h"
113 #include "ir/ts/tsTypeAliasDeclaration.h"
114 #include "ir/ts/tsTypeParameterDeclaration.h"
115 #include "ir/ts/tsNonNullExpression.h"
116 #include "ir/ts/tsThisType.h"
117 #include "generated/signatures.h"
118 
119 namespace ark::es2panda::parser {
120 class FunctionContext;
121 
122 using namespace std::literals::string_literals;
123 
ParseTopLevelStatements()124 ArenaVector<ir::Statement *> ETSParser::ParseTopLevelStatements()
125 {
126     ArenaVector<ir::Statement *> statements(Allocator()->Adapter());
127     while (Lexer()->GetToken().Type() != lexer::TokenType::EOS) {
128         if (Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_SEMI_COLON)) {
129             continue;
130         }
131         auto stmt = ParseTopLevelStatement();
132         GetContext().Status() &= ~ParserStatus::IN_AMBIENT_CONTEXT;
133         if (stmt != nullptr) {
134             statements.emplace_back(stmt);
135         }
136     }
137 
138     return statements;
139 }
140 
ValidateExportableStatement(ETSParser * parser,ir::Statement * stmt,ark::es2panda::ir::ModifierFlags memberModifiers)141 static ir::Statement *ValidateExportableStatement(ETSParser *parser, ir::Statement *stmt,
142                                                   ark::es2panda::ir::ModifierFlags memberModifiers)
143 {
144     if (stmt != nullptr) {
145         if ((memberModifiers & ir::ModifierFlags::EXPORT_TYPE) != 0U &&
146             !(stmt->IsClassDeclaration() || stmt->IsTSInterfaceDeclaration() || stmt->IsTSTypeAliasDeclaration())) {
147             parser->ThrowSyntaxError("Can only type export class or interface!", stmt->Start());
148         }
149         stmt->AddModifier(memberModifiers);
150     }
151     return stmt;
152 }
153 
ParseTopLevelDeclStatement(StatementParsingFlags flags)154 ir::Statement *ETSParser::ParseTopLevelDeclStatement(StatementParsingFlags flags)
155 {
156     auto [memberModifiers, startLoc] = ParseMemberModifiers();
157     if ((memberModifiers & (ir::ModifierFlags::EXPORTED)) != 0U &&
158         (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_MULTIPLY ||
159          Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LEFT_BRACE)) {
160         return ParseExport(startLoc, memberModifiers);
161     }
162 
163     ir::Statement *result = nullptr;
164     auto token = Lexer()->GetToken();
165     switch (token.Type()) {
166         case lexer::TokenType::KEYW_FUNCTION: {
167             result = ParseFunctionDeclaration(false, memberModifiers);
168             result->SetStart(startLoc);
169             break;
170         }
171         case lexer::TokenType::KEYW_CONST: {
172             memberModifiers |= ir::ModifierFlags::CONST;
173             [[fallthrough]];
174         }
175         case lexer::TokenType::KEYW_LET: {
176             result = ParseStatement(flags);
177             break;
178         }
179         case lexer::TokenType::KEYW_NAMESPACE:
180         case lexer::TokenType::KEYW_STATIC:
181         case lexer::TokenType::KEYW_ABSTRACT:
182         case lexer::TokenType::KEYW_FINAL:
183         case lexer::TokenType::KEYW_ENUM:
184         case lexer::TokenType::KEYW_INTERFACE:
185         case lexer::TokenType::KEYW_CLASS: {
186             result = ParseTypeDeclaration(false);
187             break;
188         }
189         case lexer::TokenType::LITERAL_IDENT: {
190             result = ParseIdentKeyword();
191             if (result == nullptr && (memberModifiers & (ir::ModifierFlags::EXPORTED)) != 0U) {
192                 return ParseExport(startLoc, memberModifiers);
193             }
194             break;
195         }
196         default: {
197         }
198     }
199 
200     return ValidateExportableStatement(this, result, memberModifiers);
201 }
202 
ParseTopLevelStatement()203 ir::Statement *ETSParser::ParseTopLevelStatement()
204 {
205     const auto flags = StatementParsingFlags::ALLOW_LEXICAL;
206     static const std::unordered_set<lexer::TokenType> ALLOWED_TOP_LEVEL_STMTS = {
207         lexer::TokenType::PUNCTUATOR_LEFT_BRACE,
208         lexer::TokenType::PUNCTUATOR_SEMI_COLON,
209         lexer::TokenType::KEYW_ASSERT,
210         lexer::TokenType::KEYW_IF,
211         lexer::TokenType::KEYW_DO,
212         lexer::TokenType::KEYW_FOR,
213         lexer::TokenType::KEYW_TRY,
214         lexer::TokenType::KEYW_WHILE,
215         lexer::TokenType::KEYW_BREAK,
216         lexer::TokenType::KEYW_CONTINUE,
217         lexer::TokenType::KEYW_THROW,
218         lexer::TokenType::KEYW_SWITCH,
219         lexer::TokenType::KEYW_DEBUGGER,
220         lexer::TokenType::LITERAL_IDENT,
221     };
222 
223     auto result = ParseTopLevelDeclStatement(flags);
224     if (result == nullptr) {
225         auto const tokenType = Lexer()->GetToken().Type();
226         if (ALLOWED_TOP_LEVEL_STMTS.count(tokenType) != 0U) {
227             result = ParseStatement(flags);
228         } else {
229             ThrowUnexpectedToken(tokenType);
230         }
231     }
232     return result;
233 }
234 
ParseTopLevelDeclaration()235 ArenaVector<ir::Statement *> ETSParser::ParseTopLevelDeclaration()
236 {
237     auto topStatements = ParseTopLevelStatements();
238     Lexer()->NextToken();
239     return topStatements;
240 }
241 
ValidateLabeledStatement(lexer::TokenType type)242 void ETSParser::ValidateLabeledStatement(lexer::TokenType type)
243 {
244     if (type != lexer::TokenType::KEYW_DO && type != lexer::TokenType::KEYW_WHILE &&
245         type != lexer::TokenType::KEYW_FOR && type != lexer::TokenType::KEYW_SWITCH) {
246         ThrowSyntaxError("Label must be followed by a loop statement", Lexer()->GetToken().Start());
247     }
248 }
249 
ValidateForInStatement()250 void ETSParser::ValidateForInStatement()
251 {
252     ThrowUnexpectedToken(lexer::TokenType::KEYW_IN);
253 }
254 
ParseDebuggerStatement()255 ir::DebuggerStatement *ETSParser::ParseDebuggerStatement()
256 {
257     ThrowUnexpectedToken(lexer::TokenType::KEYW_DEBUGGER);
258 }
259 
ParseFunctionStatement(const StatementParsingFlags flags)260 ir::Statement *ETSParser::ParseFunctionStatement([[maybe_unused]] const StatementParsingFlags flags)
261 {
262     ASSERT((flags & StatementParsingFlags::GLOBAL) == 0);
263     ThrowSyntaxError("Nested functions are not allowed");
264 }
265 
ParseAssertStatement()266 ir::Statement *ETSParser::ParseAssertStatement()
267 {
268     lexer::SourcePosition startLoc = Lexer()->GetToken().Start();
269     Lexer()->NextToken();
270 
271     ir::Expression *test = ParseExpression();
272     lexer::SourcePosition endLoc = test->End();
273     ir::Expression *second = nullptr;
274 
275     if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_COLON) {
276         Lexer()->NextToken();  // eat ':'
277         second = ParseExpression();
278         endLoc = second->End();
279     }
280 
281     auto *asStatement = AllocNode<ir::AssertStatement>(test, second);
282     asStatement->SetRange({startLoc, endLoc});
283     ConsumeSemicolon(asStatement);
284 
285     return asStatement;
286 }
287 
ParseTryStatement()288 ir::Statement *ETSParser::ParseTryStatement()
289 {
290     lexer::SourcePosition startLoc = Lexer()->GetToken().Start();
291     Lexer()->NextToken();  // eat the 'try' keyword
292 
293     if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_BRACE) {
294         ThrowSyntaxError("Unexpected token, expected '{'");
295     }
296 
297     ir::BlockStatement *body = ParseBlockStatement();
298 
299     ArenaVector<ir::CatchClause *> catchClauses(Allocator()->Adapter());
300 
301     while (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_CATCH) {
302         ir::CatchClause *clause {};
303 
304         clause = ParseCatchClause();
305 
306         catchClauses.push_back(clause);
307     }
308 
309     ir::BlockStatement *finalizer = nullptr;
310     if (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_FINALLY) {
311         Lexer()->NextToken();  // eat 'finally' keyword
312 
313         finalizer = ParseBlockStatement();
314     }
315 
316     if (catchClauses.empty() && finalizer == nullptr) {
317         ThrowSyntaxError("A try statement should contain either finally clause or at least one catch clause.",
318                          startLoc);
319     }
320 
321     lexer::SourcePosition endLoc = finalizer != nullptr ? finalizer->End() : catchClauses.back()->End();
322 
323     ArenaVector<std::pair<compiler::LabelPair, const ir::Statement *>> finalizerInsertions(Allocator()->Adapter());
324 
325     auto *tryStatement = AllocNode<ir::TryStatement>(body, std::move(catchClauses), finalizer, finalizerInsertions);
326     tryStatement->SetRange({startLoc, endLoc});
327     ConsumeSemicolon(tryStatement);
328 
329     return tryStatement;
330 }
331 
332 // NOLINTNEXTLINE(google-default-arguments)
ParseClassStatement(StatementParsingFlags flags,ir::ClassDefinitionModifiers modifiers,ir::ModifierFlags modFlags)333 ir::ClassDeclaration *ETSParser::ParseClassStatement([[maybe_unused]] StatementParsingFlags flags,
334                                                      ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags)
335 {
336     return ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED |
337                                      ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL,
338                                  modFlags);
339 }
340 
341 // NOLINTNEXTLINE(google-default-arguments)
ParseStructStatement(StatementParsingFlags flags,ir::ClassDefinitionModifiers modifiers,ir::ModifierFlags modFlags)342 ir::ETSStructDeclaration *ETSParser::ParseStructStatement([[maybe_unused]] StatementParsingFlags flags,
343                                                           [[maybe_unused]] ir::ClassDefinitionModifiers modifiers,
344                                                           [[maybe_unused]] ir::ModifierFlags modFlags)
345 {
346     ThrowSyntaxError("Illegal start of expression", Lexer()->GetToken().Start());
347 }
348 
349 }  // namespace ark::es2panda::parser
350