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