1 /**
2 * Copyright (c) 2021 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 #ifndef ES2PANDA_PARSER_CORE_PARSER_IMPL_H
17 #define ES2PANDA_PARSER_CORE_PARSER_IMPL_H
18
19 #include <binder/binder.h>
20 #include <es2panda.h>
21 #include <ir/astNode.h>
22 #include <ir/base/methodDefinition.h>
23 #include <lexer/token/sourceLocation.h>
24 #include <macros.h>
25 #include <mem/arena_allocator.h>
26 #include <parser/context/parserContext.h>
27 #include <parser/module/sourceTextModuleRecord.h>
28 #include <parser/parserFlags.h>
29 #include <parser/program/program.h>
30 #include <util/enumbitops.h>
31 #include <util/ustring.h>
32
33 #include <memory>
34 #include <sstream>
35 #include <unordered_map>
36 #include <unordered_set>
37
38 namespace panda::es2panda::lexer {
39 enum class TokenFlags;
40 enum class TokenType;
41 class LexerPosition;
42 class Token;
43 class Lexer;
44 } // namespace panda::es2panda::lexer
45
46 namespace panda::es2panda::ir {
47 class ArrowFunctionExpression;
48 class AstNode;
49 class BlockStatement;
50 class BreakStatement;
51 class CallExpression;
52 class ClassDeclaration;
53 class ClassDefinition;
54 class ContinueStatement;
55 class DoWhileStatement;
56 class ExportAllDeclaration;
57 class ExportDefaultDeclaration;
58 class ExportNamedDeclaration;
59 class ExportNamedDeclaration;
60 class Expression;
61 class FunctionDeclaration;
62 class FunctionExpression;
63 class Identifier;
64 class IfStatement;
65 class ImportDeclaration;
66 class LabelledStatement;
67 class NewExpression;
68 class ObjectExpression;
69 class ReturnStatement;
70 class ScriptFunction;
71 class SequenceExpression;
72 class SpreadElement;
73 class Statement;
74 class StringLiteral;
75 class SwitchCaseStatement;
76 class SwitchStatement;
77 class TSArrayType;
78 class TSEnumDeclaration;
79 class TSFunctionType;
80 class TSInterfaceDeclaration;
81 class TSIntersectionType;
82 class TSTupleType;
83 class TSTypeAliasDeclaration;
84 class TSUnionType;
85 class TSImportType;
86 class TemplateLiteral;
87 class ThrowStatement;
88 class TryStatement;
89 class VariableDeclaration;
90 class WhileStatement;
91 class WithStatement;
92 class TSTypeParameter;
93 class TSTypeParameterDeclaration;
94 class MemberExpression;
95 class MethodDefinition;
96 class TSTypeReference;
97 class TSMappedType;
98 class TSTypePredicate;
99 class Decorator;
100 class TSIndexSignature;
101 class Property;
102 class TSTypeParameterInstantiation;
103 class TSParameterProperty;
104 class TSTypeAssertion;
105 class TSAsExpression;
106 class TSSatisfiesExpression;
107 class YieldExpression;
108 class MetaProperty;
109 class TSModuleDeclaration;
110 class TSImportEqualsDeclaration;
111 class TSModuleBlock;
112 class EmptyStatement;
113 class DebuggerStatement;
114 class CatchClause;
115 class VariableDeclarator;
116
117 enum class PropertyKind;
118 enum class TSTupleKind;
119 enum class MethodDefinitionKind;
120 enum class ModifierFlags;
121 } // namespace panda::es2panda::ir
122
123 namespace panda::es2panda::parser {
124
125 class Program;
126 class ParserContext;
127
128 class ClassElmentDescriptor {
129 public:
130 ir::MethodDefinitionKind methodKind {};
131 ParserStatus newStatus {};
132 ir::ModifierFlags modifiers {};
133 lexer::SourcePosition methodStart {};
134 lexer::SourcePosition propStart {};
135 bool isPrivateIdent {};
136 bool hasSuperClass {};
137 bool isGenerator {};
138 bool invalidComputedProperty {};
139 bool isComputed {};
140 bool isIndexSignature {};
141 bool classMethod {};
142 bool classField {};
143 };
144
145 class ArrowFunctionDescriptor {
146 public:
ArrowFunctionDescriptor(ArenaVector<ir::Expression * > && p,binder::FunctionParamScope * ps,lexer::SourcePosition sl,ParserStatus ns)147 explicit ArrowFunctionDescriptor(ArenaVector<ir::Expression *> &&p, binder::FunctionParamScope *ps,
148 lexer::SourcePosition sl, ParserStatus ns)
149 : params(p), paramScope(ps), startLoc(sl), newStatus(ns)
150 {
151 }
152
153 ArenaVector<ir::Expression *> params;
154 binder::FunctionParamScope *paramScope;
155 lexer::SourcePosition startLoc;
156 ParserStatus newStatus;
157 };
158
159 enum class TypeAnnotationParsingOptions {
160 NO_OPTS = 0,
161 IN_UNION = 1 << 0,
162 ALLOW_CONST = 1 << 1,
163 IN_INTERSECTION = 1 << 2,
164 RESTRICT_EXTENDS = 1 << 3,
165 THROW_ERROR = 1 << 4,
166 CAN_BE_TS_TYPE_PREDICATE = 1 << 5,
167 BREAK_AT_NEW_LINE = 1 << 6,
168 IN_MODIFIER = 1 << 7,
169 };
170
DEFINE_BITOPS(TypeAnnotationParsingOptions)171 DEFINE_BITOPS(TypeAnnotationParsingOptions)
172
173 class ArrowFunctionContext;
174
175 enum class PrivateGetterSetterType {
176 GETTER = 0,
177 SETTER = 1 << 0,
178 STATIC = 1 << 1,
179 };
180
DEFINE_BITOPS(PrivateGetterSetterType)181 DEFINE_BITOPS(PrivateGetterSetterType)
182
183 class ParserImpl {
184 public:
185 explicit ParserImpl(es2panda::ScriptExtension extension);
186 NO_COPY_SEMANTIC(ParserImpl);
187 NO_MOVE_SEMANTIC(ParserImpl);
188 ~ParserImpl() = default;
189
190 Program Parse(const std::string &fileName, const std::string &source, const std::string &recordName,
191 const CompilerOptions &options, ScriptKind kind);
192
193 ScriptExtension Extension() const;
194
195 void AddPatchFixHelper(util::PatchFix *patchFixHelper);
196
197 ArenaAllocator *Allocator() const
198 {
199 return program_.Allocator();
200 }
201 bool IsDtsFile() const;
202
203 private:
204 bool IsStartOfMappedType() const;
205 bool IsStartOfTsTypePredicate() const;
206 bool IsStartOfAbstractConstructorType() const;
207
208 bool CurrentTokenIsModifier(char32_t nextCp) const;
209 [[noreturn]] void ThrowParameterModifierError(ir::ModifierFlags status) const;
210 [[noreturn]] void ThrowSyntaxError(std::string_view errorMessage) const;
211 [[noreturn]] void ThrowSyntaxError(std::initializer_list<std::string_view> list) const;
212 [[noreturn]] void ThrowSyntaxError(std::initializer_list<std::string_view> list,
213 const lexer::SourcePosition &pos) const;
214
215 [[noreturn]] void ThrowSyntaxError(std::string_view errorMessage, const lexer::SourcePosition &pos) const;
216
217 template <typename T, typename... Args>
218 T *AllocNode(Args &&... args)
219 {
220 auto ret = program_.Allocator()->New<T>(std::forward<Args>(args)...);
221 if (ret == nullptr) {
222 throw Error(ErrorType::GENERIC, "Unsuccessful allocation during parsing");
223 }
224 return ret;
225 }
226
227 [[nodiscard]] std::unique_ptr<lexer::Lexer> InitLexer(const std::string &fileName, const std::string &source);
228 void ParseScript();
229 void ParseModule();
230
231 /*
232 * Transform the commonjs module's AST by wrap the sourceCode & use Reflect.apply to invoke this wrapper with [this]
233 * pointing to [exports] object
234 *
235 * Reflect.apply(function (exports, require, module, __filename, __dirname) {
236 * [SourceCode]
237 * }, exports, [exports, require, module, __filename, __dirname]);
238 */
239 void ParseCommonjs();
240 void AddCommonjsParams(ArenaVector<ir::Expression *> ¶ms);
241 void AddReflectApplyArgs(ArenaVector<ir::Expression *> &args, ir::FunctionExpression *wrapper);
242 void ParseProgram(ScriptKind kind);
243 bool CheckTopStatementsForRequiredDeclare(const ArenaVector<ir::Statement *> &statements);
244 static ExpressionParseFlags CarryExpressionParserFlag(ExpressionParseFlags origin, ExpressionParseFlags carry);
245 static ExpressionParseFlags CarryPatternFlags(ExpressionParseFlags flags);
246 static ExpressionParseFlags CarryAllowTsParamAndPatternFlags(ExpressionParseFlags flags);
247 bool CurrentIsBasicType();
248 bool CurrentLiteralIsBasicType();
249 static bool CheckTypeNameIsReserved(const util::StringView ¶mName);
250 static bool IsPropertyKeysAreSame(const ir::Expression *exp1, const ir::Expression *exp2);
251 static bool IsMemberExpressionsAreSame(const ir::MemberExpression *mExp1, const ir::MemberExpression *mExp2);
252 static bool IsMethodDefinitionsAreSame(const ir::MethodDefinition *property, ir::MethodDefinition *overload);
253 ir::TSTypeReference *ParseTsConstExpression();
254 ir::Expression *ParseTsTypeOperatorOrTypeReference(bool throwError);
255 ir::Expression *ParseTsIdentifierReference(TypeAnnotationParsingOptions options);
256 ir::Expression *ParseTsBasicType(TypeAnnotationParsingOptions options);
257 ir::TSIntersectionType *ParseTsIntersectionType(ir::Expression *type, bool inUnion, bool restrictExtends);
258 ir::TSUnionType *ParseTsUnionType(ir::Expression *type, bool restrictExtends);
259 ir::Expression *ParseTsParenthesizedOrFunctionType(ir::Expression *typeAnnotation, bool throwError);
260 ir::TSArrayType *ParseTsArrayType(ir::Expression *elementType);
261 bool IsTsFunctionType();
262 ir::Expression *ParseTsFunctionType(lexer::SourcePosition startLoc, bool isConstructionType, bool throwError,
263 bool abstractConstructor = false);
264 ir::TSTypeParameter *ParseTsMappedTypeParameter();
265 ir::MappedOption ParseMappedOption(lexer::TokenType tokenType);
266 ir::TSMappedType *ParseTsMappedType();
267 ir::TSTypePredicate *ParseTsTypePredicate();
268 void ParseTsTypeLiteralOrInterfaceKeyModifiers(bool *isGetAccessor, bool *isSetAccessor);
269 ir::Expression *ParseTsTypeLiteralOrInterfaceKey(bool *computed, bool *signature, bool *isIndexSignature);
270 void ValidateIndexSignatureParameterType(ir::Expression *typeAnnotation);
271 ir::Expression *ParseTsConditionalType(ir::Expression *checkType, bool restrictExtends);
272 ir::Expression *ParseTsTypeLiteralOrInterfaceMember();
273 ArenaVector<ir::Expression *> ParseTsTypeLiteralOrInterface();
274 ir::Expression *ParseTsThisType(bool throwError);
275 ir::Expression *ParseTsIndexAccessType(ir::Expression *typeName, bool throwError);
276 ir::Expression *ParseTsQualifiedReference(ir::Expression *typeName);
277 ir::Expression *ParseTsTypeReferenceOrQuery(TypeAnnotationParsingOptions options, bool parseQuery = false);
278 bool IsTSNamedTupleMember();
279 void HandleRestType(ir::AstNodeType elementType, bool *hasRestType) const;
280 ir::Expression *ParseTsTupleElement(ir::TSTupleKind *kind, bool *seenOptional, bool *hasRestType);
281 ir::TSTupleType *ParseTsTupleType();
282 ir::TSImportType *ParseTsImportType(const lexer::SourcePosition &startLoc, bool isTypeof = false);
283 ir::Expression *ParseTsTypeAnnotation(TypeAnnotationParsingOptions *options);
284 ir::Expression *ParseTsTypeLiteralOrTsMappedType(ir::Expression *typeAnnotation);
285 ir::Expression *ParseTsTypeReferenceOrTsTypePredicate(ir::Expression *typeAnnotation, bool canBeTsTypePredicate,
286 bool throwError);
287 ir::Expression *ParseTsThisTypeOrTsTypePredicate(ir::Expression *typeAnnotation, bool canBeTsTypePredicate,
288 bool throwError);
289 ir::Expression *ParseTsTemplateLiteralType(bool throwError);
290 ir::Expression *ParseTsTypeAnnotationElement(ir::Expression *typeAnnotation, TypeAnnotationParsingOptions *options);
291 ir::ModifierFlags ParseModifiers();
292
293 void ThrowIfPrivateIdent(ClassElmentDescriptor *desc, const char *msg);
294 void ValidateClassKey(ClassElmentDescriptor *desc, bool isDeclare);
295
296 void ValidateClassMethodStart(ClassElmentDescriptor *desc, ir::Expression *typeAnnotation);
297 ir::Expression *ParseClassKey(ClassElmentDescriptor *desc, bool isDeclare);
298
299 void ValidateClassSetter(ClassElmentDescriptor *desc, const ArenaVector<ir::Statement *> &properties,
300 ir::Expression *propName, ir::ScriptFunction *func, bool hasDecorator,
301 lexer::SourcePosition errorInfo);
302 void ValidateClassGetter(ClassElmentDescriptor *desc, const ArenaVector<ir::Statement *> &properties,
303 ir::Expression *propName, ir::ScriptFunction *func, bool hasDecorator,
304 lexer::SourcePosition errorInfo);
305 void ValidatePrivateProperty(ir::Statement *stmt, std::unordered_set<util::StringView> &privateNames,
306 std::unordered_map<util::StringView, PrivateGetterSetterType> &unusedGetterSetterPairs);
307 ir::MethodDefinition *ParseClassMethod(ClassElmentDescriptor *desc, const ArenaVector<ir::Statement *> &properties,
308 ir::Expression *propName, lexer::SourcePosition *propEnd,
309 ArenaVector<ir::Decorator *> &&decorators, bool isDeclare);
310 ir::ClassStaticBlock *ParseStaticBlock(ClassElmentDescriptor *desc);
311 ir::Statement *ParseClassProperty(ClassElmentDescriptor *desc, const ArenaVector<ir::Statement *> &properties,
312 ir::Expression *propName, ir::Expression *typeAnnotation,
313 ArenaVector<ir::Decorator *> &&decorators, bool isDeclare,
314 std::pair<binder::FunctionScope *, binder::FunctionScope *> implicitScopes);
315 void ParseClassKeyModifiers(ClassElmentDescriptor *desc);
316 void CheckClassGeneratorMethod(ClassElmentDescriptor *desc);
317 void CheckClassPrivateIdentifier(ClassElmentDescriptor *desc);
318 void CheckFieldKey(ir::Expression *propName);
319 ir::Expression *ParseClassKeyAnnotation();
320 ir::Decorator *ParseDecorator();
321 ArenaVector<ir::Decorator *> ParseDecorators();
322 ir::Statement *ParseClassElement(const ArenaVector<ir::Statement *> &properties,
323 ArenaVector<ir::TSIndexSignature *> *indexSignatures, bool hasSuperClass,
324 bool isDeclare, bool isAbstractClass, bool isExtendsFromNull,
325 std::pair<binder::FunctionScope *, binder::FunctionScope *> implicitScopes);
326 ir::MethodDefinition *CreateImplicitMethod(ir::Expression *superClass, bool hasSuperClass,
327 ir::ScriptFunctionFlags funcFlag, bool isDeclare = false);
328 ir::MethodDefinition *CheckClassMethodOverload(ir::Statement *property, ir::MethodDefinition **ctor, bool isDeclare,
329 lexer::SourcePosition errorInfo, ir::MethodDefinition *lastOverload,
330 bool implExists, bool isAbstract = false);
331 ir::Identifier *SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl);
332 ir::ClassDefinition *ParseClassDefinition(bool isDeclaration, bool idRequired = true, bool isDeclare = false,
333 bool isAbstract = false);
334 ir::Expression *ParseSuperClass(bool isDeclare, bool *hasSuperClass, bool *isExtendsFromNull);
335 ArenaVector<ir::TSClassImplements *> ParseTSClassImplements(bool isDeclare);
336 void ValidateClassConstructor(const ir::MethodDefinition *ctor,
337 const ArenaVector<ir::Statement *> &properties,
338 bool isDeclare, bool hasConstructorFuncBody,
339 bool hasSuperClass, bool isExtendsFromNull);
340 void FindSuperCall(const ir::AstNode *parent, bool *hasSuperCall);
341 void FindSuperCallInCtorChildNode(const ir::AstNode *childNode, bool *hasSuperCall);
342 bool SuperCallShouldBeRootLevel(const ir::MethodDefinition *ctor, const ArenaVector<ir::Statement *> &properties);
343 void ValidateSuperCallLocation(const ir::MethodDefinition *ctor, bool superCallShouldBeRootLevel);
344 void FindThisOrSuperReference(const ir::AstNode *parent, bool *hasThisOrSuperReference);
345 void FindThisOrSuperReferenceInChildNode(const ir::AstNode *childNode, bool *hasThisOrSuperReference);
346 void ValidateAccessor(ExpressionParseFlags flags, lexer::TokenFlags currentTokenFlags);
347 void CheckPropertyKeyAsycModifier(ParserStatus *methodStatus);
348 ir::Property *ParseShorthandProperty(const lexer::LexerPosition *startPos);
349 void ParseGeneratorPropertyModifier(ExpressionParseFlags flags, ParserStatus *methodStatus);
350 bool ParsePropertyModifiers(ExpressionParseFlags flags, ir::PropertyKind *propertyKind, ParserStatus *methodStatus);
351 ir::Expression *ParsePropertyKey(ExpressionParseFlags flags);
352 ir::Expression *ParsePropertyValue(const ir::PropertyKind *propertyKind, const ParserStatus *methodStatus,
353 ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
354 bool ParsePropertyEnd();
355
356 ir::Expression *ParsePostfixTypeOrHigher(ir::Expression *typeAnnotation, TypeAnnotationParsingOptions *options);
357 ir::Expression *TryParseConstraintOfInferType(TypeAnnotationParsingOptions *options);
358 ir::Expression *ParsePropertyDefinition(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
359 bool CheckOutIsIdentInTypeParameter();
360 ir::TSTypeParameter *ParseTsTypeParameter(bool throwError, bool addBinding = false, bool isAllowInOut = false);
361 ir::TSTypeParameterDeclaration *ParseTsTypeParameterDeclaration(bool throwError = true, bool isAllowInOut = false);
362 ir::TSTypeParameterInstantiation *ParseTsTypeParameterInstantiation(bool throwError = true);
363 ir::ScriptFunction *ParseFunction(ParserStatus newStatus = ParserStatus::NO_OPTS,
364 bool isDeclare = false,
365 ArenaVector<ir::ParamDecorators> *paramDecorators = nullptr);
366 void ValidateFunctionParam(const ArenaVector<ir::Expression *> ¶ms, const ir::Expression *parameter,
367 bool *seenOptional);
368 void ValidateTsFunctionOverloadParams(const ArenaVector<ir::Expression *> ¶ms);
369 void CheckAccessorPair(const ArenaVector<ir::Statement *> &properties, const ir::Expression *propName,
370 ir::MethodDefinitionKind methodKind, ir::ModifierFlags access, bool hasDecorator,
371 lexer::SourcePosition errorInfo);
372 ArenaVector<ir::Expression *> ParseFunctionParams(bool isDeclare = false,
373 ArenaVector<ir::ParamDecorators> *paramDecorators = nullptr);
374 ir::SpreadElement *ParseSpreadElement(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
375 ir::TSParameterProperty *CreateTsParameterProperty(ir::Expression *parameter, ir::ModifierFlags modifiers);
376 ir::Expression *ParseFunctionParameter(bool isDeclare);
377 void CreateTSVariableForProperty(ir::AstNode *node, const ir::Expression *key, binder::VariableFlags flags);
378 void CheckObjectTypeForDuplicatedProperties(ir::Expression *member, ArenaVector<ir::Expression *> const &members);
379
380 // ExpressionParser.Cpp
381
382 ir::Expression *ParseExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
383 ir::ArrowFunctionExpression *ParseTsGenericArrowFunction();
384 ir::TSTypeAssertion *ParseTsTypeAssertion(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
385 ir::TSAsExpression *ParseTsAsExpression(ir::Expression *expr, ExpressionParseFlags flags);
386 ir::TSSatisfiesExpression *ParseTsSatisfiesExpression(ir::Expression *expr);
387 ir::Expression *ParseArrayExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
388 ir::YieldExpression *ParseYieldExpression();
389 ir::Expression *ParsePotentialExpressionSequence(ir::Expression *expr, ExpressionParseFlags flags);
390 ParserStatus ValidateArrowParameter(ir::Expression *expr);
391
392 ArrowFunctionDescriptor ConvertToArrowParameter(ir::Expression *expr, bool isAsync,
393 binder::FunctionParamScope *paramScope);
394 ir::ArrowFunctionExpression *ParseArrowFunctionExpressionBody(ArrowFunctionContext *arrowFunctionContext,
395 binder::FunctionScope *functionScope,
396 ArrowFunctionDescriptor *desc,
397 ir::TSTypeParameterDeclaration *typeParamDecl,
398 ir::Expression *returnTypeAnnotation);
399 ir::ArrowFunctionExpression *ParseArrowFunctionExpression(ir::Expression *expr,
400 ir::TSTypeParameterDeclaration *typeParamDecl,
401 ir::Expression *returnTypeAnnotation, bool isAsync);
402 ir::Expression *ParseCoverParenthesizedExpressionAndArrowParameterList();
403 ir::Expression *ParseKeywordExpression();
404 ir::Expression *ParseBinaryExpression(ir::Expression *left);
405 ir::CallExpression *ParseCallExpression(ir::Expression *callee, bool isOptionalChain = false, bool isAsync = false);
406 ir::ArrowFunctionExpression *ParsePotentialArrowExpression(ir::Expression **returnExpression,
407 const lexer::SourcePosition &startLoc,
408 bool ignoreCallExpression);
409
410 void ValidateUpdateExpression(ir::Expression *returnExpression, bool isChainExpression);
411 bool IsGenericInstantiation();
412 bool ParsePotentialTsGenericFunctionCall(ir::Expression **returnExpression, const lexer::SourcePosition &startLoc,
413 bool ignoreCallExpression);
414 ir::Expression *ParsePostPrimaryExpression(ir::Expression *primaryExpr, lexer::SourcePosition startLoc,
415 bool ignoreCallExpression, bool *isChainExpression);
416 ir::Expression *ParseMemberExpression(bool ignoreCallExpression = false,
417 ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
418 ir::ObjectExpression *ParseObjectExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
419 ir::SequenceExpression *ParseSequenceExpression(ir::Expression *startExpr, bool acceptRest = false,
420 bool acceptTsParam = false, bool acceptPattern = false);
421 ir::Expression *ParseUnaryOrPrefixUpdateExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
422 ir::Expression *ParseLeftHandSideExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
423 ir::MetaProperty *ParsePotentialNewTarget();
424 void CheckInvalidDestructuring(const ir::AstNode *object) const;
425 void ValidateParenthesizedExpression(ir::Expression *lhsExpression);
426 ir::Expression *ParseAssignmentExpression(ir::Expression *lhsExpression,
427 ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
428 ir::Expression *ParsePrimaryExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
429 ir::NewExpression *ParseNewExpression();
430 void ParsePotentialTsFunctionParameter(ExpressionParseFlags flags, ir::Expression *returnNode,
431 bool isDeclare = false);
432 ir::Expression *ParsePatternElement(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS,
433 bool allowDefault = true, bool isDeclare = false);
434 ir::TemplateLiteral *ParseTemplateLiteral(bool isTaggedTemplate = false);
435 ir::Expression *ParseImportExpression();
436 ir::ObjectExpression *ParseImportAssertionForDynamicImport();
437 void ValidateImportAssertionForDynamicImport(ir::ObjectExpression *importAssertion);
438 ir::AssertClause *ParseAssertClause();
439 ir::AssertEntry *ParseAssertEntry();
440 ir::FunctionExpression *ParseFunctionExpression(ParserStatus newStatus = ParserStatus::NO_OPTS);
441 ir::Expression *ParseOptionalChain(ir::Expression *leftSideExpr);
442 ir::Expression *ParseOptionalMemberExpression(ir::Expression *object);
443 void ParseNameSpaceImport(ArenaVector<ir::AstNode *> *specifiers, bool isType);
444 ir::Identifier *ParseNamedImport(const lexer::Token &importedToken);
445 binder::Decl *AddImportDecl(bool isType,
446 util::StringView name,
447 lexer::SourcePosition startPos,
448 binder::DeclarationFlags flag);
449
450 ir::StringLiteral *ParseFromClause(bool requireFrom = true);
451 void ParseNamedImportSpecifiers(ArenaVector<ir::AstNode *> *specifiers, bool isType);
452 ir::Expression *ParseModuleReference();
453 ir::AstNode *ParseImportDefaultSpecifier(ArenaVector<ir::AstNode *> *specifiers, bool isType);
454 ir::AstNode *ParseImportSpecifiers(ArenaVector<ir::AstNode *> *specifiers, bool isType);
455 void ValidateAssignmentTarget(ExpressionParseFlags flags, ir::Expression *node);
456 void ValidateLvalueAssignmentTarget(ir::Expression *node) const;
457 void ValidateArrowParameterBindings(const ir::Expression *node);
458
459 ir::ExportDefaultDeclaration *ParseExportDefaultDeclaration(const lexer::SourcePosition &startLoc,
460 ArenaVector<ir::Decorator *> decorators,
461 bool isExportEquals = false);
462 ir::ExportAllDeclaration *ParseExportAllDeclaration(const lexer::SourcePosition &startLoc);
463 ir::ExportNamedDeclaration *ParseExportNamedSpecifiers(const lexer::SourcePosition &startLoc, bool isType);
464 ir::ExportNamedDeclaration *ParseNamedExportDeclaration(const lexer::SourcePosition &startLoc,
465 ArenaVector<ir::Decorator *> &&decorators);
466 ir::Identifier *ParseNamedExport(const lexer::Token &exportedToken);
467 void CheckStrictReservedWord() const;
468 ir::PrivateIdentifier *ParsePrivateIdentifier();
469
470 // Discard the DISALLOW_CONDITIONAL_TYPES in current status to call function.
471 template<class Function, typename... Args>
472 ir::Expression *DoOutsideOfDisallowConditinalTypesContext(Function func, Args &&... args);
473
474 // Add the DISALLOW_CONDITIONAL_TYPES to current status to call function.
475 template<typename Function, typename... Args>
476 ir::Expression *DoInsideOfDisallowConditinalTypesContext(Function func, Args &&... args);
477
478 bool InDisallowConditionalTypesContext();
479 bool InContext(ParserStatus status);
480 void AddFlagToStatus(ParserStatus status);
481 void RemoveFlagToStatus(ParserStatus status);
482 // StatementParser.Cpp
483
484 void ConsumeSemicolon(ir::Statement *statement);
485 void CheckFunctionDeclaration(StatementParsingFlags flags);
486
487 void CheckLabelledFunction(const ir::Statement *node);
488 bool CheckDeclare();
489
490 bool IsLabelFollowedByIterationStatement();
491
492 void AddImportEntryItem(const ir::StringLiteral *source, const ArenaVector<ir::AstNode *> *specifiers, bool isType);
493 void AddImportEntryItemForImportSpecifier(const ir::StringLiteral *source, const ir::AstNode *specifier);
494 void AddImportEntryItemForImportDefaultOrNamespaceSpecifier(const ir::StringLiteral *source,
495 const ir::AstNode *specifier, bool isType);
496 void AddExportNamedEntryItem(const ArenaVector<ir::ExportSpecifier *> &specifiers,
497 const ir::StringLiteral *source, bool isType);
498 void AddExportStarEntryItem(const lexer::SourcePosition &startLoc, const ir::StringLiteral *source,
499 const ir::Identifier *exported);
500 void AddExportDefaultEntryItem(const ir::AstNode *declNode);
501 void AddExportLocalEntryItem(const ir::Statement *declNode, bool isTsModule);
502 void AddTsTypeExportLocalEntryItem(const ir::Statement *declNode, bool isTsModule,
503 binder::TSModuleScope *tsModuleScope);
504 parser::SourceTextModuleRecord *GetSourceTextModuleRecord();
505 parser::SourceTextModuleRecord *GetSourceTextTypeModuleRecord();
506
507 bool ParseDirective(ArenaVector<ir::Statement *> *statements);
508 void ParseDirectivePrologue(ArenaVector<ir::Statement *> *statements);
509 ArenaVector<ir::Statement *> ParseStatementList(StatementParsingFlags flags = StatementParsingFlags::ALLOW_LEXICAL);
510 bool IsTsDeclarationStatement() const;
511 ir::Statement *ParseStatement(StatementParsingFlags flags = StatementParsingFlags::NONE);
512 ir::TSModuleDeclaration *ParseTsModuleDeclaration(bool isDeclare, bool isExport = false);
513 ir::TSModuleDeclaration *ParseTsAmbientExternalModuleDeclaration(const lexer::SourcePosition &startLoc,
514 bool isDeclare);
515 ir::TSModuleDeclaration *ParseTsModuleOrNamespaceDelaration(const lexer::SourcePosition &startLoc,
516 bool isDeclare,
517 bool isExport);
518
519 ir::TSImportEqualsDeclaration *ParseTsImportEqualsDeclaration(const lexer::SourcePosition &startLoc,
520 bool isExport = false);
521 ir::TSNamespaceExportDeclaration *ParseTsNamespaceExportDeclaration(const lexer::SourcePosition &startLoc);
522 ir::TSModuleBlock *ParseTsModuleBlock();
523 ir::BlockStatement *ParseFunctionBody();
524 ir::BlockStatement *ParseBlockStatement();
525 ir::BlockStatement *ParseBlockStatement(binder::Scope *scope);
526 ir::EmptyStatement *ParseEmptyStatement();
527 ir::DebuggerStatement *ParseDebuggerStatement();
528 ir::BreakStatement *ParseBreakStatement();
529 ir::ContinueStatement *ParseContinueStatement();
530 ir::DoWhileStatement *ParseDoWhileStatement();
531 ir::Statement *ParsePotentialExpressionStatement(StatementParsingFlags flags, bool isDeclare);
532 ir::Statement *ParseVarStatement(bool isDeclare);
533 ir::Statement *ParseLetStatement(StatementParsingFlags flags, bool isDeclare);
534 ir::Statement *ParseConstStatement(StatementParsingFlags flags, bool isDeclare);
535 ir::Statement *ParseExpressionStatement(StatementParsingFlags flags = StatementParsingFlags::NONE);
536 ir::Statement *ParseFunctionStatement(StatementParsingFlags flags, bool isDeclare);
537 ir::FunctionDeclaration *ParseFunctionDeclaration(bool canBeAnonymous = false,
538 ParserStatus newStatus = ParserStatus::NO_OPTS,
539 bool isDeclare = false);
540 void AddFunctionToBinder(ir::ScriptFunction *func, ParserStatus newStatus);
541 void CheckOptionalBindingPatternParameter(ir::ScriptFunction *func) const;
542 ir::Statement *ParseExportDeclaration(StatementParsingFlags flags, ArenaVector<ir::Decorator *> &&decorators);
543 std::tuple<ForStatementKind, ir::AstNode *, ir::Expression *, ir::Expression *> ParseForInOf(
544 ir::Expression *leftNode, ExpressionParseFlags exprFlags, bool isAwait);
545 std::tuple<ForStatementKind, ir::Expression *, ir::Expression *> ParseForInOf(ir::AstNode *initNode,
546 ExpressionParseFlags exprFlags,
547 bool isAwait);
548 std::tuple<ir::Expression *, ir::Expression *> ParseForUpdate(bool isAwait);
549 ir::Statement *ParseForStatement();
550 ir::IfStatement *ParseIfStatement();
551
552 ir::Statement *ParseImportDeclaration(StatementParsingFlags flags);
553 ir::LabelledStatement *ParseLabelledStatement(const lexer::LexerPosition &pos);
554 ir::ReturnStatement *ParseReturnStatement();
555 ir::ClassDeclaration *ParseClassStatement(StatementParsingFlags flags, bool isDeclare,
556 ArenaVector<ir::Decorator *> &&decorators, bool isAbstract = false);
557 ir::ClassDeclaration *ParseClassDeclaration(bool idRequired, ArenaVector<ir::Decorator *> &&decorators,
558 bool isDeclare = false, bool isAbstract = false,
559 bool isExported = false);
560 ir::TSTypeAliasDeclaration *ParseTsTypeAliasDeclaration(bool isDeclare);
561 ir::TSEnumDeclaration *ParseEnumMembers(ir::Identifier *key, const lexer::SourcePosition &enumStart,
562 bool isExport, bool isDeclare, bool isConst);
563 ir::TSEnumDeclaration *ParseEnumDeclaration(bool isExport = false, bool isDeclare = false, bool isConst = false);
564 ir::TSInterfaceDeclaration *ParseTsInterfaceDeclaration(bool isDeclare);
565 void ValidateTsInterfaceName(bool isDeclare);
566 ArenaVector<ir::TSInterfaceHeritage *> ParseTsInterfaceExtends();
567 ir::SwitchCaseStatement *ParseSwitchCaseStatement(bool *seenDefault);
568 ir::SwitchStatement *ParseSwitchStatement();
569 ir::ThrowStatement *ParseThrowStatement();
570 ir::Expression *ParseCatchParam();
571 ir::CatchClause *ParseCatchClause();
572 ir::TryStatement *ParseTryStatement();
573 void ValidateDeclaratorId(bool isDeclare);
574 ir::VariableDeclarator *ParseVariableDeclaratorInitializer(ir::Expression *init, VariableParsingFlags flags,
575 const lexer::SourcePosition &startLoc, bool isDeclare);
576 ir::VariableDeclarator *ParseVariableDeclarator(VariableParsingFlags flags, bool isDeclare);
577 ir::Expression *ParseVariableDeclaratorKey(VariableParsingFlags flags, bool isDeclare, bool *isDefinite);
578 ir::Statement *ParseVariableDeclaration(VariableParsingFlags flags = VariableParsingFlags::NO_OPTS,
579 bool isDeclare = false, bool isExport = false);
580 ir::WhileStatement *ParseWhileStatement();
581 ir::VariableDeclaration *ParseContextualLet(VariableParsingFlags flags,
582 StatementParsingFlags stmFlags = StatementParsingFlags::ALLOW_LEXICAL,
583 bool isDeclare = false);
584
585 util::StringView GetNamespaceExportInternalName()
586 {
587 std::string name = std::string(parser::SourceTextModuleRecord::ANONY_NAMESPACE_NAME) +
588 std::to_string(namespaceExportCount_++);
589 util::UString internalName(name, Allocator());
590 return internalName.View();
591 }
592
593 binder::Binder *Binder()
594 {
595 return program_.Binder();
596 }
597 static constexpr unsigned maxRecursionDepth = 1024;
598
599 inline void RecursiveDepthCheck()
600 {
601 if (recursiveDepth_ < maxRecursionDepth) {
602 return;
603 }
604 RecursiveDepthException();
605 }
606
607 void RecursiveDepthException();
608 // RAII to recursive depth tracking.
609 class TrackRecursive {
610 public:
611 explicit TrackRecursive(ParserImpl *parser) : parser_(parser)
612 {
613 ++parser_->recursiveDepth_;
614 }
615 ~TrackRecursive()
616 {
617 --parser_->recursiveDepth_;
618 }
619 private:
620 ParserImpl *const parser_;
621 };
622
623 friend class Lexer;
624 friend class SavedParserContext;
625 friend class ArrowFunctionContext;
626
627 Program program_;
628 ParserContext context_;
629 lexer::Lexer *lexer_ {nullptr};
630 size_t namespaceExportCount_ {0};
631 size_t recursiveDepth_{0};
632 };
633
634 // Declare a RAII recursive tracker. Check whether the recursion limit has
635 // been exceeded, if so, throw a generic error.
636 // The macro only works from inside parserImpl methods.
637 #define CHECK_PARSER_RECURSIVE_DEPTH \
638 TrackRecursive trackRecursive{this}; \
639 RecursiveDepthCheck()
640
641 template <ParserStatus status>
642 class SavedStatusContext {
643 public:
SavedStatusContext(ParserContext * ctx)644 explicit SavedStatusContext(ParserContext *ctx)
645 // NOLINTNEXTLINE(readability-magic-numbers)
646 : ctx_(ctx), savedStatus_(static_cast<ParserStatus>(ctx->Status()))
647 {
648 // NOLINTNEXTLINE(readability-magic-numbers)
649 ctx->Status() |= status;
650 }
651
652 NO_COPY_SEMANTIC(SavedStatusContext);
653 NO_MOVE_SEMANTIC(SavedStatusContext);
654
~SavedStatusContext()655 ~SavedStatusContext()
656 {
657 ctx_->Status() = savedStatus_;
658 }
659
660 private:
661 ParserContext *ctx_;
662 ParserStatus savedStatus_;
663 };
664
665 class SwitchContext : public SavedStatusContext<ParserStatus::IN_SWITCH> {
666 public:
SwitchContext(ParserContext * ctx)667 explicit SwitchContext(ParserContext *ctx) : SavedStatusContext(ctx) {}
668 NO_COPY_SEMANTIC(SwitchContext);
669 NO_MOVE_SEMANTIC(SwitchContext);
670 ~SwitchContext() = default;
671 };
672
673 template <typename T>
674 class IterationContext : public SavedStatusContext<ParserStatus::IN_ITERATION> {
675 public:
IterationContext(ParserContext * ctx,binder::Binder * binder)676 explicit IterationContext(ParserContext *ctx, binder::Binder *binder)
677 : SavedStatusContext(ctx), lexicalScope_(binder)
678 {
679 }
680
681 NO_COPY_SEMANTIC(IterationContext);
682 NO_MOVE_SEMANTIC(IterationContext);
683 ~IterationContext() = default;
684
LexicalScope()685 const auto &LexicalScope() const
686 {
687 return lexicalScope_;
688 }
689
690 private:
691 binder::LexicalScope<T> lexicalScope_;
692 };
693
694 class FunctionParameterContext : public SavedStatusContext<ParserStatus::FUNCTION_PARAM> {
695 public:
FunctionParameterContext(ParserContext * ctx,binder::Binder * binder)696 explicit FunctionParameterContext(ParserContext *ctx, binder::Binder *binder)
697 : SavedStatusContext(ctx), lexicalScope_(binder)
698 {
699 }
700
LexicalScope()701 const auto &LexicalScope() const
702 {
703 return lexicalScope_;
704 }
705
706 NO_COPY_SEMANTIC(FunctionParameterContext);
707 NO_MOVE_SEMANTIC(FunctionParameterContext);
708 ~FunctionParameterContext() = default;
709
710 private:
711 binder::LexicalScope<binder::FunctionParamScope> lexicalScope_;
712 };
713
714 class SavedParserContext {
715 public:
716 template <typename... Args>
SavedParserContext(ParserImpl * parser,Args &&...args)717 explicit SavedParserContext(ParserImpl *parser, Args &&... args) : parser_(parser), prev_(parser->context_)
718 {
719 parser_->context_ = ParserContext(&prev_, std::forward<Args>(args)...);
720 }
721
722 NO_COPY_SEMANTIC(SavedParserContext);
723 DEFAULT_MOVE_SEMANTIC(SavedParserContext);
724
~SavedParserContext()725 ~SavedParserContext()
726 {
727 parser_->context_ = prev_;
728 }
729
730 protected:
Binder()731 binder::Binder *Binder()
732 {
733 return parser_->Binder();
734 }
735
736 ParserImpl *parser_;
737 ParserContext prev_;
738 };
739
740 class FunctionContext : public SavedParserContext {
741 public:
FunctionContext(ParserImpl * parser,ParserStatus newStatus)742 explicit FunctionContext(ParserImpl *parser, ParserStatus newStatus) : SavedParserContext(parser, newStatus)
743 {
744 if (newStatus & ParserStatus::GENERATOR_FUNCTION) {
745 flags_ |= ir::ScriptFunctionFlags::GENERATOR;
746 }
747
748 if (newStatus & ParserStatus::ASYNC_FUNCTION) {
749 flags_ |= ir::ScriptFunctionFlags::ASYNC;
750 }
751
752 if (newStatus & ParserStatus::CONSTRUCTOR_FUNCTION) {
753 flags_ |= ir::ScriptFunctionFlags::CONSTRUCTOR;
754 }
755 }
756
Flags()757 ir::ScriptFunctionFlags Flags() const
758 {
759 return flags_;
760 }
761
AddFlag(ir::ScriptFunctionFlags flags)762 void AddFlag(ir::ScriptFunctionFlags flags)
763 {
764 flags_ |= flags;
765 }
766
767 NO_COPY_SEMANTIC(FunctionContext);
768 NO_MOVE_SEMANTIC(FunctionContext);
769 ~FunctionContext() = default;
770
771 protected:
772 ir::ScriptFunctionFlags flags_ {ir::ScriptFunctionFlags::NONE};
773 };
774
775 class ArrowFunctionContext : public FunctionContext {
776 public:
ArrowFunctionContext(ParserImpl * parser,bool isAsync)777 explicit ArrowFunctionContext(ParserImpl *parser, bool isAsync)
778 : FunctionContext(parser, InitialFlags(parser->context_.Status()))
779 {
780 if (isAsync) {
781 AddFlag(ir::ScriptFunctionFlags::ASYNC);
782 }
783
784 AddFlag(ir::ScriptFunctionFlags::ARROW);
785 }
786
787 NO_COPY_SEMANTIC(ArrowFunctionContext);
788 NO_MOVE_SEMANTIC(ArrowFunctionContext);
789 ~ArrowFunctionContext() = default;
790
791 private:
InitialFlags(ParserStatus currentStatus)792 static ParserStatus InitialFlags(ParserStatus currentStatus)
793 {
794 return ParserStatus::FUNCTION | ParserStatus::ARROW_FUNCTION |
795 static_cast<ParserStatus>(currentStatus & (ParserStatus::ALLOW_SUPER | ParserStatus::ALLOW_SUPER_CALL |
796 ParserStatus::DISALLOW_ARGUMENTS));
797 }
798 };
799
800 } // namespace panda::es2panda::parser
801
802 #endif
803