• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 : uint8_t;
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 : uint16_t;
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 : uint8_t {
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 : uint8_t {
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 SourceFile &sourceFile, const CompilerOptions &options);
191 
192     ScriptExtension Extension() const;
193 
194     void AddPatchFixHelper(util::PatchFix *patchFixHelper);
195 
196     ArenaAllocator *Allocator() const
197     {
198         return program_.Allocator();
199     }
200     bool IsDtsFile() const;
201 
202 private:
203     bool IsStartOfMappedType() const;
204     bool IsStartOfTsTypePredicate() const;
205     bool IsStartOfAbstractConstructorType() const;
206 
207     bool CurrentTokenIsModifier(char32_t nextCp) const;
208     [[noreturn]] void ThrowParameterModifierError(ir::ModifierFlags status) const;
209     [[noreturn]] void ThrowSyntaxError(std::string_view errorMessage) const;
210     [[noreturn]] void ThrowSyntaxError(std::initializer_list<std::string_view> list) const;
211     [[noreturn]] void ThrowSyntaxError(std::initializer_list<std::string_view> list,
212                                        const lexer::SourcePosition &pos) const;
213 
214     [[noreturn]] void ThrowSyntaxError(std::string_view errorMessage, const lexer::SourcePosition &pos) const;
215 
216     template <typename T, typename... Args>
217     T *AllocNode(Args &&... args)
218     {
219         auto ret = program_.Allocator()->New<T>(std::forward<Args>(args)...);
220         if (ret == nullptr) {
221             throw Error(ErrorType::GENERIC, "Unsuccessful allocation during parsing");
222         }
223         return ret;
224     }
225 
226     [[nodiscard]] std::unique_ptr<lexer::Lexer> InitLexer(const std::string &fileName, const std::string &source);
227     void ParseScript();
228     void ParseModule();
229 
230     /*
231      * Transform the commonjs module's AST by wrap the sourceCode & use Reflect.apply to invoke this wrapper with [this]
232      * pointing to [exports] object
233      *
234      * Reflect.apply(function (exports, require, module, __filename, __dirname) {
235      *   [SourceCode]
236      * }, exports, [exports, require, module, __filename, __dirname]);
237      */
238     void ParseCommonjs();
239     void AddCommonjsParams(ArenaVector<ir::Expression *> &params);
240     void AddReflectApplyArgs(ArenaVector<ir::Expression *> &args, ir::FunctionExpression *wrapper);
241     void ParseProgram(ScriptKind kind);
242     bool CheckTopStatementsForRequiredDeclare(const ArenaVector<ir::Statement *> &statements);
243     static ExpressionParseFlags CarryExpressionParserFlag(ExpressionParseFlags origin, ExpressionParseFlags carry);
244     static ExpressionParseFlags CarryPatternFlags(ExpressionParseFlags flags);
245     static ExpressionParseFlags CarryAllowTsParamAndPatternFlags(ExpressionParseFlags flags);
246     bool CurrentIsBasicType();
247     bool CurrentLiteralIsBasicType();
248     static bool CheckTypeNameIsReserved(const util::StringView &paramName);
249     static bool IsPropertyKeysAreSame(const ir::Expression *exp1, const ir::Expression *exp2);
250     static bool IsMemberExpressionsAreSame(const ir::MemberExpression *mExp1, const ir::MemberExpression *mExp2);
251     static bool IsMethodDefinitionsAreSame(const ir::MethodDefinition *property, ir::MethodDefinition *overload);
252     ir::TSTypeReference *ParseTsConstExpression();
253     ir::Expression *ParseTsTypeOperatorOrTypeReference(bool throwError);
254     ir::Expression *ParseTsIdentifierReference(TypeAnnotationParsingOptions options);
255     ir::Expression *ParseTsBasicType(TypeAnnotationParsingOptions options);
256     ir::TSIntersectionType *ParseTsIntersectionType(ir::Expression *type, bool inUnion, bool restrictExtends,
257                                                     bool throwError);
258     ir::TSUnionType *ParseTsUnionType(ir::Expression *type, bool restrictExtends, bool throwError);
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::Identifier *GetKeyByFuncFlag(ir::ScriptFunctionFlags funcFlag);
327     ir::MethodDefinition *CreateImplicitMethod(ir::Expression *superClass, bool hasSuperClass,
328                                                ir::ScriptFunctionFlags funcFlag, bool isDeclare = false);
329     ir::MethodDefinition *CheckClassMethodOverload(ir::Statement *property, ir::MethodDefinition **ctor, bool isDeclare,
330                                                    lexer::SourcePosition errorInfo, ir::MethodDefinition *lastOverload,
331                                                    bool implExists, bool isAbstract = false);
332     ir::Identifier *SetIdentNodeInClassDefinition(bool isDeclare, binder::ConstDecl **decl);
333     ir::ClassDefinition *ParseClassDefinition(bool isDeclaration, bool idRequired = true, bool isDeclare = false,
334                                               bool isAbstract = false);
335     ir::Expression *ParseSuperClass(bool isDeclare, bool *hasSuperClass, bool *isExtendsFromNull);
336     ArenaVector<ir::TSClassImplements *> ParseTSClassImplements(bool isDeclare);
337     void ValidateClassConstructor(const ir::MethodDefinition *ctor,
338                                   const ArenaVector<ir::Statement *> &properties,
339                                   bool isDeclare, bool hasConstructorFuncBody,
340                                   bool hasSuperClass, bool isExtendsFromNull);
341     void FindSuperCall(const ir::AstNode *parent, bool *hasSuperCall);
342     void FindSuperCallInCtorChildNode(const ir::AstNode *childNode, bool *hasSuperCall);
343     bool SuperCallShouldBeRootLevel(const ir::MethodDefinition *ctor, const ArenaVector<ir::Statement *> &properties);
344     void ValidateSuperCallLocation(const ir::MethodDefinition *ctor, bool superCallShouldBeRootLevel);
345     void FindThisOrSuperReference(const ir::AstNode *parent, bool *hasThisOrSuperReference);
346     void FindThisOrSuperReferenceInChildNode(const ir::AstNode *childNode, bool *hasThisOrSuperReference);
347     void ValidateAccessor(ExpressionParseFlags flags, lexer::TokenFlags currentTokenFlags);
348     void CheckPropertyKeyAsycModifier(ParserStatus *methodStatus);
349     ir::Property *ParseShorthandProperty(const lexer::LexerPosition *startPos);
350     void ParseGeneratorPropertyModifier(ExpressionParseFlags flags, ParserStatus *methodStatus);
351     bool ParsePropertyModifiers(ExpressionParseFlags flags, ir::PropertyKind *propertyKind, ParserStatus *methodStatus);
352     ir::Expression *ParsePropertyKey(ExpressionParseFlags flags);
353     ir::Expression *ParsePropertyValue(const ir::PropertyKind *propertyKind, const ParserStatus *methodStatus,
354                                        ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
355     bool ParsePropertyEnd();
356 
357     ir::Expression *ParsePostfixTypeOrHigher(ir::Expression *typeAnnotation, TypeAnnotationParsingOptions *options);
358     ir::Expression *TryParseConstraintOfInferType(TypeAnnotationParsingOptions *options);
359     ir::Expression *ParsePropertyDefinition(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
360     bool CheckOutIsIdentInTypeParameter();
361     void ParseTypeModifier(bool &isTypeIn, bool &isTypeOut, bool &isAllowInOut);
362     ir::TSTypeParameter *ParseTsTypeParameter(bool throwError, bool addBinding = false, bool isAllowInOut = false);
363     ir::TSTypeParameterDeclaration *ParseTsTypeParameterDeclaration(bool throwError = true, bool isAllowInOut = false);
364     ir::TSTypeParameterInstantiation *ParseTsTypeParameterInstantiation(bool throwError = true);
365     ir::ScriptFunction *ParseFunction(ParserStatus newStatus = ParserStatus::NO_OPTS,
366                                       bool isDeclare = false,
367                                       ArenaVector<ir::ParamDecorators> *paramDecorators = nullptr);
368     void ValidateFunctionParam(const ArenaVector<ir::Expression *> &params, const ir::Expression *parameter,
369                                bool *seenOptional);
370     void ValidateTsFunctionOverloadParams(const ArenaVector<ir::Expression *> &params);
371     void CheckAccessorPair(const ArenaVector<ir::Statement *> &properties, const ir::Expression *propName,
372                            ir::MethodDefinitionKind methodKind, ir::ModifierFlags access, bool hasDecorator,
373                            lexer::SourcePosition errorInfo);
374     ArenaVector<ir::Expression *> ParseFunctionParams(bool isDeclare = false,
375                                                       ArenaVector<ir::ParamDecorators> *paramDecorators = nullptr);
376     ir::SpreadElement *ParseSpreadElement(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
377     ir::TSParameterProperty *CreateTsParameterProperty(ir::Expression *parameter, ir::ModifierFlags modifiers);
378     ir::Expression *ParseFunctionParameter(bool isDeclare);
379     void CreateTSVariableForProperty(ir::AstNode *node, const ir::Expression *key, binder::VariableFlags flags);
380     void CheckObjectTypeForDuplicatedProperties(ir::Expression *member, ArenaVector<ir::Expression *> const &members);
381 
382     // ExpressionParser.Cpp
383 
384     ir::Expression *ParseExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
385     ir::ArrowFunctionExpression *ParseTsGenericArrowFunction();
386     ir::TSTypeAssertion *ParseTsTypeAssertion(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
387     ir::TSAsExpression *ParseTsAsExpression(ir::Expression *expr, ExpressionParseFlags flags);
388     ir::TSSatisfiesExpression *ParseTsSatisfiesExpression(ir::Expression *expr);
389     ir::Expression *ParseArrayExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
390     ir::YieldExpression *ParseYieldExpression();
391     ir::Expression *ParsePotentialExpressionSequence(ir::Expression *expr, ExpressionParseFlags flags);
392     ParserStatus ValidateArrowParameter(ir::Expression *expr);
393 
394     ArrowFunctionDescriptor ConvertToArrowParameter(ir::Expression *expr, bool isAsync,
395                                                     binder::FunctionParamScope *paramScope);
396     ir::ArrowFunctionExpression *ParseArrowFunctionExpressionBody(ArrowFunctionContext *arrowFunctionContext,
397                                                                   binder::FunctionScope *functionScope,
398                                                                   ArrowFunctionDescriptor *desc,
399                                                                   ir::TSTypeParameterDeclaration *typeParamDecl,
400                                                                   ir::Expression *returnTypeAnnotation);
401     ir::ArrowFunctionExpression *ParseArrowFunctionExpression(ir::Expression *expr,
402                                                               ir::TSTypeParameterDeclaration *typeParamDecl,
403                                                               ir::Expression *returnTypeAnnotation, bool isAsync);
404     ir::Expression *ParseCoverParenthesizedExpressionAndArrowParameterList();
405     ir::Expression *ParseKeywordExpression();
406     ir::Expression *ParseBinaryExpression(ir::Expression *left);
407     ir::CallExpression *ParseCallExpression(ir::Expression *callee, bool isOptionalChain = false, bool isAsync = false);
408     ir::ArrowFunctionExpression *ParsePotentialArrowExpression(ir::Expression **returnExpression,
409                                                                const lexer::SourcePosition &startLoc,
410                                                                bool ignoreCallExpression);
411 
412     void ValidateUpdateExpression(ir::Expression *returnExpression, bool isChainExpression);
413     bool IsGenericInstantiation();
414     bool ParsePotentialTsGenericFunctionCall(ir::Expression **returnExpression, const lexer::SourcePosition &startLoc,
415                                              bool ignoreCallExpression);
416     ir::Expression *ParsePostPrimaryExpression(ir::Expression *primaryExpr, lexer::SourcePosition startLoc,
417                                                bool ignoreCallExpression, bool *isChainExpression);
418     ir::Expression *ParseMemberExpression(bool ignoreCallExpression = false,
419                                           ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
420     ir::ObjectExpression *ParseObjectExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
421     ir::SequenceExpression *ParseSequenceExpression(ir::Expression *startExpr, bool acceptRest = false,
422                                                     bool acceptTsParam = false, bool acceptPattern = false);
423     ir::Expression *ParseUnaryOrPrefixUpdateExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
424     ir::Expression *ParseLeftHandSideExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
425     ir::MetaProperty *ParsePotentialNewTarget();
426     void CheckInvalidDestructuring(const ir::AstNode *object) const;
427     void ValidateParenthesizedExpression(ir::Expression *lhsExpression);
428     ir::Expression *ParseAssignmentExpression(ir::Expression *lhsExpression,
429                                               ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
430     ir::Expression *ParsePrimaryExpression(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS);
431     ir::NewExpression *ParseNewExpression();
432     void ParsePotentialTsFunctionParameter(ExpressionParseFlags flags, ir::Expression *returnNode,
433                                            bool isDeclare = false);
434     ir::Expression *ParsePatternElement(ExpressionParseFlags flags = ExpressionParseFlags::NO_OPTS,
435                                         bool allowDefault = true, bool isDeclare = false);
436     ir::TemplateLiteral *ParseTemplateLiteral(bool isTaggedTemplate = false);
437     ir::Expression *ParseImportExpression();
438     ir::ObjectExpression *ParseImportAssertionForDynamicImport();
439     void ValidateImportAssertionForDynamicImport(ir::ObjectExpression *importAssertion);
440     ir::AssertClause *ParseAssertClause();
441     ir::AssertEntry *ParseAssertEntry();
442     ir::FunctionExpression *ParseFunctionExpression(ParserStatus newStatus = ParserStatus::NO_OPTS);
443     ir::Expression *ParseOptionalChain(ir::Expression *leftSideExpr);
444     ir::Expression *ParseOptionalMemberExpression(ir::Expression *object);
445     void ParseNameSpaceImport(ArenaVector<ir::AstNode *> *specifiers, bool isType);
446     ir::Identifier *ParseNamedImport(const lexer::Token &importedToken);
447     binder::Decl *AddImportDecl(bool isType,
448                                 util::StringView name,
449                                 lexer::SourcePosition startPos,
450                                 binder::DeclarationFlags flag);
451 
452     ir::StringLiteral *ParseFromClause(bool requireFrom = true);
453     void ParseNamedImportSpecifiers(ArenaVector<ir::AstNode *> *specifiers, bool isType, bool isLazy);
454     bool HandleTypeImportOrExportSpecifier();
455     ir::Expression *ParseModuleReference();
456     ir::AstNode *ParseImportDefaultSpecifier(ArenaVector<ir::AstNode *> *specifiers, bool isType);
457     ir::AstNode *ParseImportSpecifiers(ArenaVector<ir::AstNode *> *specifiers, bool isType, bool isLazy);
458     void ValidateAssignmentTarget(ExpressionParseFlags flags, ir::Expression *node);
459     void ValidateLvalueAssignmentTarget(ir::Expression *node) const;
460     void ValidateArrowParameterBindings(const ir::Expression *node);
461 
462     ir::ExportDefaultDeclaration *ParseExportDefaultDeclaration(const lexer::SourcePosition &startLoc,
463                                                                 ArenaVector<ir::Decorator *> decorators,
464                                                                 bool isExportEquals = false);
465     ir::ExportAllDeclaration *ParseExportAllDeclaration(const lexer::SourcePosition &startLoc);
466     ir::ExportNamedDeclaration *ParseExportNamedSpecifiers(const lexer::SourcePosition &startLoc, bool isType);
467     ir::ExportNamedDeclaration *ParseNamedExportDeclaration(const lexer::SourcePosition &startLoc,
468                                                             ArenaVector<ir::Decorator *> &&decorators);
469     ir::Identifier *ParseNamedExport(const lexer::Token &exportedToken);
470     void CheckStrictReservedWord() const;
471     ir::PrivateIdentifier *ParsePrivateIdentifier();
472 
473     // Discard the DISALLOW_CONDITIONAL_TYPES in current status to call function.
474     template<class Function,  typename... Args>
475     ir::Expression *DoOutsideOfDisallowConditinalTypesContext(Function func, Args &&... args);
476 
477     // Add the DISALLOW_CONDITIONAL_TYPES to current status to call function.
478     template<typename Function, typename... Args>
479     ir::Expression *DoInsideOfDisallowConditinalTypesContext(Function func, Args &&... args);
480 
481     bool InDisallowConditionalTypesContext();
482     bool InContext(ParserStatus status);
483     void AddFlagToStatus(ParserStatus status);
484     void RemoveFlagToStatus(ParserStatus status);
485     // StatementParser.Cpp
486 
487     void ConsumeSemicolon(ir::Statement *statement);
488     void CheckFunctionDeclaration(StatementParsingFlags flags);
489 
490     void CheckLabelledFunction(const ir::Statement *node);
491     bool CheckDeclare();
492 
493     bool IsLabelFollowedByIterationStatement();
494 
495     void AddImportEntryItem(const ir::StringLiteral *source, const ArenaVector<ir::AstNode *> *specifiers, bool isType,
496         bool isLazy);
497     void AddImportEntryItemForImportSpecifier(const ir::StringLiteral *source, const ir::AstNode *specifier,
498         bool isLazy);
499     void AddImportEntryItemForImportDefaultOrNamespaceSpecifier(const ir::StringLiteral *source,
500                                                                 const ir::AstNode *specifier, bool isType);
501     void AddExportNamedEntryItem(const ArenaVector<ir::ExportSpecifier *> &specifiers,
502                                  const ir::StringLiteral *source, bool isType);
503     void AddExportStarEntryItem(const lexer::SourcePosition &startLoc, const ir::StringLiteral *source,
504                                 const ir::Identifier *exported);
505     void AddExportDefaultEntryItem(const ir::AstNode *declNode);
506     void AddExportLocalEntryItem(const ir::Statement *declNode, bool isTsModule);
507     void AddTsTypeExportLocalEntryItem(const ir::Statement *declNode, bool isTsModule,
508                                        binder::TSModuleScope *tsModuleScope);
509     parser::SourceTextModuleRecord *GetSourceTextModuleRecord();
510     parser::SourceTextModuleRecord *GetSourceTextTypeModuleRecord();
511 
512     bool ParseDirective(ArenaVector<ir::Statement *> *statements);
513     void ParseDirectivePrologue(ArenaVector<ir::Statement *> *statements);
514     ArenaVector<ir::Statement *> ParseStatementList(StatementParsingFlags flags = StatementParsingFlags::ALLOW_LEXICAL);
515     bool IsTsDeclarationStatement() const;
516     ir::Statement *ParseStatement(StatementParsingFlags flags = StatementParsingFlags::NONE);
517     ir::TSModuleDeclaration *ParseTsModuleDeclaration(bool isDeclare, bool isExport = false);
518     ir::TSModuleDeclaration *ParseTsAmbientExternalModuleDeclaration(const lexer::SourcePosition &startLoc,
519                                                                      bool isDeclare);
520     ir::TSModuleDeclaration *ParseTsModuleOrNamespaceDelaration(const lexer::SourcePosition &startLoc,
521                                                                 bool isDeclare,
522                                                                 bool isExport);
523     bool IsInstantiatedInTsModuleBlock(ir::Statement **body);
524 
525     ir::TSImportEqualsDeclaration *ParseTsImportEqualsDeclaration(const lexer::SourcePosition &startLoc,
526                                                                   bool isExport = false);
527     ir::TSNamespaceExportDeclaration *ParseTsNamespaceExportDeclaration(const lexer::SourcePosition &startLoc);
528     ir::TSModuleBlock *ParseTsModuleBlock();
529     ir::BlockStatement *ParseFunctionBody();
530     ir::BlockStatement *ParseBlockStatement();
531     ir::BlockStatement *ParseBlockStatement(binder::Scope *scope);
532     ir::EmptyStatement *ParseEmptyStatement();
533     ir::DebuggerStatement *ParseDebuggerStatement();
534     ir::BreakStatement *ParseBreakStatement();
535     ir::ContinueStatement *ParseContinueStatement();
536     ir::DoWhileStatement *ParseDoWhileStatement();
537     ir::Statement *ParsePotentialExpressionStatement(StatementParsingFlags flags, bool isDeclare);
538     ir::Statement *ParseVarStatement(bool isDeclare);
539     ir::Statement *ParseLetStatement(StatementParsingFlags flags, bool isDeclare);
540     ir::Statement *ParseConstStatement(StatementParsingFlags flags, bool isDeclare);
541     ir::Statement *ParseExpressionStatement(StatementParsingFlags flags = StatementParsingFlags::NONE);
542     ir::Statement *ParseFunctionStatement(StatementParsingFlags flags, bool isDeclare);
543     ir::FunctionDeclaration *ParseFunctionDeclaration(bool canBeAnonymous = false,
544                                                       ParserStatus newStatus = ParserStatus::NO_OPTS,
545                                                       bool isDeclare = false);
546     void AddFunctionToBinder(ir::ScriptFunction *func, ParserStatus newStatus);
547     void CheckOptionalBindingPatternParameter(ir::ScriptFunction *func) const;
548     ir::Statement *ParseExportDeclaration(StatementParsingFlags flags, ArenaVector<ir::Decorator *> &&decorators);
549     std::tuple<ForStatementKind, ir::AstNode *, ir::Expression *, ir::Expression *> ParseForInOf(
550         ir::Expression *leftNode, ExpressionParseFlags exprFlags, bool isAwait);
551     std::tuple<ForStatementKind, ir::Expression *, ir::Expression *> ParseForInOf(ir::AstNode *initNode,
552                                                                                   ExpressionParseFlags exprFlags,
553                                                                                   bool isAwait);
554     std::tuple<ir::Expression *, ir::Expression *> ParseForUpdate(bool isAwait);
555     ir::Statement *ParseForStatement();
556     ir::IfStatement *ParseIfStatement();
557 
558     ir::Statement *ParseImportDeclaration(StatementParsingFlags flags);
559     ir::LabelledStatement *ParseLabelledStatement(const lexer::LexerPosition &pos);
560     ir::ReturnStatement *ParseReturnStatement();
561     ir::ClassDeclaration *ParseClassStatement(StatementParsingFlags flags, bool isDeclare,
562                                               ArenaVector<ir::Decorator *> &&decorators, bool isAbstract = false);
563     ir::ClassDeclaration *ParseClassDeclaration(bool idRequired, ArenaVector<ir::Decorator *> &&decorators,
564                                                 bool isDeclare = false, bool isAbstract = false,
565                                                 bool isExported = false);
566     ir::TSTypeAliasDeclaration *ParseTsTypeAliasDeclaration(bool isDeclare);
567     ir::TSEnumDeclaration *ParseEnumMembers(ir::Identifier *key, const lexer::SourcePosition &enumStart,
568                                             bool isExport, bool isDeclare, bool isConst);
569     ir::TSEnumDeclaration *ParseEnumDeclaration(bool isExport = false, bool isDeclare = false, bool isConst = false);
570     ir::TSInterfaceDeclaration *ParseTsInterfaceDeclaration(bool isDeclare);
571     void ValidateTsInterfaceName(bool isDeclare);
572     ArenaVector<ir::TSInterfaceHeritage *> ParseTsInterfaceExtends();
573     ir::SwitchCaseStatement *ParseSwitchCaseStatement(bool *seenDefault);
574     ir::SwitchStatement *ParseSwitchStatement();
575     ir::ThrowStatement *ParseThrowStatement();
576     ir::Expression *ParseCatchParam();
577     ir::CatchClause *ParseCatchClause();
578     ir::TryStatement *ParseTryStatement();
579     void ValidateDeclaratorId(bool isDeclare);
580     ir::VariableDeclarator *ParseVariableDeclaratorInitializer(ir::Expression *init, VariableParsingFlags flags,
581                                                                const lexer::SourcePosition &startLoc, bool isDeclare);
582     ir::VariableDeclarator *ParseVariableDeclarator(VariableParsingFlags flags, bool isDeclare);
583     ir::Expression *ParseVariableDeclaratorKey(VariableParsingFlags flags, bool isDeclare, bool *isDefinite);
584     ir::Statement *ParseVariableDeclaration(VariableParsingFlags flags = VariableParsingFlags::NO_OPTS,
585                                             bool isDeclare = false, bool isExport = false);
586     ir::WhileStatement *ParseWhileStatement();
587     ir::VariableDeclaration *ParseContextualLet(VariableParsingFlags flags,
588                                                 StatementParsingFlags stmFlags = StatementParsingFlags::ALLOW_LEXICAL,
589                                                 bool isDeclare = false);
590     void VerifySupportLazyImportVersion();
591 
592     util::StringView GetNamespaceExportInternalName()
593     {
594         std::string name = std::string(parser::SourceTextModuleRecord::ANONY_NAMESPACE_NAME) +
595                            std::to_string(namespaceExportCount_++);
596         util::UString internalName(name, Allocator());
597         return internalName.View();
598     }
599 
600     binder::Binder *Binder()
601     {
602         return program_.Binder();
603     }
604     static constexpr unsigned MAX_RECURSION_DEPTH = 1024;
605 
606     inline void RecursiveDepthCheck()
607     {
608         if (recursiveDepth_ < MAX_RECURSION_DEPTH) {
609             return;
610         }
611         RecursiveDepthException();
612     }
613 
614     void RecursiveDepthException();
615     // RAII to recursive depth tracking.
616     class TrackRecursive {
617     public:
618         explicit TrackRecursive(ParserImpl *parser) : parser_(parser)
619         {
620             ++parser_->recursiveDepth_;
621         }
622         ~TrackRecursive()
623         {
624             --parser_->recursiveDepth_;
625         }
626     private:
627         ParserImpl *const parser_;
628     };
629 
630     friend class Lexer;
631     friend class SavedParserContext;
632     friend class ArrowFunctionContext;
633 
634     Program program_;
635     ParserContext context_;
636     lexer::Lexer *lexer_ {nullptr};
637     size_t namespaceExportCount_ {0};
638     size_t recursiveDepth_{0};
639 };
640 
641 // Declare a RAII recursive tracker. Check whether the recursion limit has
642 // been exceeded, if so, throw a generic error.
643 // The macro only works from inside parserImpl methods.
644 #define CHECK_PARSER_RECURSIVE_DEPTH                  \
645     TrackRecursive trackRecursive{this};       \
646     RecursiveDepthCheck()
647 
648 template <ParserStatus status>
649 class SavedStatusContext {
650 public:
SavedStatusContext(ParserContext * ctx)651     explicit SavedStatusContext(ParserContext *ctx)
652         // NOLINTNEXTLINE(readability-magic-numbers)
653         : ctx_(ctx), savedStatus_(static_cast<ParserStatus>(ctx->Status()))
654     {
655         // NOLINTNEXTLINE(readability-magic-numbers)
656         ctx->Status() |= status;
657     }
658 
659     NO_COPY_SEMANTIC(SavedStatusContext);
660     NO_MOVE_SEMANTIC(SavedStatusContext);
661 
~SavedStatusContext()662     ~SavedStatusContext()
663     {
664         ctx_->Status() = savedStatus_;
665     }
666 
667 private:
668     ParserContext *ctx_;
669     ParserStatus savedStatus_;
670 };
671 
672 class SwitchContext : public SavedStatusContext<ParserStatus::IN_SWITCH> {
673 public:
SwitchContext(ParserContext * ctx)674     explicit SwitchContext(ParserContext *ctx) : SavedStatusContext(ctx) {}
675     NO_COPY_SEMANTIC(SwitchContext);
676     NO_MOVE_SEMANTIC(SwitchContext);
677     ~SwitchContext() = default;
678 };
679 
680 template <typename T>
681 class IterationContext : public SavedStatusContext<ParserStatus::IN_ITERATION> {
682 public:
IterationContext(ParserContext * ctx,binder::Binder * binder)683     explicit IterationContext(ParserContext *ctx, binder::Binder *binder)
684         : SavedStatusContext(ctx), lexicalScope_(binder)
685     {
686     }
687 
688     NO_COPY_SEMANTIC(IterationContext);
689     NO_MOVE_SEMANTIC(IterationContext);
690     ~IterationContext() = default;
691 
LexicalScope()692     const auto &LexicalScope() const
693     {
694         return lexicalScope_;
695     }
696 
697 private:
698     binder::LexicalScope<T> lexicalScope_;
699 };
700 
701 class FunctionParameterContext : public SavedStatusContext<ParserStatus::FUNCTION_PARAM> {
702 public:
FunctionParameterContext(ParserContext * ctx,binder::Binder * binder)703     explicit FunctionParameterContext(ParserContext *ctx, binder::Binder *binder)
704         : SavedStatusContext(ctx), lexicalScope_(binder)
705     {
706     }
707 
LexicalScope()708     const auto &LexicalScope() const
709     {
710         return lexicalScope_;
711     }
712 
713     NO_COPY_SEMANTIC(FunctionParameterContext);
714     NO_MOVE_SEMANTIC(FunctionParameterContext);
715     ~FunctionParameterContext() = default;
716 
717 private:
718     binder::LexicalScope<binder::FunctionParamScope> lexicalScope_;
719 };
720 
721 class SavedParserContext {
722 public:
723     template <typename... Args>
SavedParserContext(ParserImpl * parser,Args &&...args)724     explicit SavedParserContext(ParserImpl *parser, Args &&... args) : parser_(parser), prev_(parser->context_)
725     {
726         parser_->context_ = ParserContext(&prev_, std::forward<Args>(args)...);
727     }
728 
729     NO_COPY_SEMANTIC(SavedParserContext);
730     DEFAULT_MOVE_SEMANTIC(SavedParserContext);
731 
~SavedParserContext()732     ~SavedParserContext()
733     {
734         parser_->context_ = prev_;
735     }
736 
737 protected:
Binder()738     binder::Binder *Binder()
739     {
740         return parser_->Binder();
741     }
742 
743     ParserImpl *parser_;
744     ParserContext prev_;
745 };
746 
747 class FunctionContext : public SavedParserContext {
748 public:
FunctionContext(ParserImpl * parser,ParserStatus newStatus)749     explicit FunctionContext(ParserImpl *parser, ParserStatus newStatus) : SavedParserContext(parser, newStatus)
750     {
751         if (newStatus & ParserStatus::GENERATOR_FUNCTION) {
752             flags_ |= ir::ScriptFunctionFlags::GENERATOR;
753         }
754 
755         if (newStatus & ParserStatus::ASYNC_FUNCTION) {
756             flags_ |= ir::ScriptFunctionFlags::ASYNC;
757         }
758 
759         if (newStatus & ParserStatus::CONSTRUCTOR_FUNCTION) {
760             flags_ |= ir::ScriptFunctionFlags::CONSTRUCTOR;
761         }
762     }
763 
Flags()764     ir::ScriptFunctionFlags Flags() const
765     {
766         return flags_;
767     }
768 
AddFlag(ir::ScriptFunctionFlags flags)769     void AddFlag(ir::ScriptFunctionFlags flags)
770     {
771         flags_ |= flags;
772     }
773 
774     NO_COPY_SEMANTIC(FunctionContext);
775     NO_MOVE_SEMANTIC(FunctionContext);
776     ~FunctionContext() = default;
777 
778 protected:
779     ir::ScriptFunctionFlags flags_ {ir::ScriptFunctionFlags::NONE};
780 };
781 
782 class ArrowFunctionContext : public FunctionContext {
783 public:
ArrowFunctionContext(ParserImpl * parser,bool isAsync)784     explicit ArrowFunctionContext(ParserImpl *parser, bool isAsync)
785         : FunctionContext(parser, InitialFlags(parser->context_.Status()))
786     {
787         if (isAsync) {
788             AddFlag(ir::ScriptFunctionFlags::ASYNC);
789         }
790 
791         AddFlag(ir::ScriptFunctionFlags::ARROW);
792     }
793 
794     NO_COPY_SEMANTIC(ArrowFunctionContext);
795     NO_MOVE_SEMANTIC(ArrowFunctionContext);
796     ~ArrowFunctionContext() = default;
797 
798 private:
InitialFlags(ParserStatus currentStatus)799     static ParserStatus InitialFlags(ParserStatus currentStatus)
800     {
801         return ParserStatus::FUNCTION | ParserStatus::ARROW_FUNCTION |
802                static_cast<ParserStatus>(currentStatus & (ParserStatus::ALLOW_SUPER | ParserStatus::ALLOW_SUPER_CALL |
803                                          ParserStatus::DISALLOW_ARGUMENTS));
804     }
805 };
806 
807 }  // namespace panda::es2panda::parser
808 
809 #endif
810