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
124 // NOLINTNEXTLINE(google-default-arguments)
ParseEnumDeclaration(bool isConst,bool isStatic)125 ir::Statement *ETSParser::ParseEnumDeclaration(bool isConst, bool isStatic)
126 {
127 ASSERT(Lexer()->GetToken().Type() == lexer::TokenType::KEYW_ENUM);
128
129 lexer::SourcePosition enumStart = Lexer()->GetToken().Start();
130 Lexer()->NextToken(); // eat enum keyword
131
132 auto *key = ExpectIdentifier(false, true);
133
134 auto *declNode = ParseEnumMembers(key, enumStart, isConst, isStatic);
135
136 return declNode;
137 }
138
ParsePotentialConstEnum(VariableParsingFlags flags)139 ir::Statement *ETSParser::ParsePotentialConstEnum(VariableParsingFlags flags)
140 {
141 if ((flags & VariableParsingFlags::CONST) == 0) {
142 ThrowSyntaxError("Variable declaration expected.");
143 }
144
145 return ParseEnumDeclaration(true);
146 }
147
148 // NOLINTBEGIN(cert-err58-cpp)
149 static std::string const INVALID_ENUM_TYPE = "Invalid enum initialization type"s;
150 static std::string const INVALID_ENUM_VALUE = "Invalid enum initialization value"s;
151 static std::string const MISSING_COMMA_IN_ENUM = "Missing comma between enum constants"s;
152 static std::string const TRAILING_COMMA_IN_ENUM = "Trailing comma is not allowed in enum constant list"s;
153 // NOLINTEND(cert-err58-cpp)
154
155 // Helper for ETSParser::ParseEnumMembers()
IsStringEnum()156 bool ETSParser::IsStringEnum()
157 {
158 // Get the underlying type of enum (number or string). It is defined from the first element ONLY!
159 Lexer()->NextToken();
160 auto tokenType = Lexer()->GetToken().Type();
161 while (tokenType != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE && tokenType != lexer::TokenType::PUNCTUATOR_COMMA) {
162 if (tokenType == lexer::TokenType::PUNCTUATOR_SUBSTITUTION) {
163 Lexer()->NextToken();
164 if (Lexer()->GetToken().Type() == lexer::TokenType::LITERAL_STRING) {
165 return true;
166 }
167 }
168 Lexer()->NextToken();
169 tokenType = Lexer()->GetToken().Type();
170 }
171 return false;
172 }
173
ParseEnumMembers(ir::Identifier * const key,const lexer::SourcePosition & enumStart,const bool isConst,const bool isStatic)174 ir::TSEnumDeclaration *ETSParser::ParseEnumMembers(ir::Identifier *const key, const lexer::SourcePosition &enumStart,
175 const bool isConst, const bool isStatic)
176 {
177 if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_BRACE) {
178 LogExpectedToken(lexer::TokenType::PUNCTUATOR_LEFT_BRACE);
179 }
180
181 Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); // eat '{'
182
183 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) {
184 ThrowSyntaxError("An enum must have at least one enum constant");
185 }
186
187 // Get the underlying type of enum (number or string). It is defined from the first element ONLY!
188 auto const pos = Lexer()->Save();
189 const bool stringTypeEnum = IsStringEnum();
190 Lexer()->Rewind(pos);
191
192 ArenaVector<ir::AstNode *> members(Allocator()->Adapter());
193
194 if (stringTypeEnum) {
195 ParseStringEnum(members);
196 } else {
197 ParseNumberEnum(members);
198 }
199
200 auto *const enumDeclaration = AllocNode<ir::TSEnumDeclaration>(
201 Allocator(), key, std::move(members),
202 ir::TSEnumDeclaration::ConstructorFlags {isConst, isStatic, InAmbientContext()});
203 enumDeclaration->SetRange({enumStart, Lexer()->GetToken().End()});
204 if (InAmbientContext()) {
205 enumDeclaration->AddModifier(ir::ModifierFlags::DECLARE);
206 }
207
208 Lexer()->NextToken(); // eat '}'
209
210 return enumDeclaration;
211 }
212
ParseNumberEnumEnd()213 bool ETSParser::ParseNumberEnumEnd()
214 {
215 bool isBreak = false;
216 if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_COMMA) {
217 // enum5.sts
218 LogSyntaxError(MISSING_COMMA_IN_ENUM);
219 if (lexer::Token::IsPunctuatorToken((Lexer()->GetToken().Type()))) {
220 /* enum Direction {
221 Left = -1;
222 Right = 1",
223 }*/
224 Lexer()->GetToken().SetTokenType(lexer::TokenType::PUNCTUATOR_COMMA);
225 Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); // eat ','
226 }
227 /* in another case just skip the token
228 enum Direction {
229 Left = -1
230 Right = 1,
231 }
232 */
233 } else {
234 Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); // eat ','
235 }
236
237 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) {
238 isBreak = true;
239 }
240 return isBreak;
241 }
242
ParseNumberEnumHelper()243 bool ETSParser::ParseNumberEnumHelper()
244 {
245 bool minusSign = false;
246 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_PLUS) {
247 Lexer()->NextToken();
248 } else if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_MINUS) {
249 minusSign = true;
250 Lexer()->NextToken();
251 }
252
253 if (Lexer()->GetToken().Type() != lexer::TokenType::LITERAL_NUMBER) {
254 // enum15.sts; will be zero by default
255 LogSyntaxError(INVALID_ENUM_TYPE);
256 Lexer()->GetToken().SetTokenType(lexer::TokenType::LITERAL_NUMBER);
257 Lexer()->GetToken().SetTokenStr(ERROR_LITERAL);
258 }
259 return minusSign;
260 }
261
ParseNumberEnum(ArenaVector<ir::AstNode * > & members)262 void ETSParser::ParseNumberEnum(ArenaVector<ir::AstNode *> &members)
263 {
264 checker::ETSIntEnumType::ValueType currentValue {};
265
266 // Lambda to parse enum member (maybe with initializer)
267 auto const parseMember = [this, &members, ¤tValue]() {
268 auto *const ident = ExpectIdentifier(false, true);
269
270 ir::NumberLiteral *ordinal;
271 lexer::SourcePosition endLoc;
272
273 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SUBSTITUTION) {
274 // Case when user explicitly set the value for enumeration constant
275
276 bool minusSign = false;
277
278 Lexer()->NextToken();
279 minusSign = ParseNumberEnumHelper();
280
281 ordinal = ParseNumberLiteral()->AsNumberLiteral();
282 if (minusSign) {
283 ordinal->Number().Negate();
284 }
285 if (!ordinal->Number().CanGetValue<checker::ETSIntEnumType::ValueType>()) {
286 ThrowSyntaxError(INVALID_ENUM_VALUE);
287 }
288
289 currentValue = ordinal->Number().GetValue<checker::ETSIntEnumType::ValueType>();
290
291 endLoc = ordinal->End();
292 } else {
293 // Default enumeration constant value. Equal to 0 for the first item and = previous_value + 1 for all
294 // the others.
295
296 ordinal = AllocNode<ir::NumberLiteral>(lexer::Number(currentValue));
297
298 endLoc = ident->End();
299 }
300
301 auto *const member = AllocNode<ir::TSEnumMember>(ident, ordinal);
302 member->SetRange({ident->Start(), endLoc});
303 members.emplace_back(member);
304
305 ++currentValue;
306 };
307
308 parseMember();
309
310 while (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) {
311 if (ParseNumberEnumEnd()) {
312 break;
313 }
314
315 parseMember();
316 }
317 }
318
ParseStringEnum(ArenaVector<ir::AstNode * > & members)319 void ETSParser::ParseStringEnum(ArenaVector<ir::AstNode *> &members)
320 {
321 // Lambda to parse enum member (maybe with initializer)
322 auto const parseMember = [this, &members]() {
323 auto *const ident = ExpectIdentifier();
324
325 ir::StringLiteral *itemValue;
326
327 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SUBSTITUTION) {
328 // Case when user explicitly set the value for enumeration constant
329
330 Lexer()->NextToken();
331 if (Lexer()->GetToken().Type() != lexer::TokenType::LITERAL_STRING) {
332 // enum24.sts; will be set as "0" by default
333 LogSyntaxError(INVALID_ENUM_TYPE);
334 Lexer()->GetToken().SetTokenType(lexer::TokenType::LITERAL_STRING);
335 Lexer()->GetToken().SetTokenStr(ERROR_LITERAL);
336 }
337
338 itemValue = ParseStringLiteral();
339 } else {
340 // Default item value is not allowed for string type enumerations!
341 ThrowSyntaxError("All items of string-type enumeration should be explicitly initialized.");
342 }
343
344 auto *const member = AllocNode<ir::TSEnumMember>(ident, itemValue);
345 member->SetRange({ident->Start(), itemValue->End()});
346 members.emplace_back(member);
347 };
348
349 parseMember();
350
351 while (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) {
352 if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_COMMA) {
353 // enum5.sts
354 LogSyntaxError(MISSING_COMMA_IN_ENUM);
355 if (lexer::Token::IsPunctuatorToken((Lexer()->GetToken().Type()))) {
356 /* enum Direction {
357 Left = "LEFT";
358 Right = "RIGHT",
359 }*/
360 Lexer()->GetToken().SetTokenType(lexer::TokenType::PUNCTUATOR_COMMA);
361 Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); // eat ','
362 }
363 /* in another case just skip the token
364 enum Direction {
365 Left = "LEFT"
366 Right = "RIGHT",
367 }
368 */
369 } else {
370 Lexer()->NextToken(lexer::NextTokenFlags::KEYWORD_TO_IDENT); // eat ','
371 }
372
373 if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) {
374 ThrowSyntaxError(TRAILING_COMMA_IN_ENUM);
375 }
376
377 parseMember();
378 }
379 }
380
381 } // namespace ark::es2panda::parser
382