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