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