diff --git a/.gitmodules b/.gitmodules index e69de29..fd49688 100644 --- a/.gitmodules +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "libs/tracy"] + path = libs/tracy + url = git@github.com:wolfpld/tracy.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 46d21b7..5c2f677 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,12 +3,19 @@ project(typescript) set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_FLAGS "-Wall -Wextra -O2") +# enable for profiling +#add_definitions(-DTRACY_ENABLE) + +include_directories(libs/tracy/) + list(APPEND CMAKE_MODULE_PATH libs/) #add_definitions(-DTRACY_ENABLE) #include_directories(libs/tracy/) +add_subdirectory(libs/tracy) + +link_libraries(Tracy::TracyClient) add_subdirectory(src) include_directories(libs) diff --git a/libs/tracy b/libs/tracy new file mode 160000 index 0000000..a53c8be --- /dev/null +++ b/libs/tracy @@ -0,0 +1 @@ +Subproject commit a53c8befdc914e58c0fbd1d159c11ff85d4f05df diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b50a1cc..a04ce9a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -5,6 +5,11 @@ add_definitions(-DTRACY_ENABLE) add_subdirectory(tests) +set(CMAKE_CXX_FLAGS "-Wall -Wextra -O2") +#set(CMAKE_CXX_FLAGS "-Wall -Wextra -O3 -ffast-math") + add_library(typescript utf.h utf.cpp core.h core.cpp utilities.h utilities.cpp node_test.h node_test.cpp syntax_cursor.h syntax_cursor.cpp parser2.h parser2.cpp types.h types.cpp path.h path.cpp - factory.h factory.cpp parenthesizer.h parenthesizer.cpp scanner.h scanner.cpp) + factory.h factory.cpp parenthesizer.h parenthesizer.cpp scanner.h scanner.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libs/tracy/TracyClient.cpp + ) diff --git a/src/core.cpp b/src/core.cpp index ca31af1..319a6a4 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -11,15 +11,30 @@ namespace ts::Debug { } namespace ts { - string substr(const string &str, int start, int length) { + string substr(const string &str, int start, optional len) { + if (start <= 0 && len && len < 0) return ""; + if (!len || *len < 0 || len > str.size()) *len = str.size(); if (start < 0) start += str.length(); - if (length < 0) length = str.length() + length - start; - if (length < 0) return ""; - return str.substr(start, length); + return str.substr(start, *len); } - string substr(const string &str, int start) { - return substr(str, start, str.length()); + + //compatible with JavaScript's String.substring + string substring(const string &str, int start, optional end) { + if (start < 0) start = 0; + int len = str.size(); + if (end) { + if (*end < start) { + len = start - *end; + start = *end; + } else { + len = *end - start; + } + } + if (len < 0) len = 0; + if (start > str.size()) start = str.size(); + return str.substr(start, len); } + string replaceLeading(const string &text, const string &from, const string &to) { if (0 == text.find(from)) { string str = text; diff --git a/src/core.h b/src/core.h index 0a5fcd1..1480456 100644 --- a/src/core.h +++ b/src/core.h @@ -40,9 +40,11 @@ namespace ts { return const_hash(s); } - string substr(const string &str, int start, int length); + //compatible with JavaScript's String.substr + string substr(const string &str, int start, optional len = {}); - string substr(const string &str, int start); + //compatible with JavaScript's String.substring + string substring(const string &str, int start, optional end = {}); /** * shared_ptr has optional semantic already built-in, so we use it instead of std::optional>, @@ -157,6 +159,7 @@ namespace ts { } return false; } + template inline bool some(optional> array) { return array && !array->empty(); @@ -223,7 +226,10 @@ namespace ts { template inline optional set(unordered_map &m, K key, T v) { - m[key] = v; +// m.insert_or_assign(key, v); + std::cout << "set map: " << key << ", " << v << "\n"; +// m.insert({key, v}); +// m[key] = v; } template diff --git a/src/factory.cpp b/src/factory.cpp index b41be08..a207c12 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -18,45 +18,45 @@ namespace ts { return propagateChildFlags(std::move(node)) & ~(int) TransformFlags::ContainsPossibleTopLevelAwait; } - int Factory::propagateChildrenFlags(optional children) { + int Factory::propagateChildrenFlags(sharedOpt children) { return children ? children->transformFlags : (int) TransformFlags::None; } - void Factory::aggregateChildrenFlags(NodeArray &children) { + void Factory::aggregateChildrenFlags(shared &children) { int subtreeFlags = (int) TransformFlags::None; - for (auto &child: children.list) { + for (auto &child: children->list) { subtreeFlags |= propagateChildFlags(child); } - children.transformFlags = subtreeFlags; + children->transformFlags = subtreeFlags; } - NodeArray Factory::createNodeArray(optional elements, optional hasTrailingComma) { + shared Factory::createNodeArray(sharedOpt elements, optional hasTrailingComma) { if (elements) { if (!hasTrailingComma || elements->hasTrailingComma == hasTrailingComma) { // Ensure the transform flags have been aggregated for this NodeArray if (elements->transformFlags == (int) types::TransformFlags::None) { - aggregateChildrenFlags(*elements); + aggregateChildrenFlags(elements); } // Debug.attachNodeArrayDebugInfo(elements); - return *elements; + return elements; } } // This *was* a `NodeArray`, but the `hasTrailingComma` option differs. Recreate the // array with the same elements, text range, and transform flags but with the updated // value for `hasTrailingComma` - NodeArray array; - if (elements) array = *elements; - array.pos = elements->pos; - array.end = elements->end; - array.hasTrailingComma = *hasTrailingComma; - array.transformFlags = elements->transformFlags; + auto array = make_shared(); + if (elements) array = elements; + array->pos = elements->pos; + array->end = elements->end; + array->hasTrailingComma = *hasTrailingComma; + array->transformFlags = elements->transformFlags; // Debug.attachNodeArrayDebugInfo(array); return array; } - optional Factory::asNodeArray(optional array) { - return array; + sharedOpt Factory::asNodeArray(sharedOpt elements) { + return elements; } // @api @@ -154,11 +154,11 @@ namespace ts { // } void Factory::setName(shared &lName, shared rName) { - lName = dynamic_pointer_cast(rName); + lName = reinterpret_pointer_cast(rName); } void Factory::setName(shared &lName, shared rName) { - lName = dynamic_pointer_cast(rName); + lName = reinterpret_pointer_cast(rName); } void Factory::setName(shared &lName, shared rName) { @@ -246,11 +246,11 @@ namespace ts { } // @api - shared Factory::createIdentifier(string text, optional typeArguments, optional originalKeywordKind) { + shared Factory::createIdentifier(string text, sharedOpt typeArguments, optional originalKeywordKind) { auto node = createBaseIdentifier(std::move(text), originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations - node->typeArguments = createNodeArray(*typeArguments); + node->typeArguments = createNodeArray(typeArguments); } if (node->originalKeywordKind == SyntaxKind::AwaitKeyword) { node->transformFlags |= (int) TransformFlags::ContainsPossibleTopLevelAwait; @@ -352,7 +352,7 @@ namespace ts { shared Factory::createQualifiedName(shared left, NameType right) { auto node = createBaseNode(SyntaxKind::QualifiedName); node->left = left; - node->right = dynamic_pointer_cast(asName(right)); + node->right = reinterpret_pointer_cast(asName(right)); node->transformFlags |= propagateChildFlags(node->left) | propagateIdentifierNameFlags(node->right); @@ -390,22 +390,22 @@ namespace ts { // // // // // @api -// function createTypeParameterDeclaration(optional modifiers, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; +// function createTypeParameterDeclaration(sharedOpt modifiers, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; // /** @deprecated */ // function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; shared Factory::createTypeParameterDeclaration( - optional, string>> modifiersOrName, + optional, shared, string>> modifiersOrName, optional, shared, string>> nameOrConstraint, sharedOpt constraintOrDefault, sharedOpt defaultType ) { NameType name = ""; - optional modifiers; + sharedOpt modifiers; sharedOpt constraint = constraintOrDefault; if (modifiersOrName) { - if (holds_alternative(*modifiersOrName)) { - modifiers = get(*modifiersOrName); + if (holds_alternative>(*modifiersOrName)) { + modifiers = get>(*modifiersOrName); } else if (holds_alternative(*modifiersOrName)) { name = get(*modifiersOrName); } else if (holds_alternative>(*modifiersOrName)) { @@ -435,7 +435,7 @@ namespace ts { // } auto node = createBaseNamedDeclaration( SyntaxKind::TypeParameter, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, name ); @@ -446,7 +446,7 @@ namespace ts { } // // @api -// function updateTypeParameterDeclaration(node: TypeParameterDeclaration, optional modifiers, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; +// function updateTypeParameterDeclaration(node: TypeParameterDeclaration, sharedOpt modifiers, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; // /** @deprecated */ // function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; // function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiersOrName: readonly Modifier[] | Identifier | undefined, nameOrConstraint: Identifier | TypeNode | undefined, constraintOrDefault: TypeNode | undefined, defaultType?: TypeNode | undefined) { @@ -473,8 +473,8 @@ namespace ts { // @api shared Factory::createParameterDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt dotDotDotToken, NameType name, sharedOpt questionToken, @@ -507,8 +507,8 @@ namespace ts { // // @api // function updateParameterDeclaration( // node: ParameterDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // dotDotDotToken: DotDotDotToken | undefined, // name: string | BindingName, // sharedOpt questionToken, @@ -550,14 +550,14 @@ namespace ts { // @api shared Factory::createPropertySignature( - optional modifiers, + sharedOpt modifiers, NameType name, sharedOpt questionToken, sharedOpt type ) { auto node = createBaseNamedDeclaration( SyntaxKind::PropertySignature, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, name ); @@ -570,7 +570,7 @@ namespace ts { // // @api // function updatePropertySignature( // node: PropertySignature, -// optional modifiers, +// sharedOpt modifiers, // name: PropertyName, // sharedOpt questionToken, // sharedOpt type @@ -585,8 +585,8 @@ namespace ts { // @api shared Factory::createPropertyDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, sharedOpt questionOrExclamationToken, sharedOpt type, @@ -600,8 +600,8 @@ namespace ts { type, initializer ); - node->questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? dynamic_pointer_cast(questionOrExclamationToken) : nullptr; - node->exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? dynamic_pointer_cast(questionOrExclamationToken) : nullptr; + node->questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? reinterpret_pointer_cast(questionOrExclamationToken) : nullptr; + node->exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? reinterpret_pointer_cast(questionOrExclamationToken) : nullptr; node->transformFlags |= propagateChildFlags(node->questionToken) | propagateChildFlags(node->exclamationToken) | @@ -618,8 +618,8 @@ namespace ts { // // @api // function updatePropertyDeclaration( // node: PropertyDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // NameType name, // questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, // sharedOpt type, @@ -638,16 +638,16 @@ namespace ts { // // @api shared Factory::createMethodSignature( - optional modifiers, + sharedOpt modifiers, NameType name, sharedOpt questionToken, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( SyntaxKind::MethodSignature, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, name, typeParameters, @@ -662,7 +662,7 @@ namespace ts { // // @api // function updateMethodSignature( // node: MethodSignature, -// optional modifiers, +// sharedOpt modifiers, // name: PropertyName, // sharedOpt questionToken, // typeParameters: NodeArray | undefined, @@ -681,13 +681,13 @@ namespace ts { // // @api shared Factory::createMethodDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, sharedOpt questionToken, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt body ) { @@ -725,13 +725,13 @@ namespace ts { // // @api // function updateMethodDeclaration( // node: MethodDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: PropertyName, // sharedOpt questionToken, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -750,8 +750,8 @@ namespace ts { // // @api shared Factory::createClassStaticBlockDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, shared body ) { auto node = createBaseNamedDeclaration( @@ -768,8 +768,8 @@ namespace ts { // // @api // function updateClassStaticBlockDeclaration( // node: ClassStaticBlockDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // shared block // ): ClassStaticBlockDeclaration { // return node->decorators != decorators @@ -781,9 +781,9 @@ namespace ts { // @api shared Factory::createConstructorDeclaration( - optional decorators, - optional modifiers, - NodeArray parameters, + sharedOpt decorators, + sharedOpt modifiers, + shared parameters, sharedOpt body ) { auto node = createBaseFunctionLikeDeclaration( @@ -803,9 +803,9 @@ namespace ts { // // @api // function updateConstructorDeclaration( // node: ConstructorDeclaration, -// optional decorators, -// optional modifiers, -// NodeArray parameters, +// sharedOpt decorators, +// sharedOpt modifiers, +// shared parameters, // sharedOpt body // ) { // return node->decorators != decorators @@ -818,10 +818,10 @@ namespace ts { // // @api shared Factory::createGetAccessorDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - NodeArray parameters, + shared parameters, sharedOpt type, sharedOpt body ) { @@ -840,10 +840,10 @@ namespace ts { // // @api // function updateGetAccessorDeclaration( // node: GetAccessorDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: PropertyName, -// NodeArray parameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -859,10 +859,10 @@ namespace ts { // @api shared Factory::createSetAccessorDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - NodeArray parameters, + shared parameters, sharedOpt body ) { return createBaseFunctionLikeDeclaration( @@ -880,10 +880,10 @@ namespace ts { // // @api // function updateSetAccessorDeclaration( // node: SetAccessorDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: PropertyName, -// NodeArray parameters, +// shared parameters, // sharedOpt body // ) { // return node->decorators != decorators @@ -897,14 +897,14 @@ namespace ts { // // @api shared Factory::createCallSignature( - optional typeParameters, - NodeTypeArray(ParameterDeclaration) parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( SyntaxKind::CallSignature, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, /*name*/ {}, typeParameters, parameters, @@ -930,14 +930,14 @@ namespace ts { // // @api shared Factory::createConstructSignature( - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( SyntaxKind::ConstructSignature, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, /*name*/ {}, typeParameters, parameters, @@ -963,9 +963,9 @@ namespace ts { // // @api shared Factory::createIndexSignature( - optional decorators, - optional modifiers, - NodeArray parameters, + sharedOpt decorators, + sharedOpt modifiers, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( @@ -984,9 +984,9 @@ namespace ts { // // @api // function updateIndexSignature( // node: IndexSignatureDeclaration, -// optional decorators, -// optional modifiers, -// NodeArray parameters, +// sharedOpt decorators, +// sharedOpt modifiers, +// shared parameters, // shared type // ) { // return node->parameters != parameters @@ -1043,7 +1043,7 @@ namespace ts { // } // @api - shared Factory::createTypeReferenceNode(NameType typeName, optional typeArguments) { + shared Factory::createTypeReferenceNode(NameType typeName, sharedOpt typeArguments) { auto node = createBaseNode(SyntaxKind::TypeReference); node->typeName = asName(typeName); if (typeArguments) node->typeArguments = parenthesizer.parenthesizeTypeArguments(createNodeArray(typeArguments)); @@ -1061,14 +1061,14 @@ namespace ts { // @api shared Factory::createFunctionTypeNode( - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( SyntaxKind::FunctionType, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, /*name*/ {}, typeParameters, parameters, @@ -1100,14 +1100,14 @@ namespace ts { // } shared Factory::createConstructorTypeNode1( - optional modifiers, - optional typeParameters, - NodeArray parameters, + sharedOpt modifiers, + sharedOpt typeParameters, + shared parameters, sharedOpt type ) { auto node = createBaseSignatureDeclaration( SyntaxKind::ConstructorType, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, /*name*/ {}, typeParameters, @@ -1120,11 +1120,11 @@ namespace ts { // /** @deprecated */ // function createConstructorTypeNode2( -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type // ): ConstructorTypeNode { -// return createConstructorTypeNode1(/*modifiers*/ {}, typeParameters, parameters, type); +// return createConstructorTypeNode1(/*modifiers*/ nullptr, typeParameters, parameters, type); // } // // // @api @@ -1136,7 +1136,7 @@ namespace ts { // // function updateConstructorTypeNode1( // node: ConstructorTypeNode, -// optional modifiers, +// sharedOpt modifiers, // typeParameters: NodeArray | undefined, // parameters: NodeArray, // sharedOpt type @@ -1160,7 +1160,7 @@ namespace ts { // } // // @api - shared Factory::createTypeQueryNode(shared exprName, optional typeArguments) { + shared Factory::createTypeQueryNode(shared exprName, sharedOpt typeArguments) { auto node = createBaseNode(SyntaxKind::TypeQuery); node->exprName = exprName; if (typeArguments) node->typeArguments = parenthesizer.parenthesizeTypeArguments(typeArguments); @@ -1177,7 +1177,7 @@ namespace ts { // } // // @api - shared Factory::createTypeLiteralNode(optional members) { + shared Factory::createTypeLiteralNode(sharedOpt members) { auto node = createBaseNode(SyntaxKind::TypeLiteral); node->members = createNodeArray(members); node->transformFlags = (int) TransformFlags::ContainsTypeScript; @@ -1207,7 +1207,7 @@ namespace ts { // } // // @api - shared Factory::createTupleTypeNode(NodeArray elements) { + shared Factory::createTupleTypeNode(shared elements) { auto node = createBaseNode(SyntaxKind::TupleType); node->elements = createNodeArray(parenthesizer.parenthesizeElementTypesOfTupleType(elements)); node->transformFlags = (int) TransformFlags::ContainsTypeScript; @@ -1279,7 +1279,7 @@ namespace ts { // } // @api - shared Factory::createUnionTypeNode(NodeArray types) { + shared Factory::createUnionTypeNode(shared types) { return createUnionOrIntersectionTypeNode(SyntaxKind::UnionType, types, CALLBACK(parenthesizer.parenthesizeConstituentTypesOfUnionType)); } @@ -1289,7 +1289,7 @@ namespace ts { // } // @api - shared Factory::createIntersectionTypeNode(NodeArray types) { + shared Factory::createIntersectionTypeNode(shared types) { return createUnionOrIntersectionTypeNode(SyntaxKind::IntersectionType, types, CALLBACK(parenthesizer.parenthesizeConstituentTypesOfIntersectionType)); } @@ -1335,7 +1335,7 @@ namespace ts { // } // @api - shared Factory::createTemplateLiteralType(shared head, NodeArray templateSpans) { + shared Factory::createTemplateLiteralType(shared head, shared templateSpans) { auto node = createBaseNode(SyntaxKind::TemplateLiteralType); node->head = head; node->templateSpans = createNodeArray(templateSpans); @@ -1357,13 +1357,13 @@ namespace ts { shared Factory::createImportTypeNode( shared argument, optional, shared>> qualifierOrAssertions, - optional, NodeArray>> typeArgumentsOrQualifier, - optional> isTypeOfOrTypeArguments, + optional, shared>> typeArgumentsOrQualifier, + optional>> isTypeOfOrTypeArguments, optional isTypeOf ) { sharedOpt assertion; sharedOpt qualifier; - optional typeArguments; + sharedOpt typeArguments; if (qualifierOrAssertions) { if (holds_alternative>(*qualifierOrAssertions)) { assertion = get>(*qualifierOrAssertions); @@ -1373,16 +1373,16 @@ namespace ts { } if (typeArgumentsOrQualifier) { - if (holds_alternative(*typeArgumentsOrQualifier)) { - typeArguments = get(*typeArgumentsOrQualifier); + if (holds_alternative>(*typeArgumentsOrQualifier)) { + typeArguments = get>(*typeArgumentsOrQualifier); } else if (holds_alternative>(*typeArgumentsOrQualifier)) { qualifier = get>(*typeArgumentsOrQualifier); } } if (isTypeOfOrTypeArguments) { - if (holds_alternative(*isTypeOfOrTypeArguments)) { - typeArguments = get(*isTypeOfOrTypeArguments); + if (holds_alternative>(*isTypeOfOrTypeArguments)) { + typeArguments = get>(*isTypeOfOrTypeArguments); } else if (holds_alternative(*isTypeOfOrTypeArguments)) { isTypeOf = get(*isTypeOfOrTypeArguments); } @@ -1398,15 +1398,15 @@ namespace ts { node->argument = argument; node->assertions = assertion; node->qualifier = qualifier; - if (typeArguments) node->typeArguments = parenthesizer.parenthesizeTypeArguments(*typeArguments); + if (typeArguments) node->typeArguments = parenthesizer.parenthesizeTypeArguments(typeArguments); node->isTypeOf = isTrue(isTypeOf); node->transformFlags = (int) TransformFlags::ContainsTypeScript; return node; } // // @api -// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, optional typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; -// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, optional typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; +// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, sharedOpt typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; +// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, sharedOpt typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; // function updateImportTypeNode( // node: ImportTypeNode, // argument: TypeNode, @@ -1494,7 +1494,7 @@ namespace ts { sharedOpt nameType, sharedOpt questionToken, //: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, - optional members + sharedOpt members ) { auto node = createBaseNode(SyntaxKind::MappedType); node->readonlyToken = readonlyToken; @@ -1508,7 +1508,7 @@ namespace ts { } // // @api -// function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, namesharedOpt type, questionToken: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, optional members): MappedTypeNode { +// function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, namesharedOpt type, questionToken: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, sharedOpt members): MappedTypeNode { // return node->readonlyToken != readonlyToken // || node->typeParameter != typeParameter // || node->nameType != nameType @@ -1539,7 +1539,7 @@ namespace ts { // // // // @api - shared Factory::createObjectBindingPattern(NodeArray elements) { + shared Factory::createObjectBindingPattern(shared elements) { auto node = createBaseNode(SyntaxKind::ObjectBindingPattern); node->elements = createNodeArray(elements); node->transformFlags |= @@ -1562,7 +1562,7 @@ namespace ts { // } // // @api - shared Factory::createArrayBindingPattern(NodeArray elements) { + shared Factory::createArrayBindingPattern(shared elements) { auto node = createBaseNode(SyntaxKind::ArrayBindingPattern); node->elements = createNodeArray(elements); node->transformFlags |= @@ -1588,8 +1588,8 @@ namespace ts { ) { auto node = createBaseBindingLikeDeclaration( SyntaxKind::BindingElement, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, name, initializer ? parenthesizer.parenthesizeExpressionForDisallowedComma(initializer) : nullptr ); @@ -1620,7 +1620,7 @@ namespace ts { // // // @api - shared Factory::createArrayLiteralExpression(optional elements, bool multiLine) { + shared Factory::createArrayLiteralExpression(sharedOpt elements, bool multiLine) { auto node = createBaseExpression(SyntaxKind::ArrayLiteralExpression); // Ensure we add a trailing comma for something like `[NumericLiteral(1), NumericLiteral(2), OmittedExpresion]` so that // we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like @@ -1641,7 +1641,7 @@ namespace ts { // } // @api - shared Factory::createObjectLiteralExpression(optional properties, bool multiLine) { + shared Factory::createObjectLiteralExpression(sharedOpt properties, bool multiLine) { auto node = createBaseExpression(SyntaxKind::ObjectLiteralExpression); node->properties = createNodeArray(properties); node->multiLine = multiLine; @@ -1774,7 +1774,7 @@ namespace ts { // } // // @api - shared Factory::createCallExpression(shared expression, optional typeArguments, optional argumentsArray) { + shared Factory::createCallExpression(shared expression, sharedOpt typeArguments, sharedOpt argumentsArray) { auto node = createBaseExpression(SyntaxKind::CallExpression); node->expression = parenthesizer.parenthesizeLeftSideOfAccess(expression); node->typeArguments = asNodeArray(typeArguments); @@ -1795,7 +1795,7 @@ namespace ts { } // @api - shared Factory::createCallChain(shared expression, sharedOpt questionDotToken, optional typeArguments, optional argumentsArray) { + shared Factory::createCallChain(shared expression, sharedOpt questionDotToken, sharedOpt typeArguments, sharedOpt argumentsArray) { auto node = createBaseExpression(SyntaxKind::CallExpression); node->flags |= (int) NodeFlags::OptionalChain; node->expression = parenthesizer.parenthesizeLeftSideOfAccess(expression); @@ -1818,7 +1818,7 @@ namespace ts { } // @api - shared Factory::updateCallChain(shared node, shared expression, sharedOpt questionDotToken, optional typeArguments, NodeArray argumentsArray) { + shared Factory::updateCallChain(shared node, shared expression, sharedOpt questionDotToken, sharedOpt typeArguments, shared argumentsArray) { Debug::asserts(!!(node->flags & (int) NodeFlags::OptionalChain), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); return node->expression != expression || node->questionDotToken != questionDotToken @@ -1829,7 +1829,7 @@ namespace ts { } // @api - shared Factory::updateCallExpression(shared node, shared expression, optional typeArguments, NodeArray argumentsArray) { + shared Factory::updateCallExpression(shared node, shared expression, sharedOpt typeArguments, shared argumentsArray) { if (isCallChain(node)) { return updateCallChain(node, expression, node->questionDotToken, typeArguments, argumentsArray); } @@ -1841,11 +1841,11 @@ namespace ts { } // @api - shared Factory::createNewExpression(shared expression, optional typeArguments, optional argumentsArray) { + shared Factory::createNewExpression(shared expression, sharedOpt typeArguments, sharedOpt argumentsArray) { auto node = createBaseExpression(SyntaxKind::NewExpression); node->expression = parenthesizer.parenthesizeExpressionOfNew(expression); node->typeArguments = asNodeArray(typeArguments); - if (argumentsArray) node->arguments = parenthesizer.parenthesizeExpressionsOfCommaDelimitedList(*argumentsArray); + if (argumentsArray) node->arguments = parenthesizer.parenthesizeExpressionsOfCommaDelimitedList(argumentsArray); node->transformFlags |= propagateChildFlags(node->expression) | propagateChildrenFlags(node->typeArguments) | @@ -1858,7 +1858,7 @@ namespace ts { } // // @api -// function updateNewExpression(node: NewExpression, shared expression, optional typeArguments, optional argumentsArray) { +// function updateNewExpression(node: NewExpression, shared expression, sharedOpt typeArguments, sharedOpt argumentsArray) { // return node->expression != expression // || node->typeArguments != typeArguments // || node->arguments != argumentsArray @@ -1867,7 +1867,7 @@ namespace ts { // } // @api - shared Factory::createTaggedTemplateExpression(shared tag, optional typeArguments, shared templateLiteral) { + shared Factory::createTaggedTemplateExpression(shared tag, sharedOpt typeArguments, shared templateLiteral) { auto node = createBaseExpression(SyntaxKind::TaggedTemplateExpression); node->tag = parenthesizer.parenthesizeLeftSideOfAccess(tag); node->typeArguments = asNodeArray(typeArguments); @@ -1887,7 +1887,7 @@ namespace ts { } // // // @api -// function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, optional typeArguments, template: TemplateLiteral) { +// function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, sharedOpt typeArguments, template: TemplateLiteral) { // return node->tag != tag // || node->typeArguments != typeArguments // || node->template != template @@ -1932,17 +1932,17 @@ namespace ts { // @api shared Factory::createFunctionExpression( - optional modifiers, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, - optional typeParameters, - optional parameters, + sharedOpt typeParameters, + sharedOpt parameters, sharedOpt type, shared body ) { auto node = createBaseFunctionLikeDeclaration( SyntaxKind::FunctionExpression, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, name, typeParameters, @@ -1970,11 +1970,11 @@ namespace ts { // // @api // function updateFunctionExpression( // node: FunctionExpression, -// optional modifiers, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: Identifier | undefined, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // shared block // ) { @@ -1990,16 +1990,16 @@ namespace ts { // } // @api shared Factory::createArrowFunction( - optional modifiers, - optional typeParameters, - NodeArray parameters, + sharedOpt modifiers, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt equalsGreaterThanToken, shared body ) { auto node = createBaseFunctionLikeDeclaration( SyntaxKind::ArrowFunction, - /*decorators*/ {}, + /*decorators*/ nullptr, modifiers, /*name*/ {}, typeParameters, @@ -2020,9 +2020,9 @@ namespace ts { // // @api // function updateArrowFunction( // node: ArrowFunction, -// optional modifiers, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt modifiers, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // equalsGreaterThanToken: EqualsGreaterThanToken, // body: ConciseBody @@ -2253,7 +2253,7 @@ namespace ts { // } // @api - shared Factory::createTemplateExpression(shared head, NodeArray templateSpans) { + shared Factory::createTemplateExpression(shared head, shared templateSpans) { auto node = createBaseExpression(SyntaxKind::TemplateExpression); node->head = head; node->templateSpans = createNodeArray(templateSpans); @@ -2358,12 +2358,12 @@ namespace ts { // @api shared Factory::createClassExpression( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses, - NodeArray members + sharedOpt typeParameters, + sharedOpt heritageClauses, + shared members ) { auto node = createBaseClassLikeDeclaration( SyntaxKind::ClassExpression, @@ -2381,12 +2381,12 @@ namespace ts { // // @api // function updateClassExpression( // node: ClassExpression, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier | undefined, -// optional typeParameters, -// optional heritageClauses, -// NodeArray members +// sharedOpt typeParameters, +// sharedOpt heritageClauses, +// shared members // ) { // return node->decorators != decorators // || node->modifiers != modifiers @@ -2404,7 +2404,7 @@ namespace ts { } // @api - shared Factory::createExpressionWithTypeArguments(shared expression, optional typeArguments) { + shared Factory::createExpressionWithTypeArguments(shared expression, sharedOpt typeArguments) { auto node = createBaseNode(SyntaxKind::ExpressionWithTypeArguments); node->expression = parenthesizer.parenthesizeLeftSideOfAccess(expression); if (typeArguments) node->typeArguments = parenthesizer.parenthesizeTypeArguments(typeArguments); @@ -2416,7 +2416,7 @@ namespace ts { } // // @api -// function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, shared expression, optional typeArguments) { +// function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, shared expression, sharedOpt typeArguments) { // return node->expression != expression // || node->typeArguments != typeArguments // ? update(createExpressionWithTypeArguments(expression, typeArguments), node) @@ -2544,7 +2544,7 @@ namespace ts { // // @api - shared Factory::createBlock(NodeArray statements, bool multiLine) { + shared Factory::createBlock(shared statements, bool multiLine) { auto node = createBaseNode(SyntaxKind::Block); node->statements = createNodeArray(statements); node->multiLine = multiLine; @@ -2553,7 +2553,7 @@ namespace ts { } // @api - shared Factory::createVariableDeclarationList(NodeArray declarations, int flags) { + shared Factory::createVariableDeclarationList(shared declarations, int flags) { auto node = createBaseNode(SyntaxKind::VariableDeclarationList); node->flags |= flags & (int) NodeFlags::BlockScoped; node->declarations = declarations; @@ -2580,8 +2580,8 @@ namespace ts { // } // @api - shared Factory::createVariableStatement(optional modifiers, variant, vector>> declarationList) { - auto node = createBaseDeclaration(SyntaxKind::VariableStatement, /*decorators*/ {}, modifiers); + shared Factory::createVariableStatement(sharedOpt modifiers, variant, vector>> declarationList) { + auto node = createBaseDeclaration(SyntaxKind::VariableStatement, /*decorators*/ nullptr, modifiers); if (holds_alternative>(declarationList)) { node->declarationList = get>(declarationList); @@ -2597,7 +2597,7 @@ namespace ts { } // // @api -// function updateVariableStatement(node: VariableStatement, optional modifiers, declarationList: VariableDeclarationList) { +// function updateVariableStatement(node: VariableStatement, sharedOpt modifiers, declarationList: VariableDeclarationList) { // return node->modifiers != modifiers // || node->declarationList != declarationList // ? update(createVariableStatement(modifiers, declarationList), node) @@ -2933,8 +2933,8 @@ namespace ts { shared Factory::createVariableDeclaration(NameType name, sharedOpt exclamationToken, sharedOpt type, sharedOpt initializer) { auto node = createBaseVariableLikeDeclaration( SyntaxKind::VariableDeclaration, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, name, type, initializer ? parenthesizer.parenthesizeExpressionForDisallowedComma(initializer) : nullptr @@ -2967,12 +2967,12 @@ namespace ts { // @api shared Factory::createFunctionDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt body ) { @@ -3009,12 +3009,12 @@ namespace ts { // // @api // function updateFunctionDeclaration( // node: FunctionDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: Identifier | undefined, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -3032,12 +3032,12 @@ namespace ts { // // @api shared Factory::createClassDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses, - NodeArray members + sharedOpt typeParameters, + sharedOpt heritageClauses, + shared members ) { auto node = createBaseClassLikeDeclaration( SyntaxKind::ClassDeclaration, @@ -3062,12 +3062,12 @@ namespace ts { // // @api // function updateClassDeclaration( // node: ClassDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier | undefined, -// optional typeParameters, -// optional heritageClauses, -// NodeArray members +// sharedOpt typeParameters, +// sharedOpt heritageClauses, +// shared members // ) { // return node->decorators != decorators // || node->modifiers != modifiers @@ -3081,11 +3081,11 @@ namespace ts { // // // @api // function createInterfaceDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, -// optional typeParameters, -// optional heritageClauses, +// sharedOpt typeParameters, +// sharedOpt heritageClauses, // members: readonly TypeElement[] // ) { // auto node = createBaseInterfaceOrClassLikeDeclaration( @@ -3104,11 +3104,11 @@ namespace ts { // // @api // function updateInterfaceDeclaration( // node: InterfaceDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, -// optional typeParameters, -// optional heritageClauses, +// sharedOpt typeParameters, +// sharedOpt heritageClauses, // members: readonly TypeElement[] // ) { // return node->decorators != decorators @@ -3123,10 +3123,10 @@ namespace ts { // // // @api // function createTypeAliasDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, -// optional typeParameters, +// sharedOpt typeParameters, // shared type // ) { // auto node = createBaseGenericNamedDeclaration( @@ -3144,10 +3144,10 @@ namespace ts { // // @api // function updateTypeAliasDeclaration( // node: TypeAliasDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, -// optional typeParameters, +// sharedOpt typeParameters, // shared type // ) { // return node->decorators != decorators @@ -3161,8 +3161,8 @@ namespace ts { // // // @api // function createEnumDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, // members: readonly EnumMember[] // ) { @@ -3183,8 +3183,8 @@ namespace ts { // // @api // function updateEnumDeclaration( // node: EnumDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, // members: readonly EnumMember[]) { // return node->decorators != decorators @@ -3197,8 +3197,8 @@ namespace ts { // // // @api // function createModuleDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: ModuleName, // body: ModuleBody | undefined, // flags = NodeFlags::None @@ -3227,8 +3227,8 @@ namespace ts { // // @api // function updateModuleDeclaration( // node: ModuleDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: ModuleName, // body: ModuleBody | undefined // ) { @@ -3274,8 +3274,8 @@ namespace ts { // function createNamespaceExportDeclaration(name: string | Identifier) { // auto node = createBaseNamedDeclaration( // SyntaxKind::NamespaceExportDeclaration, -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // name // ); // node->transformFlags = (int)TransformFlags::ContainsTypeScript; @@ -3291,8 +3291,8 @@ namespace ts { // // // @api // function createImportEqualsDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // name: string | Identifier, // moduleReference: ModuleReference @@ -3314,8 +3314,8 @@ namespace ts { // // @api // function updateImportEqualsDeclaration( // node: ImportEqualsDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // name: Identifier, // moduleReference: ModuleReference @@ -3331,8 +3331,8 @@ namespace ts { // // // @api // function createImportDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // importClause: ImportClause | undefined, // moduleSpecifier: Expression, // assertClause: AssertClause | undefined @@ -3355,8 +3355,8 @@ namespace ts { // // @api // function updateImportDeclaration( // node: ImportDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // importClause: ImportClause | undefined, // moduleSpecifier: Expression, // assertClause: AssertClause | undefined @@ -3396,7 +3396,7 @@ namespace ts { // } // // @api - shared Factory::createAssertClause(NodeArray elements, bool multiLine) { + shared Factory::createAssertClause(shared elements, bool multiLine) { auto node = createBaseNode(SyntaxKind::AssertClause); node->elements = createNodeArray(elements); node->multiLine = multiLine; @@ -3519,8 +3519,8 @@ namespace ts { // // // @api // function createExportAssignment( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isExportEquals: boolean | undefined, // shared expression // ) { @@ -3541,8 +3541,8 @@ namespace ts { // // @api // function updateExportAssignment( // node: ExportAssignment, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // shared expression // ) { // return node->decorators != decorators @@ -3554,8 +3554,8 @@ namespace ts { // // // @api // function createExportDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // exportClause: NamedExportBindings | undefined, // moduleSpecifier?: Expression, @@ -3580,8 +3580,8 @@ namespace ts { // // @api // function updateExportDeclaration( // node: ExportDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // exportClause: NamedExportBindings | undefined, // moduleSpecifier: Expression | undefined, @@ -3639,7 +3639,7 @@ namespace ts { shared Factory::createMissingDeclaration() { auto node = createBaseDeclaration( SyntaxKind::MissingDeclaration, - /*decorators*/ {}, + /*decorators*/ nullptr, /*modifiers*/ {} ); return node; @@ -3718,11 +3718,11 @@ namespace ts { // } // // // @api -// function createJSDocFunctionType(NodeArray parameters, sharedOpt type): JSDocFunctionType { +// function createJSDocFunctionType(shared parameters, sharedOpt type): JSDocFunctionType { // auto node = createBaseSignatureDeclaration( // SyntaxKind::JSDocFunctionType, -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // /*name*/ {}, // /*typeParameters*/ {}, // parameters, @@ -3732,7 +3732,7 @@ namespace ts { // } // // // @api -// function updateJSDocFunctionType(node: JSDocFunctionType, NodeArray parameters, sharedOpt type): JSDocFunctionType { +// function updateJSDocFunctionType(node: JSDocFunctionType, shared parameters, sharedOpt type): JSDocFunctionType { // return node->parameters != parameters // || node->type != type // ? update(createJSDocFunctionType(parameters, type), node) @@ -4129,7 +4129,7 @@ namespace ts { // // // // @api - shared Factory::createJsxElement(shared openingElement, NodeArray children, shared closingElement) { + shared Factory::createJsxElement(shared openingElement, shared children, shared closingElement) { auto node = createBaseNode(SyntaxKind::JsxElement); node->openingElement = openingElement; node->children = createNodeArray(children); @@ -4152,7 +4152,7 @@ namespace ts { // } // @api - shared Factory::createJsxSelfClosingElement(shared tagName, optional typeArguments, shared attributes) { + shared Factory::createJsxSelfClosingElement(shared tagName, sharedOpt typeArguments, shared attributes) { auto node = createBaseNode(SyntaxKind::JsxSelfClosingElement); node->tagName = tagName; node->typeArguments = asNodeArray(typeArguments); @@ -4169,7 +4169,7 @@ namespace ts { } // // // @api -// function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, optional typeArguments, attributes: JsxAttributes) { +// function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, sharedOpt typeArguments, attributes: JsxAttributes) { // return node->tagName != tagName // || node->typeArguments != typeArguments // || node->attributes != attributes @@ -4178,7 +4178,7 @@ namespace ts { // } // // @api - shared Factory::createJsxOpeningElement(shared tagName, optional typeArguments, shared attributes) { + shared Factory::createJsxOpeningElement(shared tagName, sharedOpt typeArguments, shared attributes) { auto node = createBaseNode(SyntaxKind::JsxOpeningElement); node->tagName = tagName; node->typeArguments = asNodeArray(typeArguments); @@ -4195,7 +4195,7 @@ namespace ts { } // // // @api -// function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, optional typeArguments, attributes: JsxAttributes) { +// function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, sharedOpt typeArguments, attributes: JsxAttributes) { // return node->tagName != tagName // || node->typeArguments != typeArguments // || node->attributes != attributes @@ -4221,7 +4221,7 @@ namespace ts { // } // @api - shared Factory::createJsxFragment(shared openingFragment, NodeArray children, shared closingFragment) { + shared Factory::createJsxFragment(shared openingFragment, shared children, shared closingFragment) { auto node = createBaseNode(SyntaxKind::JsxFragment); node->openingFragment = openingFragment; node->children = createNodeArray(children); @@ -4287,7 +4287,7 @@ namespace ts { // } // // @api - shared Factory::createJsxAttributes(NodeArray properties) { + shared Factory::createJsxAttributes(shared properties) { auto node = createBaseNode(SyntaxKind::JsxAttributes); node->properties = createNodeArray(properties); node->transformFlags |= @@ -4378,7 +4378,7 @@ namespace ts { // } // @api - shared Factory::createHeritageClause(SyntaxKind token, NodeArray types) { + shared Factory::createHeritageClause(SyntaxKind token, shared types) { auto node = createBaseNode(SyntaxKind::HeritageClause); node->token = token; node->types = createNodeArray(types); @@ -4439,8 +4439,8 @@ namespace ts { shared Factory::createPropertyAssignment(NameType name, shared initializer) { auto node = createBaseNamedDeclaration( SyntaxKind::PropertyAssignment, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, name ); node->initializer = parenthesizer.parenthesizeExpressionForDisallowedComma(initializer); @@ -4471,8 +4471,8 @@ namespace ts { shared Factory::createShorthandPropertyAssignment(NameType name, sharedOpt objectAssignmentInitializer) { auto node = createBaseNamedDeclaration( SyntaxKind::ShorthandPropertyAssignment, - /*decorators*/ {}, - /*modifiers*/ {}, + /*decorators*/ nullptr, + /*modifiers*/ nullptr, name ); node->objectAssignmentInitializer = objectAssignmentInitializer ? parenthesizer.parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer) : nullptr; @@ -4859,7 +4859,7 @@ namespace ts { // function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { // return createCallExpression( // createFunctionExpression( -// /*modifiers*/ {}, +// /*modifiers*/ nullptr, // /*asteriskToken*/ {}, // /*name*/ {}, // /*typeParameters*/ {}, @@ -4877,7 +4877,7 @@ namespace ts { // function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { // return createCallExpression( // createArrowFunction( -// /*modifiers*/ {}, +// /*modifiers*/ nullptr, // /*typeParameters*/ {}, // /*parameters*/ param ? [param] : [], // /*type*/ {}, @@ -4895,16 +4895,16 @@ namespace ts { // // function createExportDefault(shared expression) { // return createExportAssignment( -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // /*isExportEquals*/ false, // expression); // } // // function createExternalModuleExport(exportName: Identifier) { // return createExportDeclaration( -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // /*isTypeOnly*/ false, // createNamedExports([ // createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ {}, exportName) @@ -5162,12 +5162,12 @@ namespace ts { // createParenthesizedExpression( // createObjectLiteralExpression([ // createSetAccessorDeclaration( -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // "value", // [createParameterDeclaration( -// /*decorators*/ {}, -// /*modifiers*/ {}, +// /*decorators*/ nullptr, +// /*modifiers*/ nullptr, // /*dotDotDotToken*/ {}, // paramName, // /*questionToken*/ {}, @@ -5387,7 +5387,7 @@ namespace ts { // } // // /** -// * Lifts a NodeArray containing only Statement nodes to a block. +// * Lifts a shared containing only Statement nodes to a block. // * // * @param nodes The NodeArray. // */ diff --git a/src/factory.h b/src/factory.h index 52fd4ca..3c07a92 100644 --- a/src/factory.h +++ b/src/factory.h @@ -2,6 +2,7 @@ #include +#include "Tracy.hpp" #include "types.h" #include "utilities.h" #include "scanner.h" @@ -40,31 +41,31 @@ namespace ts { int propagateIdentifierNameFlags(shared node); - int propagateChildrenFlags(optional children); + int propagateChildrenFlags(sharedOpt children); - void aggregateChildrenFlags(NodeArray &children); + void aggregateChildrenFlags(shared &children); - NodeArray createNodeArray(optional elements, optional hasTrailingComma = {}); + shared createNodeArray(sharedOpt elements, optional hasTrailingComma = {}); - optional asNodeArray(optional array); + sharedOpt asNodeArray(sharedOpt elements); template - NodeArray asNodeArray(vector> array) { - NodeArray nodeArray; - for (auto node: array) nodeArray.list.push_back(node); + inline shared asNodeArray(const vector> &array) { + auto nodeArray = make_shared(); + for (auto node: array) nodeArray->list.push_back(node); return nodeArray; } - template - optional asNodeArray(optional>> array) { - if (!array) return nullopt; - - return asNodeArray(*array); - } +// template +// sharedOpt asNodeArray(optional>> &array) { +// if (!array) return nullptr; +// +// return asNodeArray(*array); +// } // @api template - NodeArray createNodeArray(vector> elements, optional hasTrailingComma = {}) { + shared createNodeArray(const vector> &elements, optional hasTrailingComma = {}) { // Since the element list of a node array is typically created by starting with an empty array and // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. @@ -217,8 +218,8 @@ namespace ts { template shared createBaseDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers + sharedOpt decorators, + sharedOpt modifiers ) { auto node = createBaseNode(kind); node->decorators = asNodeArray(decorators); @@ -257,8 +258,8 @@ namespace ts { template shared createBaseNamedDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, optional _name ) { auto node = createBaseDeclaration( @@ -295,10 +296,10 @@ namespace ts { template shared createBaseGenericNamedDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters + sharedOpt typeParameters ) { auto node = createBaseNamedDeclaration( kind, @@ -315,11 +316,11 @@ namespace ts { template shared createBaseSignatureDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional parameters, + sharedOpt typeParameters, + sharedOpt parameters, sharedOpt type ) { auto node = createBaseGenericNamedDeclaration( @@ -347,11 +348,11 @@ namespace ts { template shared createBaseFunctionLikeDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional parameters, + sharedOpt typeParameters, + sharedOpt parameters, sharedOpt type, decltype(declval().body) body ) { @@ -380,11 +381,11 @@ namespace ts { template shared createBaseInterfaceOrClassLikeDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses + sharedOpt typeParameters, + sharedOpt heritageClauses ) { auto node = createBaseGenericNamedDeclaration( kind, @@ -401,12 +402,12 @@ namespace ts { template shared createBaseClassLikeDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses, - NodeArray members + sharedOpt typeParameters, + sharedOpt heritageClauses, + shared members ) { auto node = createBaseInterfaceOrClassLikeDeclaration( kind, @@ -424,8 +425,8 @@ namespace ts { template shared createBaseBindingLikeDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, optional name, sharedOpt initializer ) { @@ -443,8 +444,8 @@ namespace ts { template shared createBaseVariableLikeDeclaration( SyntaxKind kind, - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, optional name, sharedOpt type, sharedOpt initializer @@ -490,7 +491,7 @@ namespace ts { shared createBaseGeneratedIdentifier(string text, GeneratedIdentifierFlags autoGenerateFlags); // @api - shared createIdentifier(string text, optional typeArguments = {}, optional originalKeywordKind = {}); + shared createIdentifier(string text, sharedOpt typeArguments = {}, optional originalKeywordKind = {}); // // // @api // function updateIdentifier(node: Identifier, typeArguments?: NodeArray | undefined): Identifier { @@ -602,18 +603,18 @@ namespace ts { // // // // // @api -// function createTypeParameterDeclaration(optional modifiers, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; +// function createTypeParameterDeclaration(sharedOpt modifiers, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; // /** @deprecated */ // function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; shared createTypeParameterDeclaration( - optional, string>> modifiersOrName, + optional, shared, string>> modifiersOrName, optional, shared, string>> nameOrConstraint, sharedOpt constraintOrDefault, sharedOpt defaultType = nullptr ); // // @api -// function updateTypeParameterDeclaration(node: TypeParameterDeclaration, optional modifiers, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; +// function updateTypeParameterDeclaration(node: TypeParameterDeclaration, sharedOpt modifiers, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; // /** @deprecated */ // function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultsharedOpt type): TypeParameterDeclaration; // function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiersOrName: readonly Modifier[] | Identifier | undefined, nameOrConstraint: Identifier | TypeNode | undefined, constraintOrDefault: TypeNode | undefined, defaultType?: TypeNode | undefined) { @@ -640,8 +641,8 @@ namespace ts { // @api shared createParameterDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt dotDotDotToken = nullptr, NameType name = "", sharedOpt questionToken = nullptr, @@ -652,8 +653,8 @@ namespace ts { // // @api // function updateParameterDeclaration( // node: ParameterDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // dotDotDotToken: DotDotDotToken | undefined, // name: string | BindingName, // sharedOpt questionToken, @@ -687,7 +688,7 @@ namespace ts { // // @api shared createPropertySignature( - optional modifiers, + sharedOpt modifiers, NameType name, sharedOpt questionToken, sharedOpt type @@ -696,7 +697,7 @@ namespace ts { // // @api // function updatePropertySignature( // node: PropertySignature, -// optional modifiers, +// sharedOpt modifiers, // name: PropertyName, // sharedOpt questionToken, // sharedOpt type @@ -711,8 +712,8 @@ namespace ts { // @api shared createPropertyDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, sharedOpt questionOrExclamationToken, sharedOpt type, @@ -722,8 +723,8 @@ namespace ts { // // @api // function updatePropertyDeclaration( // node: PropertyDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // NameType name, // questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, // sharedOpt type, @@ -742,18 +743,18 @@ namespace ts { // // @api shared createMethodSignature( - optional modifiers, + sharedOpt modifiers, NameType name, sharedOpt questionToken, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ); // // @api // function updateMethodSignature( // node: MethodSignature, -// optional modifiers, +// sharedOpt modifiers, // name: PropertyName, // sharedOpt questionToken, // typeParameters: NodeArray | undefined, @@ -772,13 +773,13 @@ namespace ts { // // @api shared createMethodDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, sharedOpt questionToken, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt body ); @@ -786,13 +787,13 @@ namespace ts { // // @api // function updateMethodDeclaration( // node: MethodDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: PropertyName, // sharedOpt questionToken, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -811,16 +812,16 @@ namespace ts { // // @api shared createClassStaticBlockDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, shared body ); // // // @api // function updateClassStaticBlockDeclaration( // node: ClassStaticBlockDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // shared block // ): ClassStaticBlockDeclaration { // return node->decorators != decorators @@ -832,18 +833,18 @@ namespace ts { // @api shared createConstructorDeclaration( - optional decorators, - optional modifiers, - NodeArray parameters, + sharedOpt decorators, + sharedOpt modifiers, + shared parameters, sharedOpt body ); // // @api // function updateConstructorDeclaration( // node: ConstructorDeclaration, -// optional decorators, -// optional modifiers, -// NodeArray parameters, +// sharedOpt decorators, +// sharedOpt modifiers, +// shared parameters, // sharedOpt body // ) { // return node->decorators != decorators @@ -856,10 +857,10 @@ namespace ts { // // @api shared createGetAccessorDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - NodeArray parameters, + shared parameters, sharedOpt type, sharedOpt body ); @@ -867,10 +868,10 @@ namespace ts { // // @api // function updateGetAccessorDeclaration( // node: GetAccessorDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: PropertyName, -// NodeArray parameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -886,20 +887,20 @@ namespace ts { // @api shared createSetAccessorDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - NodeArray parameters, + shared parameters, sharedOpt body ); // // @api // function updateSetAccessorDeclaration( // node: SetAccessorDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: PropertyName, -// NodeArray parameters, +// shared parameters, // sharedOpt body // ) { // return node->decorators != decorators @@ -913,8 +914,8 @@ namespace ts { // // @api shared createCallSignature( - optional typeParameters, - NodeTypeArray(ParameterDeclaration) parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ); @@ -934,8 +935,8 @@ namespace ts { // // @api shared createConstructSignature( - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ); // @@ -955,18 +956,18 @@ namespace ts { // // @api shared createIndexSignature( - optional decorators, - optional modifiers, - NodeArray parameters, + sharedOpt decorators, + sharedOpt modifiers, + shared parameters, sharedOpt type ); // // @api // function updateIndexSignature( // node: IndexSignatureDeclaration, -// optional decorators, -// optional modifiers, -// NodeArray parameters, +// sharedOpt decorators, +// sharedOpt modifiers, +// shared parameters, // shared type // ) { // return node->parameters != parameters @@ -1010,7 +1011,7 @@ namespace ts { // } // @api - shared createTypeReferenceNode(NameType typeName, optional typeArguments); + shared createTypeReferenceNode(NameType typeName, sharedOpt typeArguments); // // @api // function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { @@ -1022,8 +1023,8 @@ namespace ts { // @api shared createFunctionTypeNode( - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type ); @@ -1049,19 +1050,19 @@ namespace ts { // } shared createConstructorTypeNode1( - optional modifiers, - optional typeParameters, - NodeArray parameters, + sharedOpt modifiers, + sharedOpt typeParameters, + shared parameters, sharedOpt type ); // /** @deprecated */ // function createConstructorTypeNode2( -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type // ): ConstructorTypeNode { -// return createConstructorTypeNode1(/*modifiers*/ {}, typeParameters, parameters, type); +// return createConstructorTypeNode1(/*modifiers*/ nullptr, typeParameters, parameters, type); // } // // // @api @@ -1073,7 +1074,7 @@ namespace ts { // // function updateConstructorTypeNode1( // node: ConstructorTypeNode, -// optional modifiers, +// sharedOpt modifiers, // typeParameters: NodeArray | undefined, // parameters: NodeArray, // sharedOpt type @@ -1097,7 +1098,7 @@ namespace ts { // } // // @api - shared createTypeQueryNode(shared exprName, optional typeArguments); + shared createTypeQueryNode(shared exprName, sharedOpt typeArguments); // // @api // function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]) { @@ -1108,7 +1109,7 @@ namespace ts { // } // // @api - shared createTypeLiteralNode(optional members); + shared createTypeLiteralNode(sharedOpt members); // // // @api // function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { @@ -1128,7 +1129,7 @@ namespace ts { // } // // @api - shared createTupleTypeNode(NodeArray elements); + shared createTupleTypeNode(shared elements); // // @api // function updateTupleTypeNode(node: TupleTypeNode, elements: readonly (TypeNode | NamedTupleMember)[]) { @@ -1176,7 +1177,7 @@ namespace ts { // } template - shared createUnionOrIntersectionTypeNode(SyntaxKind kind, NodeArray types, function parenthesize) { + shared createUnionOrIntersectionTypeNode(SyntaxKind kind, shared types, function(shared)> parenthesize) { auto node = createBaseNode(kind); node->types = createNodeArray(parenthesize(types)); node->transformFlags = (int) TransformFlags::ContainsTypeScript; @@ -1190,7 +1191,7 @@ namespace ts { // } // @api - shared createUnionTypeNode(NodeArray types); + shared createUnionTypeNode(shared types); // // @api // function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray) { @@ -1198,7 +1199,7 @@ namespace ts { // } // @api - shared createIntersectionTypeNode(NodeArray types); + shared createIntersectionTypeNode(shared types); // // @api // function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray) { @@ -1229,7 +1230,7 @@ namespace ts { // } // @api - shared createTemplateLiteralType(shared head, NodeArray templateSpans); + shared createTemplateLiteralType(shared head, shared templateSpans); // // @api // function updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]) { @@ -1245,14 +1246,14 @@ namespace ts { shared createImportTypeNode( shared argument, optional, shared>> qualifierOrAssertions, - optional, NodeArray>> typeArgumentsOrQualifier, - optional> isTypeOfOrTypeArguments, + optional, shared>> typeArgumentsOrQualifier, + optional>> isTypeOfOrTypeArguments, optional isTypeOf ); // // @api -// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, optional typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; -// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, optional typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; +// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, sharedOpt typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; +// function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, sharedOpt typeArguments, isTypeOf?: boolean | undefined): ImportTypeNode; // function updateImportTypeNode( // node: ImportTypeNode, // argument: TypeNode, @@ -1317,11 +1318,11 @@ namespace ts { sharedOpt nameType, sharedOpt questionToken, //: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, - optional members + sharedOpt members ); // // @api -// function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, namesharedOpt type, questionToken: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, optional members): MappedTypeNode { +// function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, namesharedOpt type, questionToken: QuestionToken | PlusToken | MinusToken | undefined, sharedOpt type, sharedOpt members): MappedTypeNode { // return node->readonlyToken != readonlyToken // || node->typeParameter != typeParameter // || node->nameType != nameType @@ -1347,7 +1348,7 @@ namespace ts { // // // // @api - shared createObjectBindingPattern(NodeArray elements); + shared createObjectBindingPattern(shared elements); // // @api // function updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]) { @@ -1357,7 +1358,7 @@ namespace ts { // } // // @api - shared createArrayBindingPattern(NodeArray elements); + shared createArrayBindingPattern(shared elements); // // @api // function updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]) { @@ -1390,13 +1391,14 @@ namespace ts { template shared createBaseExpression(SyntaxKind kind) { + ZoneScoped; auto node = createBaseNode(kind); // the following properties are commonly set by the checker/binder return node; } // @api - shared createArrayLiteralExpression(optional elements, bool multiLine); + shared createArrayLiteralExpression(sharedOpt elements, bool multiLine); // // @api // function updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]) { @@ -1406,7 +1408,7 @@ namespace ts { // } // @api - shared createObjectLiteralExpression(optional properties, bool multiLine); + shared createObjectLiteralExpression(sharedOpt properties, bool multiLine); // // @api // function updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) { @@ -1475,22 +1477,22 @@ namespace ts { // } // // @api - shared createCallExpression(shared expression, optional typeArguments, optional argumentsArray); + shared createCallExpression(shared expression, sharedOpt typeArguments, sharedOpt argumentsArray); // @api - shared createCallChain(shared expression, sharedOpt questionDotToken, optional typeArguments, optional argumentsArray); + shared createCallChain(shared expression, sharedOpt questionDotToken, sharedOpt typeArguments, sharedOpt argumentsArray); // @api - shared updateCallChain(shared node, shared expression, sharedOpt questionDotToken, optional typeArguments, NodeArray argumentsArray); + shared updateCallChain(shared node, shared expression, sharedOpt questionDotToken, sharedOpt typeArguments, shared argumentsArray); // @api - shared updateCallExpression(shared node, shared expression, optional typeArguments, NodeArray argumentsArray); + shared updateCallExpression(shared node, shared expression, sharedOpt typeArguments, shared argumentsArray); // @api - shared createNewExpression(shared expression, optional typeArguments, optional argumentsArray); + shared createNewExpression(shared expression, sharedOpt typeArguments, sharedOpt argumentsArray); // // @api -// function updateNewExpression(node: NewExpression, shared expression, optional typeArguments, optional argumentsArray) { +// function updateNewExpression(node: NewExpression, shared expression, sharedOpt typeArguments, sharedOpt argumentsArray) { // return node->expression != expression // || node->typeArguments != typeArguments // || node->arguments != argumentsArray @@ -1499,10 +1501,10 @@ namespace ts { // } // @api - shared createTaggedTemplateExpression(shared tag, optional typeArguments, shared templateLiteral); + shared createTaggedTemplateExpression(shared tag, sharedOpt typeArguments, shared templateLiteral); // // // @api -// function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, optional typeArguments, template: TemplateLiteral) { +// function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, sharedOpt typeArguments, template: TemplateLiteral) { // return node->tag != tag // || node->typeArguments != typeArguments // || node->template != template @@ -1524,11 +1526,11 @@ namespace ts { // @api shared createFunctionExpression( - optional modifiers, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, - optional typeParameters, - optional parameters, + sharedOpt typeParameters, + sharedOpt parameters, sharedOpt type, shared body ); @@ -1536,11 +1538,11 @@ namespace ts { // // @api // function updateFunctionExpression( // node: FunctionExpression, -// optional modifiers, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: Identifier | undefined, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // shared block // ) { @@ -1556,9 +1558,9 @@ namespace ts { // } // @api shared createArrowFunction( - optional modifiers, - optional typeParameters, - NodeArray parameters, + sharedOpt modifiers, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt equalsGreaterThanToken, shared body @@ -1567,9 +1569,9 @@ namespace ts { // // @api // function updateArrowFunction( // node: ArrowFunction, -// optional modifiers, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt modifiers, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // equalsGreaterThanToken: EqualsGreaterThanToken, // body: ConciseBody @@ -1699,7 +1701,7 @@ namespace ts { // } // @api - shared createTemplateExpression(shared head, NodeArray templateSpans); + shared createTemplateExpression(shared head, shared templateSpans); // // @api // function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]) { @@ -1775,23 +1777,23 @@ namespace ts { // @api shared createClassExpression( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses, - NodeArray members + sharedOpt typeParameters, + sharedOpt heritageClauses, + shared members ); // // @api // function updateClassExpression( // node: ClassExpression, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier | undefined, -// optional typeParameters, -// optional heritageClauses, -// NodeArray members +// sharedOpt typeParameters, +// sharedOpt heritageClauses, +// shared members // ) { // return node->decorators != decorators // || node->modifiers != modifiers @@ -1807,10 +1809,10 @@ namespace ts { shared createOmittedExpression(); // @api - shared createExpressionWithTypeArguments(shared expression, optional typeArguments); + shared createExpressionWithTypeArguments(shared expression, sharedOpt typeArguments); // // @api -// function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, shared expression, optional typeArguments) { +// function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, shared expression, sharedOpt typeArguments) { // return node->expression != expression // || node->typeArguments != typeArguments // ? update(createExpressionWithTypeArguments(expression, typeArguments), node) @@ -1868,10 +1870,10 @@ namespace ts { // // @api - shared createBlock(NodeArray statements, bool multiLine); + shared createBlock(shared statements, bool multiLine); // @api - shared createVariableDeclarationList(NodeArray declarations, int flags = (int) NodeFlags::None); + shared createVariableDeclarationList(shared declarations, int flags = (int) NodeFlags::None); shared createVariableDeclarationList(vector> declarations, int flags = (int) NodeFlags::None); @@ -1883,10 +1885,10 @@ namespace ts { // } // @api - shared createVariableStatement(optional modifiers, variant, vector>> declarationList); + shared createVariableStatement(sharedOpt modifiers, variant, vector>> declarationList); // // @api -// function updateVariableStatement(node: VariableStatement, optional modifiers, declarationList: VariableDeclarationList) { +// function updateVariableStatement(node: VariableStatement, sharedOpt modifiers, declarationList: VariableDeclarationList) { // return node->modifiers != modifiers // || node->declarationList != declarationList // ? update(createVariableStatement(modifiers, declarationList), node) @@ -2224,12 +2226,12 @@ namespace ts { // @api shared createFunctionDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, sharedOpt asteriskToken, NameType name, - optional typeParameters, - NodeArray parameters, + sharedOpt typeParameters, + shared parameters, sharedOpt type, sharedOpt body ); @@ -2237,12 +2239,12 @@ namespace ts { // // @api // function updateFunctionDeclaration( // node: FunctionDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // sharedOpt asteriskToken, // name: Identifier | undefined, -// optional typeParameters, -// NodeArray parameters, +// sharedOpt typeParameters, +// shared parameters, // sharedOpt type, // sharedOpt body // ) { @@ -2260,23 +2262,23 @@ namespace ts { // // @api shared createClassDeclaration( - optional decorators, - optional modifiers, + sharedOpt decorators, + sharedOpt modifiers, NameType name, - optional typeParameters, - optional heritageClauses, - NodeArray members + sharedOpt typeParameters, + sharedOpt heritageClauses, + shared members ); // // @api // function updateClassDeclaration( // node: ClassDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier | undefined, -// optional typeParameters, -// optional heritageClauses, -// NodeArray members +// sharedOpt typeParameters, +// sharedOpt heritageClauses, +// shared members // ) { // return node->decorators != decorators // || node->modifiers != modifiers @@ -2290,11 +2292,11 @@ namespace ts { // // // @api // function createInterfaceDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, -// optional typeParameters, -// optional heritageClauses, +// sharedOpt typeParameters, +// sharedOpt heritageClauses, // members: readonly TypeElement[] // ) { // auto node = createBaseInterfaceOrClassLikeDeclaration( @@ -2313,11 +2315,11 @@ namespace ts { // // @api // function updateInterfaceDeclaration( // node: InterfaceDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, -// optional typeParameters, -// optional heritageClauses, +// sharedOpt typeParameters, +// sharedOpt heritageClauses, // members: readonly TypeElement[] // ) { // return node->decorators != decorators @@ -2332,10 +2334,10 @@ namespace ts { // // // @api // function createTypeAliasDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, -// optional typeParameters, +// sharedOpt typeParameters, // shared type // ) { // auto node = createBaseGenericNamedDeclaration( @@ -2353,10 +2355,10 @@ namespace ts { // // @api // function updateTypeAliasDeclaration( // node: TypeAliasDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, -// optional typeParameters, +// sharedOpt typeParameters, // shared type // ) { // return node->decorators != decorators @@ -2370,8 +2372,8 @@ namespace ts { // // // @api // function createEnumDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: string | Identifier, // members: readonly EnumMember[] // ) { @@ -2392,8 +2394,8 @@ namespace ts { // // @api // function updateEnumDeclaration( // node: EnumDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: Identifier, // members: readonly EnumMember[]) { // return node->decorators != decorators @@ -2406,8 +2408,8 @@ namespace ts { // // // @api // function createModuleDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: ModuleName, // body: ModuleBody | undefined, // flags = NodeFlags::None @@ -2436,8 +2438,8 @@ namespace ts { // // @api // function updateModuleDeclaration( // node: ModuleDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // name: ModuleName, // body: ModuleBody | undefined // ) { @@ -2500,8 +2502,8 @@ namespace ts { // // // @api // function createImportEqualsDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // name: string | Identifier, // moduleReference: ModuleReference @@ -2523,8 +2525,8 @@ namespace ts { // // @api // function updateImportEqualsDeclaration( // node: ImportEqualsDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // name: Identifier, // moduleReference: ModuleReference @@ -2540,8 +2542,8 @@ namespace ts { // // // @api // function createImportDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // importClause: ImportClause | undefined, // moduleSpecifier: Expression, // assertClause: AssertClause | undefined @@ -2564,8 +2566,8 @@ namespace ts { // // @api // function updateImportDeclaration( // node: ImportDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // importClause: ImportClause | undefined, // moduleSpecifier: Expression, // assertClause: AssertClause | undefined @@ -2605,7 +2607,7 @@ namespace ts { // } // // @api - shared createAssertClause(NodeArray elements, bool multiLine); + shared createAssertClause(shared elements, bool multiLine); // // @api // function updateAssertClause(node: AssertClause, elements: readonly AssertEntry[], multiLine?: boolean): AssertClause { @@ -2711,8 +2713,8 @@ namespace ts { // // // @api // function createExportAssignment( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isExportEquals: boolean | undefined, // shared expression // ) { @@ -2733,8 +2735,8 @@ namespace ts { // // @api // function updateExportAssignment( // node: ExportAssignment, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // shared expression // ) { // return node->decorators != decorators @@ -2746,8 +2748,8 @@ namespace ts { // // // @api // function createExportDeclaration( -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // exportClause: NamedExportBindings | undefined, // moduleSpecifier?: Expression, @@ -2772,8 +2774,8 @@ namespace ts { // // @api // function updateExportDeclaration( // node: ExportDeclaration, -// optional decorators, -// optional modifiers, +// sharedOpt decorators, +// sharedOpt modifiers, // isTypeOnly: boolean, // exportClause: NamedExportBindings | undefined, // moduleSpecifier: Expression | undefined, @@ -2903,7 +2905,7 @@ namespace ts { // } // // // @api -// function createJSDocFunctionType(NodeArray parameters, sharedOpt type): JSDocFunctionType { +// function createJSDocFunctionType(shared parameters, sharedOpt type): JSDocFunctionType { // auto node = createBaseSignatureDeclaration( // SyntaxKind::JSDocFunctionType, // /*decorators*/ {}, @@ -2917,7 +2919,7 @@ namespace ts { // } // // // @api -// function updateJSDocFunctionType(node: JSDocFunctionType, NodeArray parameters, sharedOpt type): JSDocFunctionType { +// function updateJSDocFunctionType(node: JSDocFunctionType, shared parameters, sharedOpt type): JSDocFunctionType { // return node->parameters != parameters // || node->type != type // ? update(createJSDocFunctionType(parameters, type), node) @@ -3314,7 +3316,7 @@ namespace ts { // // // // @api - shared createJsxElement(shared openingElement, NodeArray children, shared closingElement); + shared createJsxElement(shared openingElement, shared children, shared closingElement); // // @api // function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { @@ -3326,10 +3328,10 @@ namespace ts { // } // @api - shared createJsxSelfClosingElement(shared tagName, optional typeArguments, shared attributes); + shared createJsxSelfClosingElement(shared tagName, sharedOpt typeArguments, shared attributes); // // // @api -// function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, optional typeArguments, attributes: JsxAttributes) { +// function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, sharedOpt typeArguments, attributes: JsxAttributes) { // return node->tagName != tagName // || node->typeArguments != typeArguments // || node->attributes != attributes @@ -3338,10 +3340,10 @@ namespace ts { // } // // @api - shared createJsxOpeningElement(shared tagName, optional typeArguments, shared attributes); + shared createJsxOpeningElement(shared tagName, sharedOpt typeArguments, shared attributes); // // // @api -// function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, optional typeArguments, attributes: JsxAttributes) { +// function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, sharedOpt typeArguments, attributes: JsxAttributes) { // return node->tagName != tagName // || node->typeArguments != typeArguments // || node->attributes != attributes @@ -3360,7 +3362,7 @@ namespace ts { // } // @api - shared createJsxFragment(shared openingFragment, NodeArray children, shared closingFragment); + shared createJsxFragment(shared openingFragment, shared children, shared closingFragment); // // @api // function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { @@ -3398,7 +3400,7 @@ namespace ts { // } // // @api - shared createJsxAttributes(NodeArray properties); + shared createJsxAttributes(shared properties); // // // @api // function updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]) { @@ -3466,7 +3468,7 @@ namespace ts { // } // @api - shared createHeritageClause(SyntaxKind token, NodeArray types); + shared createHeritageClause(SyntaxKind token, shared types); // // @api // function updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]) { @@ -3581,34 +3583,34 @@ namespace ts { // ? update(createEnumMember(name, initializer), node) // : node; // } -// -// // -// // Top-level nodes -// // -// -// // @api -// function createSourceFile( -// statements: readonly Statement[], -// endOfFileToken: EndOfFileToken, -// flags: NodeFlags -// ) { -// auto node = basecreateBaseSourceFileNode(SyntaxKind::SourceFile) as Mutable; -// node->statements = createNodeArray(statements); -// node->endOfFileToken = endOfFileToken; -// node->flags |= flags; -// node->fileName = ""; -// node->text = ""; -// node->languageVersion = 0; -// node->languageVariant = 0; -// node->scriptKind = 0; -// node->isDeclarationFile = false; -// node->hasNoDefaultLib = false; -// node->transformFlags |= -// propagateChildrenFlags(node->statements) | -// propagateChildFlags(node->endOfFileToken); -// return node; -// } -// + + // + // Top-level nodes + // + + // @api + shared createSourceFile( + shared statements, + shared endOfFileToken, + int flags + ) { + auto node = make_shared(); + node->statements = createNodeArray(statements); + node->endOfFileToken = endOfFileToken; + node->flags |= (int)flags; + node->fileName = ""; + node->text = ""; + node->languageVersion = types::ScriptTarget::ES3; + node->languageVariant = types::LanguageVariant::Standard; + node->scriptKind = types::ScriptKind::Unknown; + node->isDeclarationFile = false; + node->hasNoDefaultLib = false; + node->transformFlags |= + propagateChildrenFlags(node->statements) | + propagateChildFlags(node->endOfFileToken); + return node; + } + // function cloneSourceFileWithChanges( // source: SourceFile, // statements: readonly Statement[], @@ -4385,7 +4387,7 @@ namespace ts { // } // // /** -// * Lifts a NodeArray containing only Statement nodes to a block. +// * Lifts a shared containing only Statement nodes to a block. // * // * @param nodes The NodeArray. // */ diff --git a/src/node_test.cpp b/src/node_test.cpp index 9508d6c..142db80 100644 --- a/src/node_test.cpp +++ b/src/node_test.cpp @@ -57,10 +57,10 @@ namespace ts { return ModifierFlags::None; } - int modifiersToFlags(optional modifiers) { + int modifiersToFlags(shared modifiers) { int flags = (int) ModifierFlags::None; if (modifiers) { - for (auto &modifier: (*modifiers).list) { + for (auto &modifier: modifiers->list) { flags |= (int) modifierToFlag(modifier->kind); } } @@ -114,19 +114,17 @@ namespace ts { } shared resolveNameToNode(const shared &node) { - auto a = dynamic_pointer_cast(node); - switch (node->kind) { case SyntaxKind::Identifier: - return dynamic_pointer_cast(node); + return reinterpret_pointer_cast(node); case SyntaxKind::StringLiteral: - return dynamic_pointer_cast(node); + return reinterpret_pointer_cast(node); case SyntaxKind::NumericLiteral: - return dynamic_pointer_cast(node); + return reinterpret_pointer_cast(node); case SyntaxKind::ComputedPropertyName: - return dynamic_pointer_cast(node); + return reinterpret_pointer_cast(node); case SyntaxKind::PrivateIdentifier: - return dynamic_pointer_cast(node); + return reinterpret_pointer_cast(node); } throw runtime_error(format("resolveNamToNode with kind %d no valid name property", (int) node->kind)); @@ -141,7 +139,7 @@ namespace ts { return false; } - optional getTypeParameters(shared node) { + sharedOpt getTypeParameters(shared node) { switch (node->kind) { case SyntaxKind::Constructor: return node->to().typeParameters; @@ -188,9 +186,9 @@ namespace ts { string &getEscapedName(const shared &node) { switch (node->kind) { case SyntaxKind::Identifier: - return dynamic_pointer_cast(node)->escapedText; + return reinterpret_pointer_cast(node)->escapedText; case SyntaxKind::PrivateIdentifier: - return dynamic_pointer_cast(node)->escapedText; + return reinterpret_pointer_cast(node)->escapedText; } throw runtime_error(format("getEscapedName with kind %d no valid", (int) node->kind)); @@ -204,91 +202,90 @@ namespace ts { //[x] Check child of DeclarationStatement //[x] Check child of FunctionOrConstructorTypeNodeBase - if (auto v = dynamic_pointer_cast(node)) { - return resolveNameToNode(v->name); - } else if (auto v = dynamic_pointer_cast(node)) { - return resolveNameToNode(v->name); - } else - switch (node->kind) { - case SyntaxKind::FunctionType: - return resolveNameToNode(node->to().name); - case SyntaxKind::ConstructorType: - return resolveNameToNode(node->to().name); - case SyntaxKind::PropertyAccessExpression: - return resolveNameToNode(node->to().name); - case SyntaxKind::MetaProperty: - return resolveNameToNode(node->to().name); - case SyntaxKind::ShorthandPropertyAssignment: - return resolveNameToNode(node->to().name); - case SyntaxKind::Parameter: - return resolveNameToNode(node->to().name); - case SyntaxKind::MissingDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::InterfaceDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::ClassDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::ClassExpression: - return resolveNameToNode(node->to().name); - case SyntaxKind::TypeAliasDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::EnumDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::EnumMember: - return resolveNameToNode(node->to().name); - case SyntaxKind::PropertySignature: - return resolveNameToNode(node->to().name); - case SyntaxKind::ModuleDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::ImportEqualsDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::NamespaceImport: - return resolveNameToNode(node->to().name); - case SyntaxKind::ImportSpecifier: - return resolveNameToNode(node->to().name); - case SyntaxKind::AssertEntry: - return resolveNameToNode(node->to().name); - case SyntaxKind::ImportClause: - return resolveNameToNode(node->to().name); - case SyntaxKind::NamespaceExport: - return resolveNameToNode(node->to().name); - case SyntaxKind::ExportSpecifier: - return resolveNameToNode(node->to().name); - case SyntaxKind::ExportDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::NamespaceExportDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::MethodSignature: - return resolveNameToNode(node->to().name); - case SyntaxKind::FunctionDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::MethodDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::GetAccessor: - return resolveNameToNode(node->to().name); - case SyntaxKind::SetAccessor: - return resolveNameToNode(node->to().name); - case SyntaxKind::FunctionExpression: - return resolveNameToNode(node->to().name); - case SyntaxKind::NamedTupleMember: - return resolveNameToNode(node->to().name); - case SyntaxKind::JsxAttribute: - return resolveNameToNode(node->to().name); - case SyntaxKind::TypeParameter: - return resolveNameToNode(node->to().name); - case SyntaxKind::BindingElement: - return resolveNameToNode(node->to().name); - case SyntaxKind::VariableDeclaration: - return resolveNameToNode(node->to().name); - case SyntaxKind::IndexSignature: - return resolveNameToNode(node->to().name); - case SyntaxKind::CallSignature: - return resolveNameToNode(node->to().name); - case SyntaxKind::ConstructSignature: - return resolveNameToNode(node->to().name); - case SyntaxKind::ExportAssignment: - return resolveNameToNode(node->to().name); - } + switch (node->kind) { + case SyntaxKind::FunctionType: + return resolveNameToNode(node->to().name); + case SyntaxKind::ConstructorType: + return resolveNameToNode(node->to().name); + case SyntaxKind::PropertyAccessExpression: + return resolveNameToNode(node->to().name); + case SyntaxKind::MetaProperty: + return resolveNameToNode(node->to().name); + case SyntaxKind::ShorthandPropertyAssignment: + return resolveNameToNode(node->to().name); + case SyntaxKind::Parameter: + return resolveNameToNode(node->to().name); + case SyntaxKind::MissingDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::InterfaceDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::ClassDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::ClassExpression: + return resolveNameToNode(node->to().name); + case SyntaxKind::TypeAliasDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::EnumDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::EnumMember: + return resolveNameToNode(node->to().name); + case SyntaxKind::PropertySignature: + return resolveNameToNode(node->to().name); + case SyntaxKind::ModuleDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::ImportEqualsDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::NamespaceImport: + return resolveNameToNode(node->to().name); + case SyntaxKind::ImportSpecifier: + return resolveNameToNode(node->to().name); + case SyntaxKind::AssertEntry: + return resolveNameToNode(node->to().name); + case SyntaxKind::ImportClause: + return resolveNameToNode(node->to().name); + case SyntaxKind::NamespaceExport: + return resolveNameToNode(node->to().name); + case SyntaxKind::ExportSpecifier: + return resolveNameToNode(node->to().name); + case SyntaxKind::ExportDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::NamespaceExportDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::MethodSignature: + return resolveNameToNode(node->to().name); + case SyntaxKind::FunctionDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::MethodDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::GetAccessor: + return resolveNameToNode(node->to().name); + case SyntaxKind::SetAccessor: + return resolveNameToNode(node->to().name); + case SyntaxKind::FunctionExpression: + return resolveNameToNode(node->to().name); + case SyntaxKind::NamedTupleMember: + return resolveNameToNode(node->to().name); + case SyntaxKind::JsxAttribute: + return resolveNameToNode(node->to().name); + case SyntaxKind::TypeParameter: + return resolveNameToNode(node->to().name); + case SyntaxKind::BindingElement: + return resolveNameToNode(node->to().name); + case SyntaxKind::VariableDeclaration: + return resolveNameToNode(node->to().name); + case SyntaxKind::IndexSignature: + return resolveNameToNode(node->to().name); + case SyntaxKind::CallSignature: + return resolveNameToNode(node->to().name); + case SyntaxKind::ConstructSignature: + return resolveNameToNode(node->to().name); + case SyntaxKind::ExportAssignment: + return resolveNameToNode(node->to().name); + default: + if (auto v = dynamic_pointer_cast(node)) { + return resolveNameToNode(v->name); + } + } return nullptr; } diff --git a/src/node_test.h b/src/node_test.h index 6609624..6fe4cf3 100644 --- a/src/node_test.h +++ b/src/node_test.h @@ -25,7 +25,7 @@ namespace ts { ModifierFlags modifierToFlag(SyntaxKind token); - int modifiersToFlags(optional modifiers); + int modifiersToFlags(sharedOpt modifiers); /** * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored. @@ -48,7 +48,7 @@ namespace ts { bool isFunctionOrConstructorTypeNode(shared node); - optional getTypeParameters(shared node); + sharedOpt getTypeParameters(shared node); shared getTagName(shared node); diff --git a/src/parenthesizer.cpp b/src/parenthesizer.cpp index 858113f..a23c386 100644 --- a/src/parenthesizer.cpp +++ b/src/parenthesizer.cpp @@ -8,12 +8,12 @@ namespace ts { template - NodeArray sameMap(optional array, function(shared, int)> callback) { - NodeArray result; + shared sameMap(const sharedOpt &array, const function(shared, int)> &callback) { + auto result = make_shared(); if (array) { auto i = 0; for (auto &v: array->list) { - result.list.push_back(callback(dynamic_pointer_cast(v), i++)); + result->list.push_back(callback(reinterpret_pointer_cast(v), i++)); } } return result; @@ -33,7 +33,7 @@ namespace ts { return condition; } - optional Parenthesizer::parenthesizeTypeArguments(optional typeArguments) { + sharedOpt Parenthesizer::parenthesizeTypeArguments(sharedOpt typeArguments) { if (typeArguments && (*typeArguments).empty()) { auto m = sameMap(typeArguments, CALLBACK(parenthesizeOrdinalTypeArgument)); return factory->createNodeArray(m); @@ -50,7 +50,7 @@ namespace ts { : branch; } - NodeArray Parenthesizer::parenthesizeElementTypesOfTupleType(NodeArray types) { + shared Parenthesizer::parenthesizeElementTypesOfTupleType(shared types) { return factory->createNodeArray(sameMap(types, CALLBACK(parenthesizeElementTypeOfTupleType))); } @@ -58,7 +58,7 @@ namespace ts { return isFunctionOrConstructorTypeNode(node) && getTypeParameters(node) ? factory->createParenthesizedType(node) : node; } - NodeArray Parenthesizer::parenthesizeConstituentTypesOfIntersectionType(NodeArray members) { + shared Parenthesizer::parenthesizeConstituentTypesOfIntersectionType(shared members) { return factory->createNodeArray(sameMap(members, CALLBACK(parenthesizeConstituentTypeOfIntersectionType))); } @@ -110,7 +110,7 @@ namespace ts { if (isLeftHandSideExpression(emittedExpression) && (emittedExpression->kind != SyntaxKind::NewExpression || emittedExpression->to().arguments)) { // TODO(rbuckton): Verify whether this assertion holds. - return dynamic_pointer_cast(expression); + return reinterpret_pointer_cast(expression); } // TODO(rbuckton): Verifiy whether `setTextRange` is needed. @@ -130,7 +130,7 @@ namespace ts { case SyntaxKind::NewExpression: return !leftmostExpr->to().arguments ? factory->createParenthesizedExpression(expression) - : dynamic_pointer_cast(expression); // TODO(rbuckton): Verify this assertion holds + : reinterpret_pointer_cast(expression); // TODO(rbuckton): Verify this assertion holds } return parenthesizeLeftSideOfAccess(expression); @@ -138,12 +138,12 @@ namespace ts { shared Parenthesizer::parenthesizeOperandOfPostfixUnary(shared operand) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return isLeftHandSideExpression(operand) ? dynamic_pointer_cast(operand) : setTextRange(factory->createParenthesizedExpression(operand), operand); + return isLeftHandSideExpression(operand) ? reinterpret_pointer_cast(operand) : setTextRange(factory->createParenthesizedExpression(operand), operand); } shared Parenthesizer::parenthesizeOperandOfPrefixUnary(shared operand) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return isUnaryExpression(operand) ? dynamic_pointer_cast(operand) : setTextRange(factory->createParenthesizedExpression(operand), operand); + return isUnaryExpression(operand) ? reinterpret_pointer_cast(operand) : setTextRange(factory->createParenthesizedExpression(operand), operand); } shared Parenthesizer::parenthesizeExpressionForDisallowedComma(shared expression, int) { @@ -154,9 +154,9 @@ namespace ts { return expressionPrecedence > commaPrecedence ? expression : setTextRange(factory->createParenthesizedExpression(expression), expression); } - NodeArray Parenthesizer::parenthesizeExpressionsOfCommaDelimitedList(NodeArray elements) { + shared Parenthesizer::parenthesizeExpressionsOfCommaDelimitedList(shared elements) { auto result = sameMap(elements, CALLBACK(parenthesizeExpressionForDisallowedComma)); - return setTextRange(factory->createNodeArray(result, elements.hasTrailingComma), elements); + return setTextRange(factory->createNodeArray(result, elements->hasTrailingComma), elements); } shared Parenthesizer::parenthesizeExpressionOfExpressionStatement(shared expression) { @@ -189,7 +189,7 @@ namespace ts { // function parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody; shared Parenthesizer::parenthesizeConciseBodyOfArrowFunction(shared body) { if (isBlock(body)) return body; - auto e = dynamic_pointer_cast(body); + auto e = reinterpret_pointer_cast(body); if (isCommaSequence(body) || getLeftmostExpression(e, /*stopAtCallExpressions*/ false)->kind == SyntaxKind::ObjectLiteralExpression) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return setTextRange(factory->createParenthesizedExpression(e), body); @@ -241,7 +241,7 @@ namespace ts { return parenthesizeCheckTypeOfConditionalType(type); } - NodeArray Parenthesizer::parenthesizeConstituentTypesOfUnionType(NodeArray members) { + shared Parenthesizer::parenthesizeConstituentTypesOfUnionType(shared members) { return factory->createNodeArray(sameMap(members, CALLBACK(parenthesizeConstituentTypeOfUnionType))); } } diff --git a/src/parenthesizer.h b/src/parenthesizer.h index 9ea0005..33514b0 100644 --- a/src/parenthesizer.h +++ b/src/parenthesizer.h @@ -270,7 +270,7 @@ namespace ts { shared parenthesizeExpressionForDisallowedComma(shared expression, int = 0); - NodeArray parenthesizeExpressionsOfCommaDelimitedList(NodeArray elements); + shared parenthesizeExpressionsOfCommaDelimitedList(shared elements); shared parenthesizeExpressionOfExpressionStatement(shared expression); @@ -300,7 +300,7 @@ namespace ts { // - A union type constituent has the same precedence as the check type of a conditional type shared parenthesizeConstituentTypeOfUnionType(shared type, int = 0); - NodeArray parenthesizeConstituentTypesOfUnionType(NodeArray members); + shared parenthesizeConstituentTypesOfUnionType(shared members); // IntersectionType[Extends] : // `&`? TypeOperator[?Extends] @@ -309,7 +309,7 @@ namespace ts { // - An intersection type constituent does not allow function, constructor, conditional, or union types (they must be parenthesized) shared parenthesizeConstituentTypeOfIntersectionType(shared type, int = 0); - NodeArray parenthesizeConstituentTypesOfIntersectionType(NodeArray members); + shared parenthesizeConstituentTypesOfIntersectionType(shared members); // TypeOperator[Extends] : // PostfixType @@ -372,7 +372,7 @@ namespace ts { // RestType : // `...` Type[~Extends] // - NodeArray parenthesizeElementTypesOfTupleType(NodeArray types); + shared parenthesizeElementTypesOfTupleType(shared types); // function hasJSDocPostfixQuestion(shared type | NamedTupleMember): boolean { // if (isJSDocNullableType(type)) return type.postfix; @@ -417,6 +417,6 @@ namespace ts { return i == 0 ? parenthesizeLeadingTypeArgument(node) : node; } - optional parenthesizeTypeArguments(optional typeArguments); + sharedOpt parenthesizeTypeArguments(sharedOpt typeArguments); }; } diff --git a/src/parser2.cpp b/src/parser2.cpp index 16adbc7..c19132f 100644 --- a/src/parser2.cpp +++ b/src/parser2.cpp @@ -11,16 +11,20 @@ namespace ts { } optional Parser::parseErrorAtPosition(int start, int length, const DiagnosticMessage &message, DiagnosticArg arg) { - // Mark that we've encountered an error. We'll set an appropriate bit on the next - // node we finish so that it can't be reused incrementally. - parseErrorBeforeNextFinishedNode = true; + ZoneScoped; + auto lastError = lastOrUndefined(parseDiagnostics); // Don't report another error if it would just be at the same position as the last error. - if (!parseDiagnostics.empty() || start != parseDiagnostics.back().start) { + if (!lastError || start != lastError->start) { auto d = createDetachedDiagnostic(fileName, start, length, message, {arg}); parseDiagnostics.push_back(d); return d; } + + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + return nullopt; } diff --git a/src/parser2.h b/src/parser2.h index 708aee9..fa5bd0d 100644 --- a/src/parser2.h +++ b/src/parser2.h @@ -1,5 +1,6 @@ #pragma once +#include "Tracy.hpp" #include #include #include @@ -97,7 +98,7 @@ namespace ts { //// /* @internal */ //// export const parseNodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory); - sharedOpt visitNode(function(shared)> cbNode, sharedOpt node) { + inline sharedOpt visitNode(const function(shared)> &cbNode, const sharedOpt &node) { if (node) cbNode(node); return nullptr; } @@ -106,14 +107,20 @@ namespace ts { // return cbNode(node); // } - sharedOpt visitNodes( - function(shared)> cbNode, - optional(NodeArray)>> cbNodes, - optional nodes + inline sharedOpt noop(const shared &) { + return nullptr; + }; + + inline sharedOpt forEachChild(const shared &node, const function(shared)> &cbNode, const function(shared)> &cbNodes = noop); + + inline sharedOpt visitNodes( + const function(shared)> &cbNode, + const function(shared)> &cbNodes = noop, + const sharedOpt &nodes = nullptr ) { if (nodes) { if (cbNodes) { - return (*cbNodes)(*nodes); + return cbNodes(nodes); } for (auto node: nodes->list) { auto result = cbNode(node); @@ -130,10 +137,10 @@ namespace ts { * returns a truthy value, then returns that value. * If no such value is found, the callback is applied to each element of array and undefined is returned. */ - sharedOpt forEach(optional array, function(shared element, int index)> callback) { + inline sharedOpt forEach(const sharedOpt &array, const function(shared element, int index)> &callback) { if (array) { for (int i = 0; i < array->list.size(); i++) { - auto result = callback((*array).list[i], i); + auto result = callback(array->list[i], i); if (result) { return result; } @@ -147,7 +154,7 @@ namespace ts { // * returns a truthy value, then returns that value. // * If no such value is found, the callback is applied to each element of array and undefined is returned. // */ -// bool forEach(optional array, function element, int index)> callback) { +// bool forEach(sharedOpt array, function element, int index)> callback) { // if (array) { // for (int i = 0; i < array->list.size(); i ++) { // auto result = callback((*array).list[i], i); @@ -159,29 +166,30 @@ namespace ts { // return false; // } - bool some(optional array, optional value)>> predicate) { +// inline bool some(const sharedOpt &array) { +// if (array) { +// return array->list.size() > 0; +// } +// return false; +// } + + inline bool some(const sharedOpt &array, const function value)> &predicate) { if (array) { - if (predicate) { - for (auto &v: array->list) { - if ((*predicate)(v)) { - return true; - } + for (auto &v: array->list) { + if (predicate(v)) { + return true; } - } else { - return array->list.size() > 0; } } return false; } - sharedOpt forEachChild(const shared &node, function(shared)> cbNode, optional(NodeArray)>> cbNodes = nullopt); - /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */ - bool hasModifierOfKind(const shared &node, SyntaxKind kind) { - return some(node->modifiers, [kind](auto m) { return m->kind == kind; }); + inline bool hasModifierOfKind(const shared &node, SyntaxKind kind) { + return some(node->modifiers, [kind](auto m) { return m->kind == kind; }); } - sharedOpt isAnExternalModuleIndicatorNode(shared node, int) { + inline sharedOpt isAnExternalModuleIndicatorNode(shared node, int) { if (hasModifierOfKind(node, SyntaxKind::ExportKeyword) || (node->is() && isExternalModuleReference(node->to().moduleReference)) || isImportDeclaration(node) @@ -191,7 +199,7 @@ namespace ts { return nullptr; } - bool isImportMeta(const shared &node) { + inline bool isImportMeta(const shared &node) { if (isMetaProperty(node)) { auto meta = node->to(); return meta.keywordToken == SyntaxKind::ImportKeyword && meta.name->to().escapedText == "meta"; @@ -199,19 +207,19 @@ namespace ts { return false; } - sharedOpt walkTreeForImportMeta(const shared &node) { + inline sharedOpt walkTreeForImportMeta(const shared &node) { if (isImportMeta(node)) return node; - return forEachChild(node, walkTreeForImportMeta, nullopt); + return forEachChild(node, walkTreeForImportMeta); } - sharedOpt getImportMetaIfNecessary(const shared &sourceFile) { + inline sharedOpt getImportMetaIfNecessary(const shared &sourceFile) { return sourceFile->flags & (int) NodeFlags::PossiblyContainsImportMeta ? walkTreeForImportMeta(sourceFile) : nullptr; } /*@internal*/ - sharedOpt isFileProbablyExternalModule(const shared &sourceFile) { + inline sharedOpt isFileProbablyExternalModule(const shared &sourceFile) { // Try to use the first top-level import/export when available, then // fall back to looking for an 'import.meta' somewhere in the tree if necessary. auto r = forEach(sourceFile->statements, isAnExternalModuleIndicatorNode); @@ -219,7 +227,6 @@ namespace ts { return getImportMetaIfNecessary(sourceFile); } - /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -233,85 +240,85 @@ namespace ts { * @remarks `forEachChild` must visit the children of a node in the order * that they appear in the source code. The language service depends on this property to locate nodes by position. */ - sharedOpt forEachChild(Node &node, function(shared)> cbNode, optional(NodeArray)>> cbNodes) { - if (node.kind <= SyntaxKind::LastToken) { + inline sharedOpt forEachChild(const shared &node, const function(shared)> &cbNode, const function(shared)> &cbNodes) { + if (node->kind <= SyntaxKind::LastToken) { return nullptr; } - switch (node.kind) { + switch (node->kind) { case SyntaxKind::QualifiedName: //short-circuit evaluation is always boolean ... not last value in c++ - return visitNode(cbNode, node.to().left) || - visitNode(cbNode, node.to().right); + return visitNode(cbNode, node->to().left) || + visitNode(cbNode, node->to().right); case SyntaxKind::TypeParameter: - return visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().constraint) || - visitNode(cbNode, node.to().defaultType) || - visitNode(cbNode, node.to().expression); + return visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().constraint) || + visitNode(cbNode, node->to().defaultType) || + visitNode(cbNode, node->to().expression); case SyntaxKind::ShorthandPropertyAssignment: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().exclamationToken) || - visitNode(cbNode, node.to().equalsToken) || - visitNode(cbNode, node.to().objectAssignmentInitializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().exclamationToken) || + visitNode(cbNode, node->to().equalsToken) || + visitNode(cbNode, node->to().objectAssignmentInitializer); case SyntaxKind::SpreadAssignment: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::Parameter: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().dotDotDotToken) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().type) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().dotDotDotToken) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().type) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::PropertyDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().exclamationToken) || - visitNode(cbNode, node.to().type) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().exclamationToken) || + visitNode(cbNode, node->to().type) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::PropertySignature: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().type) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().type) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::PropertyAssignment: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::VariableDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().exclamationToken) || - visitNode(cbNode, node.to().type) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().exclamationToken) || + visitNode(cbNode, node->to().type) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::BindingElement: { - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().dotDotDotToken) || - visitNode(cbNode, node.to().propertyName) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().initializer); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().dotDotDotToken) || + visitNode(cbNode, node->to().propertyName) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().initializer); } case SyntaxKind::FunctionType: case SyntaxKind::ConstructorType: case SyntaxKind::CallSignature: case SyntaxKind::ConstructSignature: case SyntaxKind::IndexSignature: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.to().typeParameters) || - visitNodes(cbNode, cbNodes, node.to().parameters) || - visitNode(cbNode, node.to().type); + return visitNodes(cbNode, cbNodes, node->decorators) || + visitNodes(cbNode, cbNodes, node->modifiers) || + visitNodes(cbNode, cbNodes, node->to().typeParameters) || + visitNodes(cbNode, cbNodes, node->to().parameters) || + visitNode(cbNode, node->to().type); case SyntaxKind::MethodDeclaration: case SyntaxKind::MethodSignature: case SyntaxKind::Constructor: @@ -320,358 +327,358 @@ namespace ts { case SyntaxKind::FunctionExpression: case SyntaxKind::FunctionDeclaration: case SyntaxKind::ArrowFunction: { - if (auto b = visitNodes(cbNode, cbNodes, node.decorators)) return b; - - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.cast().asteriskToken) || - visitNode(cbNode, node.cast().name) || - visitNode(cbNode, node.cast().questionToken) || - visitNode(cbNode, node.cast().exclamationToken) || - visitNodes(cbNode, cbNodes, node.cast().typeParameters) || - visitNodes(cbNode, cbNodes, node.cast().parameters) || - visitNode(cbNode, node.cast().type) || - (node.kind == SyntaxKind::ArrowFunction ? visitNode(cbNode, node.to().equalsGreaterThanToken) : shared(nullptr)) || - visitNode(cbNode, node.cast().body); + if (auto b = visitNodes(cbNode, cbNodes, node->decorators)) return b; + + return visitNodes(cbNode, cbNodes, node->decorators) || + visitNodes(cbNode, cbNodes, node->modifiers) || + visitNode(cbNode, node->cast().asteriskToken) || + visitNode(cbNode, node->cast().name) || + visitNode(cbNode, node->cast().questionToken) || + visitNode(cbNode, node->cast().exclamationToken) || + visitNodes(cbNode, cbNodes, node->cast().typeParameters) || + visitNodes(cbNode, cbNodes, node->cast().parameters) || + visitNode(cbNode, node->cast().type) || + (node->kind == SyntaxKind::ArrowFunction ? visitNode(cbNode, node->to().equalsGreaterThanToken) : shared(nullptr)) || + visitNode(cbNode, node->cast().body); } case SyntaxKind::ClassStaticBlockDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().body); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().body); case SyntaxKind::TypeReference: - return visitNode(cbNode, node.to().typeName) || - visitNodes(cbNode, cbNodes, node.to().typeArguments); + return visitNode(cbNode, node->to().typeName) || + visitNodes(cbNode, cbNodes, node->to().typeArguments); case SyntaxKind::TypePredicate: - return visitNode(cbNode, node.to().assertsModifier) || - visitNode(cbNode, node.to().parameterName) || - visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().assertsModifier) || + visitNode(cbNode, node->to().parameterName) || + visitNode(cbNode, node->to().type); case SyntaxKind::TypeQuery: - return visitNode(cbNode, node.to().exprName) || - visitNodes(cbNode, cbNodes, node.to().typeArguments); + return visitNode(cbNode, node->to().exprName) || + visitNodes(cbNode, cbNodes, node->to().typeArguments); case SyntaxKind::TypeLiteral: - return visitNodes(cbNode, cbNodes, node.to().members); + return visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::ArrayType: - return visitNode(cbNode, node.to().elementType); + return visitNode(cbNode, node->to().elementType); case SyntaxKind::TupleType: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::UnionType: - return visitNodes(cbNode, cbNodes, node.to().types); + return visitNodes(cbNode, cbNodes, node->to().types); case SyntaxKind::IntersectionType: - return visitNodes(cbNode, cbNodes, node.to().types); + return visitNodes(cbNode, cbNodes, node->to().types); case SyntaxKind::ConditionalType: - return visitNode(cbNode, node.to().checkType) || - visitNode(cbNode, node.to().extendsType) || - visitNode(cbNode, node.to().trueType) || - visitNode(cbNode, node.to().falseType); + return visitNode(cbNode, node->to().checkType) || + visitNode(cbNode, node->to().extendsType) || + visitNode(cbNode, node->to().trueType) || + visitNode(cbNode, node->to().falseType); case SyntaxKind::InferType: - return visitNode(cbNode, node.to().typeParameter); + return visitNode(cbNode, node->to().typeParameter); case SyntaxKind::ImportType: - return visitNode(cbNode, node.to().argument) || - visitNode(cbNode, node.to().assertions) || - visitNode(cbNode, node.to().qualifier) || - visitNodes(cbNode, cbNodes, node.to().typeArguments); + return visitNode(cbNode, node->to().argument) || + visitNode(cbNode, node->to().assertions) || + visitNode(cbNode, node->to().qualifier) || + visitNodes(cbNode, cbNodes, node->to().typeArguments); case SyntaxKind::ImportTypeAssertionContainer: - return visitNode(cbNode, node.to().assertClause); + return visitNode(cbNode, node->to().assertClause); case SyntaxKind::ParenthesizedType: - return visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().type); case SyntaxKind::TypeOperator: - return visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().type); case SyntaxKind::IndexedAccessType: - return visitNode(cbNode, node.to().objectType) || - visitNode(cbNode, node.to().indexType); + return visitNode(cbNode, node->to().objectType) || + visitNode(cbNode, node->to().indexType); case SyntaxKind::MappedType: - return visitNode(cbNode, node.to().readonlyToken) || - visitNode(cbNode, node.to().typeParameter) || - visitNode(cbNode, node.to().nameType) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().type) || - visitNodes(cbNode, cbNodes, node.to().members); + return visitNode(cbNode, node->to().readonlyToken) || + visitNode(cbNode, node->to().typeParameter) || + visitNode(cbNode, node->to().nameType) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().type) || + visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::LiteralType: - return visitNode(cbNode, node.to().literal); + return visitNode(cbNode, node->to().literal); case SyntaxKind::NamedTupleMember: - return visitNode(cbNode, node.to().dotDotDotToken) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().dotDotDotToken) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().type); case SyntaxKind::ObjectBindingPattern: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::ArrayBindingPattern: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::ArrayLiteralExpression: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::ObjectLiteralExpression: - return visitNodes(cbNode, cbNodes, node.to().properties); + return visitNodes(cbNode, cbNodes, node->to().properties); case SyntaxKind::PropertyAccessExpression: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().questionDotToken) || - visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().questionDotToken) || + visitNode(cbNode, node->to().name); case SyntaxKind::ElementAccessExpression: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().questionDotToken) || - visitNode(cbNode, node.to().argumentExpression); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().questionDotToken) || + visitNode(cbNode, node->to().argumentExpression); case SyntaxKind::CallExpression: case SyntaxKind::NewExpression: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().questionDotToken) || - visitNodes(cbNode, cbNodes, node.to().typeArguments) || - visitNodes(cbNode, cbNodes, node.to().arguments); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().questionDotToken) || + visitNodes(cbNode, cbNodes, node->to().typeArguments) || + visitNodes(cbNode, cbNodes, node->to().arguments); case SyntaxKind::TaggedTemplateExpression: - return visitNode(cbNode, node.to().tag) || - visitNode(cbNode, node.to().questionDotToken) || - visitNodes(cbNode, cbNodes, node.to().typeArguments) || - visitNode(cbNode, node.to().templateLiteral); + return visitNode(cbNode, node->to().tag) || + visitNode(cbNode, node->to().questionDotToken) || + visitNodes(cbNode, cbNodes, node->to().typeArguments) || + visitNode(cbNode, node->to().templateLiteral); case SyntaxKind::TypeAssertionExpression: - return visitNode(cbNode, node.to().type) || - visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().type) || + visitNode(cbNode, node->to().expression); case SyntaxKind::ParenthesizedExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::DeleteExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::TypeOfExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::VoidExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::PrefixUnaryExpression: - return visitNode(cbNode, node.to().operand); + return visitNode(cbNode, node->to().operand); case SyntaxKind::YieldExpression: - return visitNode(cbNode, node.to().asteriskToken) || - visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().asteriskToken) || + visitNode(cbNode, node->to().expression); case SyntaxKind::AwaitExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::PostfixUnaryExpression: - return visitNode(cbNode, node.to().operand); + return visitNode(cbNode, node->to().operand); case SyntaxKind::BinaryExpression: - return visitNode(cbNode, node.to().left) || - visitNode(cbNode, node.to().operatorToken) || - visitNode(cbNode, node.to().right); + return visitNode(cbNode, node->to().left) || + visitNode(cbNode, node->to().operatorToken) || + visitNode(cbNode, node->to().right); case SyntaxKind::AsExpression: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().type); case SyntaxKind::NonNullExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::MetaProperty: - return visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().name); case SyntaxKind::ConditionalExpression: - return visitNode(cbNode, node.to().condition) || - visitNode(cbNode, node.to().questionToken) || - visitNode(cbNode, node.to().whenTrue) || - visitNode(cbNode, node.to().colonToken) || - visitNode(cbNode, node.to().whenFalse); + return visitNode(cbNode, node->to().condition) || + visitNode(cbNode, node->to().questionToken) || + visitNode(cbNode, node->to().whenTrue) || + visitNode(cbNode, node->to().colonToken) || + visitNode(cbNode, node->to().whenFalse); case SyntaxKind::SpreadElement: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::Block: case SyntaxKind::ModuleBlock: - return visitNodes(cbNode, cbNodes, node.to().statements); + return visitNodes(cbNode, cbNodes, node->to().statements); case SyntaxKind::SourceFile: - return visitNodes(cbNode, cbNodes, node.to().statements) || - visitNode(cbNode, node.to().endOfFileToken); + return visitNodes(cbNode, cbNodes, node->to().statements) || + visitNode(cbNode, node->to().endOfFileToken); case SyntaxKind::VariableStatement: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().declarationList); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().declarationList); case SyntaxKind::VariableDeclarationList: - return visitNodes(cbNode, cbNodes, node.to().declarations); + return visitNodes(cbNode, cbNodes, node->to().declarations); case SyntaxKind::ExpressionStatement: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::IfStatement: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().thenStatement) || - visitNode(cbNode, node.to().elseStatement); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().thenStatement) || + visitNode(cbNode, node->to().elseStatement); case SyntaxKind::DoStatement: - return visitNode(cbNode, node.to().statement) || - visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().statement) || + visitNode(cbNode, node->to().expression); case SyntaxKind::WhileStatement: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().statement); case SyntaxKind::ForStatement: - return visitNode(cbNode, node.to().initializer) || - visitNode(cbNode, node.to().condition) || - visitNode(cbNode, node.to().incrementor) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().initializer) || + visitNode(cbNode, node->to().condition) || + visitNode(cbNode, node->to().incrementor) || + visitNode(cbNode, node->to().statement); case SyntaxKind::ForInStatement: - return visitNode(cbNode, node.to().initializer) || - visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().initializer) || + visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().statement); case SyntaxKind::ForOfStatement: - return visitNode(cbNode, node.to().awaitModifier) || - visitNode(cbNode, node.to().initializer) || - visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().awaitModifier) || + visitNode(cbNode, node->to().initializer) || + visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().statement); case SyntaxKind::ContinueStatement: - return visitNode(cbNode, node.to().label); + return visitNode(cbNode, node->to().label); case SyntaxKind::BreakStatement: - return visitNode(cbNode, node.to().label); + return visitNode(cbNode, node->to().label); case SyntaxKind::ReturnStatement: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::WithStatement: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().statement); case SyntaxKind::SwitchStatement: - return visitNode(cbNode, node.to().expression) || - visitNode(cbNode, node.to().caseBlock); + return visitNode(cbNode, node->to().expression) || + visitNode(cbNode, node->to().caseBlock); case SyntaxKind::CaseBlock: - return visitNodes(cbNode, cbNodes, node.to().clauses); + return visitNodes(cbNode, cbNodes, node->to().clauses); case SyntaxKind::CaseClause: - return visitNode(cbNode, node.to().expression) || - visitNodes(cbNode, cbNodes, node.to().statements); + return visitNode(cbNode, node->to().expression) || + visitNodes(cbNode, cbNodes, node->to().statements); case SyntaxKind::DefaultClause: - return visitNodes(cbNode, cbNodes, node.to().statements); + return visitNodes(cbNode, cbNodes, node->to().statements); case SyntaxKind::LabeledStatement: - return visitNode(cbNode, node.to().label) || - visitNode(cbNode, node.to().statement); + return visitNode(cbNode, node->to().label) || + visitNode(cbNode, node->to().statement); case SyntaxKind::ThrowStatement: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::TryStatement: - return visitNode(cbNode, node.to().tryBlock) || - visitNode(cbNode, node.to().catchClause) || - visitNode(cbNode, node.to().finallyBlock); + return visitNode(cbNode, node->to().tryBlock) || + visitNode(cbNode, node->to().catchClause) || + visitNode(cbNode, node->to().finallyBlock); case SyntaxKind::CatchClause: - return visitNode(cbNode, node.to().variableDeclaration) || - visitNode(cbNode, node.to().block); + return visitNode(cbNode, node->to().variableDeclaration) || + visitNode(cbNode, node->to().block); case SyntaxKind::Decorator: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::ClassDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNodes(cbNode, cbNodes, node.to().typeParameters) || - visitNodes(cbNode, cbNodes, node.to().heritageClauses) || - visitNodes(cbNode, cbNodes, node.to().members); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNodes(cbNode, cbNodes, node->to().typeParameters) || + visitNodes(cbNode, cbNodes, node->to().heritageClauses) || + visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::ClassExpression: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNodes(cbNode, cbNodes, node.to().typeParameters) || - visitNodes(cbNode, cbNodes, node.to().heritageClauses) || - visitNodes(cbNode, cbNodes, node.to().members); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNodes(cbNode, cbNodes, node->to().typeParameters) || + visitNodes(cbNode, cbNodes, node->to().heritageClauses) || + visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::InterfaceDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNodes(cbNode, cbNodes, node.to().typeParameters) || - visitNodes(cbNode, cbNodes, node.to().heritageClauses) || - visitNodes(cbNode, cbNodes, node.to().members); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNodes(cbNode, cbNodes, node->to().typeParameters) || + visitNodes(cbNode, cbNodes, node->to().heritageClauses) || + visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::TypeAliasDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNodes(cbNode, cbNodes, node.to().typeParameters) || - visitNode(cbNode, node.to().type); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNodes(cbNode, cbNodes, node->to().typeParameters) || + visitNode(cbNode, node->to().type); case SyntaxKind::EnumDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNodes(cbNode, cbNodes, node.to().members); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNodes(cbNode, cbNodes, node->to().members); case SyntaxKind::EnumMember: - return visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().initializer); + return visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::ModuleDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().body); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().body); case SyntaxKind::ImportEqualsDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().moduleReference); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().moduleReference); case SyntaxKind::ImportDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().importClause) || - visitNode(cbNode, node.to().moduleSpecifier) || - visitNode(cbNode, node.to().assertClause); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().importClause) || + visitNode(cbNode, node->to().moduleSpecifier) || + visitNode(cbNode, node->to().assertClause); case SyntaxKind::ImportClause: - return visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().namedBindings); + return visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().namedBindings); case SyntaxKind::AssertClause: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::AssertEntry: - return visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().value); + return visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().value); case SyntaxKind::NamespaceExportDeclaration: - return visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().name); case SyntaxKind::NamespaceImport: - return visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().name); case SyntaxKind::NamespaceExport: - return visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().name); case SyntaxKind::NamedImports: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::NamedExports: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::ExportDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().exportClause) || - visitNode(cbNode, node.to().moduleSpecifier) || - visitNode(cbNode, node.to().assertClause); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().exportClause) || + visitNode(cbNode, node->to().moduleSpecifier) || + visitNode(cbNode, node->to().assertClause); case SyntaxKind::ImportSpecifier: - return visitNode(cbNode, node.to().propertyName) || - visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().propertyName) || + visitNode(cbNode, node->to().name); case SyntaxKind::ExportSpecifier: - return visitNode(cbNode, node.to().propertyName) || - visitNode(cbNode, node.to().name); + return visitNode(cbNode, node->to().propertyName) || + visitNode(cbNode, node->to().name); case SyntaxKind::ExportAssignment: - return visitNodes(cbNode, cbNodes, node.to().decorators) || - visitNodes(cbNode, cbNodes, node.to().modifiers) || - visitNode(cbNode, node.to().expression); + return visitNodes(cbNode, cbNodes, node->to().decorators) || + visitNodes(cbNode, cbNodes, node->to().modifiers) || + visitNode(cbNode, node->to().expression); case SyntaxKind::TemplateExpression: - return visitNode(cbNode, node.to().head) || visitNodes(cbNode, cbNodes, node.to().templateSpans); + return visitNode(cbNode, node->to().head) || visitNodes(cbNode, cbNodes, node->to().templateSpans); case SyntaxKind::TemplateSpan: - return visitNode(cbNode, node.to().expression) || visitNode(cbNode, node.to().literal); + return visitNode(cbNode, node->to().expression) || visitNode(cbNode, node->to().literal); case SyntaxKind::TemplateLiteralType: - return visitNode(cbNode, node.to().head) || visitNodes(cbNode, cbNodes, node.to().templateSpans); + return visitNode(cbNode, node->to().head) || visitNodes(cbNode, cbNodes, node->to().templateSpans); case SyntaxKind::TemplateLiteralTypeSpan: - return visitNode(cbNode, node.to().type) || visitNode(cbNode, node.to().literal); + return visitNode(cbNode, node->to().type) || visitNode(cbNode, node->to().literal); case SyntaxKind::ComputedPropertyName: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::HeritageClause: - return visitNodes(cbNode, cbNodes, node.to().types); + return visitNodes(cbNode, cbNodes, node->to().types); case SyntaxKind::ExpressionWithTypeArguments: - return visitNode(cbNode, node.to().expression) || - visitNodes(cbNode, cbNodes, node.to().typeArguments); + return visitNode(cbNode, node->to().expression) || + visitNodes(cbNode, cbNodes, node->to().typeArguments); case SyntaxKind::ExternalModuleReference: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::MissingDeclaration: - return visitNodes(cbNode, cbNodes, node.to().decorators); + return visitNodes(cbNode, cbNodes, node->to().decorators); case SyntaxKind::CommaListExpression: - return visitNodes(cbNode, cbNodes, node.to().elements); + return visitNodes(cbNode, cbNodes, node->to().elements); case SyntaxKind::JsxElement: - return visitNode(cbNode, node.to().openingElement) || - visitNodes(cbNode, cbNodes, node.to().children) || - visitNode(cbNode, node.to().closingElement); + return visitNode(cbNode, node->to().openingElement) || + visitNodes(cbNode, cbNodes, node->to().children) || + visitNode(cbNode, node->to().closingElement); case SyntaxKind::JsxFragment: - return visitNode(cbNode, node.to().openingFragment) || - visitNodes(cbNode, cbNodes, node.to().children) || - visitNode(cbNode, node.to().closingFragment); + return visitNode(cbNode, node->to().openingFragment) || + visitNodes(cbNode, cbNodes, node->to().children) || + visitNode(cbNode, node->to().closingFragment); case SyntaxKind::JsxSelfClosingElement: - return visitNode(cbNode, node.to().tagName) || - visitNodes(cbNode, cbNodes, node.to().typeArguments) || - visitNode(cbNode, node.to().attributes); + return visitNode(cbNode, node->to().tagName) || + visitNodes(cbNode, cbNodes, node->to().typeArguments) || + visitNode(cbNode, node->to().attributes); case SyntaxKind::JsxOpeningElement: - return visitNode(cbNode, node.to().tagName) || - visitNodes(cbNode, cbNodes, node.to().typeArguments) || - visitNode(cbNode, node.to().attributes); + return visitNode(cbNode, node->to().tagName) || + visitNodes(cbNode, cbNodes, node->to().typeArguments) || + visitNode(cbNode, node->to().attributes); case SyntaxKind::JsxAttributes: - return visitNodes(cbNode, cbNodes, node.to().properties); + return visitNodes(cbNode, cbNodes, node->to().properties); case SyntaxKind::JsxAttribute: - return visitNode(cbNode, node.to().name) || - visitNode(cbNode, node.to().initializer); + return visitNode(cbNode, node->to().name) || + visitNode(cbNode, node->to().initializer); case SyntaxKind::JsxSpreadAttribute: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); case SyntaxKind::JsxExpression: - return visitNode(cbNode, node.to().dotDotDotToken) || - visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().dotDotDotToken) || + visitNode(cbNode, node->to().expression); case SyntaxKind::JsxClosingElement: - return visitNode(cbNode, node.to().tagName); + return visitNode(cbNode, node->to().tagName); case SyntaxKind::OptionalType: - return visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().type); case SyntaxKind::RestType: - return visitNode(cbNode, node.to().type); + return visitNode(cbNode, node->to().type); case SyntaxKind::PartiallyEmittedExpression: - return visitNode(cbNode, node.to().expression); + return visitNode(cbNode, node->to().expression); } } @@ -764,7 +771,7 @@ namespace ts { // sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile); // } - void setExternalModuleIndicator(shared sourceFile) { + inline void setExternalModuleIndicator(const shared &sourceFile) { sourceFile->externalModuleIndicator = isFileProbablyExternalModule(sourceFile); } @@ -785,12 +792,12 @@ namespace ts { // export function parseJsonText(fileName: string, sourceText: string): JsonSourceFile { // return Parser.parseJsonText(fileName, sourceText); // } -// -// // See also `isExternalOrCommonJsModule` in utilities.ts -// export function isExternalModule(file: SourceFile): boolean { -// return file.externalModuleIndicator != undefined; -// } -// + + // See also `isExternalOrCommonJsModule` in utilities.ts + inline bool isExternalModule(const shared &file) { + return (bool) file->externalModuleIndicator; + } + // // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter // // indicates what changed between the 'text' that this SourceFile has and the 'newText'. // // The SourceFile will be created with the compiler attempting to reuse as many nodes from @@ -835,7 +842,7 @@ namespace ts { Scanner scanner{ScriptTarget::Latest, /*skipTrivia*/ true}; Factory factory; - int disallowInAndDecoratorContext = (int)NodeFlags::DisallowInContext | (int)NodeFlags::DecoratorContext; + int disallowInAndDecoratorContext = (int) NodeFlags::DisallowInContext | (int) NodeFlags::DecoratorContext; // // capture constructors in 'initializeState' to avoid null checks // // tslint:disable variable-name @@ -987,6 +994,7 @@ namespace ts { } SyntaxKind nextToken() { + ZoneScoped; // if the keyword had an escape if (isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) { // issue a parse error for the escape @@ -997,11 +1005,13 @@ namespace ts { template T nextTokenAnd(function func) { + ZoneScoped; nextToken(); return func(); } void initializeState(string _fileName, string _sourceText, ScriptTarget _languageVersion, ScriptKind _scriptKind) { + ZoneScoped; // NodeConstructor = objectAllocator.getNodeConstructor(); // TokenConstructor = objectAllocator.getTokenConstructor(); // IdentifierConstructor = objectAllocator.getIdentifierConstructor(); @@ -1040,12 +1050,13 @@ namespace ts { // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); - scanner.setOnError([this](auto ...a) { scanError(a...); }); +// scanner.setOnError([this](auto ...a) { scanError(a...); }); scanner.setScriptTarget(languageVersion); scanner.setLanguageVariant(languageVariant); } void clearState() { + ZoneScoped; // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. scanner.clearCommentDirectives(); scanner.setText(""); @@ -1209,44 +1220,52 @@ namespace ts { // // binding. // setParentRecursive(rootNode, /*incremental*/ true); // } -// -// function createSourceFile( -// fileName: string, -// languageVersion: ScriptTarget, -// scriptKind: ScriptKind, -// isDeclarationFile: boolean, -// statements: readonly Statement[], -// endOfFileToken: EndOfFileToken, -// flags: NodeFlags, -// setExternalModuleIndicator: (sourceFile: SourceFile) => void): SourceFile { -// // code from createNode is inlined here so createNode won't have to deal with special case of creating source files -// // this is quite rare comparing to other nodes and createNode should be as fast as possible -// auto sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); -// setTextRangePosWidth(sourceFile, 0, sourceText.length); -// setFields(sourceFile); -// -// // If we parsed this as an external module, it may contain top-level await -// if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & TransformFlags.ContainsPossibleTopLevelAwait) { + + shared createSourceFile( + string fileName, + ScriptTarget languageVersion, + ScriptKind scriptKind, + bool isDeclarationFile, + shared statements, + shared endOfFileToken, + int flags, + function)> setExternalModuleIndicator + ) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + auto sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); + setTextRangePosEnd(sourceFile, 0, sourceText.size()); + sourceFile->text = sourceText; + +// sourceFile.bindDiagnostics = []; +// sourceFile.bindSuggestionDiagnostics = undefined; + sourceFile->languageVersion = languageVersion; + sourceFile->fileName = fileName; + sourceFile->languageVariant = getLanguageVariant(scriptKind); + sourceFile->isDeclarationFile = isDeclarationFile; + sourceFile->scriptKind = scriptKind; + setExternalModuleIndicator(sourceFile); + sourceFile->setExternalModuleIndicator = setExternalModuleIndicator; + + // If we parsed this as an external module, it may contain top-level await + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile->transformFlags & (int) TransformFlags::ContainsPossibleTopLevelAwait) { + throw runtime_error("not implemented"); // sourceFile = reparseTopLevelAwait(sourceFile); -// setFields(sourceFile); -// } -// -// return sourceFile; -// -// function setFields(sourceFile: SourceFile) { -// sourceFile.text = sourceText; + + sourceFile->text = sourceText; // sourceFile.bindDiagnostics = []; // sourceFile.bindSuggestionDiagnostics = undefined; -// sourceFile.languageVersion = languageVersion; -// sourceFile.fileName = fileName; -// sourceFile.languageVariant = getLanguageVariant(scriptKind); -// sourceFile.isDeclarationFile = isDeclarationFile; -// sourceFile.scriptKind = scriptKind; -// -// setExternalModuleIndicator(sourceFile); -// sourceFile.setExternalModuleIndicator = setExternalModuleIndicator; -// } -// } + sourceFile->languageVersion = languageVersion; + sourceFile->fileName = fileName; + sourceFile->languageVariant = getLanguageVariant(scriptKind); + sourceFile->isDeclarationFile = isDeclarationFile; + sourceFile->scriptKind = scriptKind; + setExternalModuleIndicator(sourceFile); + sourceFile->setExternalModuleIndicator = setExternalModuleIndicator; + } + + return sourceFile; + } void setContextFlag(bool val, int flag) { if (val) { @@ -1340,6 +1359,7 @@ namespace ts { } template T speculationHelper(const function &callback, SpeculationKind speculationKind) { + ZoneScoped; // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). auto saveToken = currentToken; @@ -1363,7 +1383,7 @@ namespace ts { // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. - if (!(bool)result || (speculationKind != SpeculationKind::TryParse)) { + if (!(bool) result || (speculationKind != SpeculationKind::TryParse)) { currentToken = saveToken; if (speculationKind != SpeculationKind::Reparse) { parseDiagnostics.resize(saveParseDiagnosticsLength); @@ -1380,6 +1400,7 @@ namespace ts { */ template T lookAhead(const function &callback) { + ZoneScoped; return speculationHelper(callback, SpeculationKind::Lookahead); } @@ -1428,13 +1449,11 @@ namespace ts { void parseErrorForInvalidName(DiagnosticMessage nameDiagnostic, DiagnosticMessage blankDiagnostic, SyntaxKind tokenIfBlankName) { if (token() == tokenIfBlankName) { parseErrorAtCurrentToken(blankDiagnostic); - } - else { + } else { parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue()); } } - /** * Provides a better error message than the generic "';' expected" if possible for * known common variants of a missing semicolon, such as from a mispelled names. @@ -1554,8 +1573,7 @@ namespace ts { if (type && !canParseSemicolon()) { if (initializer) { parseErrorAtCurrentToken(Diagnostics::_0_expected, tokenToString(SyntaxKind::SemicolonToken)); - } - else { + } else { parseErrorAtCurrentToken(Diagnostics::Expected_for_property_initializer); } return; @@ -1592,6 +1610,7 @@ namespace ts { template shared finishNode(shared node, int pos, optional end = {}) { + ZoneScoped; setTextRangePosEnd(node, pos, end ? *end : scanner.getStartPos()); if (contextFlags) { node->flags |= contextFlags; @@ -1610,6 +1629,7 @@ namespace ts { template shared parseTokenNode() { + ZoneScoped; auto pos = getNodePos(); auto kind = token(); nextToken(); @@ -1619,6 +1639,7 @@ namespace ts { // function parseOptionalToken(t: TKind): Token; template sharedOpt parseOptionalToken(SyntaxKind t) { + ZoneScoped; if (token() == t) { return parseTokenNode(); } @@ -1650,12 +1671,19 @@ namespace ts { return tryParseSemicolon() || parseExpected(SyntaxKind::SemicolonToken); } - NodeArray createNodeArray(vector> elements, int pos, optional end = {}, optional hasTrailingComma = {}) { + shared createNodeArray(const vector> &elements, int pos, optional end = {}, optional hasTrailingComma = {}) { auto array = factory.createNodeArray(elements, hasTrailingComma); setTextRangePosEnd(array, pos, end ? *end : scanner.getStartPos()); return array; } + //for empty call: createNodeArray(nullptr) + shared createNodeArray(vector> *elements, int pos, optional end = {}, optional hasTrailingComma = {}) { + auto array = factory.createNodeArray(elements ? *elements : (vector>) {}, hasTrailingComma); + setTextRangePosEnd(array, pos, end ? *end : scanner.getStartPos()); + return array; + } + // function createMissingNode(kind: T["kind"], reportAtCurrentPosition: false, optional diagnosticMessage, arg0?: any): T; // function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): T; template @@ -1674,14 +1702,15 @@ namespace ts { kind == SyntaxKind::StringLiteral ? factory.createStringLiteral("", /*isSingleQuote*/ {}) : kind == SyntaxKind::MissingDeclaration ? factory.createMissingDeclaration() : factory.createToken(kind); - auto a = finishNode(result, pos); + return to(finishNode(result, pos)); } string internIdentifier(string text) { auto identifier = get(identifiers, text); if (!identifier) { identifier = text; - set(identifiers, text, *identifier); + identifiers[text] = text; +// set(identifiers, text, *identifier); } return *identifier; } @@ -1713,7 +1742,7 @@ namespace ts { * of invoking the callback is returned from this function. */ template - T tryParse(function callback) { + T tryParse(const function &callback) { return speculationHelper(callback, SpeculationKind::TryParse); } @@ -1732,7 +1761,7 @@ namespace ts { return token() == SyntaxKind::ClassKeyword || token() == SyntaxKind::FunctionKeyword || token() == SyntaxKind::InterfaceKeyword || (token() == SyntaxKind::AbstractKeyword && lookAhead(CALLBACK(nextTokenIsClassKeywordOnSameLine)) || - (token() == SyntaxKind::AsyncKeyword && lookAhead(CALLBACK(nextTokenIsFunctionKeywordOnSameLine)))); + (token() == SyntaxKind::AsyncKeyword && lookAhead(CALLBACK(nextTokenIsFunctionKeywordOnSameLine)))); } bool isLiteralPropertyName() { @@ -1796,7 +1825,7 @@ namespace ts { } bool parseContextualModifier(SyntaxKind t) { - return token() == t && tryParse(CALLBACK(CALLBACK(nextTokenCanFollowModifier))); + return token() == t && tryParse(CALLBACK(nextTokenCanFollowModifier)); } bool nextTokenIsOpenParenOrLessThanOrDot() { @@ -2334,6 +2363,7 @@ namespace ts { // True if positioned at the start of a list element bool isListElement(ParsingContext parsingContext, bool inErrorRecovery) { + ZoneScoped; auto node = currentNode(parsingContext); if (node) { return true; @@ -2887,6 +2917,7 @@ namespace ts { template sharedOpt parseListElement(ParsingContext parsingContext, function()> parseElement) { + ZoneScoped; auto node = currentNode(parsingContext); if (node) { return consumeNode(node); @@ -2896,8 +2927,9 @@ namespace ts { } // Parses a list of elements - NodeArray parseList(ParsingContext kind, function()> parseElement) { - auto saveParsingContext = parsingContext; + shared parseList(ParsingContext kind, const function()> &parseElement) { + ZoneScoped; + int saveParsingContext = parsingContext; parsingContext |= 1 << (int) kind; vector> list; @@ -2905,7 +2937,9 @@ namespace ts { while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - list.push_back(parseListElement(kind, parseElement)); + auto n = parseListElement(kind, parseElement); + if (!n) throw runtime_error("No node given"); + list.push_back(n); continue; } @@ -2922,7 +2956,8 @@ namespace ts { // // Parses a comma-delimited list of elements // function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray; // function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray> | undefined; - optional parseDelimitedList(ParsingContext kind, function()> parseElement, optional considerSemicolonAsDelimiter = {}) { + sharedOpt parseDelimitedList(ParsingContext kind, function()> parseElement, optional considerSemicolonAsDelimiter = {}) { + ZoneScoped; auto saveParsingContext = parsingContext; parsingContext |= 1 << (int) kind; vector> list; @@ -2935,7 +2970,7 @@ namespace ts { auto result = parseListElement(kind, parseElement); if (!result) { parsingContext = saveParsingContext; - return nullopt; + return nullptr; } list.push_back(result); commaStart = scanner.getTokenPos(); @@ -2995,14 +3030,14 @@ namespace ts { // isMissingList: true; // } - NodeArray createMissingList() { - auto list = createNodeArray({}, getNodePos()); - list.isMissingList = true; + shared createMissingList() { + auto list = createNodeArray(nullptr, getNodePos()); + list->isMissingList = true; return list; } - bool isMissingList(NodeArray &arr) { - return arr.isMissingList; + bool isMissingList(const shared &arr) { + return arr->isMissingList; } // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues @@ -3076,6 +3111,7 @@ namespace ts { template T doInsideOfContext(/*NodeFlags*/int context, function func) { + ZoneScoped; // contextFlagsToSet will contain only the context flags that // are not currently set that we need to temporarily enable. // We don't just blindly reset to the previous flags to ensure @@ -3098,37 +3134,37 @@ namespace ts { template T allowInAnd(const function &func) { - return doOutsideOfContext((int)NodeFlags::DisallowInContext, func); + return doOutsideOfContext((int) NodeFlags::DisallowInContext, func); } template T disallowInAnd(const function &func) { - return doInsideOfContext((int)NodeFlags::DisallowInContext, func); + return doInsideOfContext((int) NodeFlags::DisallowInContext, func); } template T allowConditionalTypesAnd(const function &func) { - return doOutsideOfContext((int)NodeFlags::DisallowConditionalTypesContext, func); + return doOutsideOfContext((int) NodeFlags::DisallowConditionalTypesContext, func); } template T disallowConditionalTypesAnd(const function &func) { - return doInsideOfContext((int)NodeFlags::DisallowConditionalTypesContext, func); + return doInsideOfContext((int) NodeFlags::DisallowConditionalTypesContext, func); } template T doInYieldContext(const function &func) { - return doInsideOfContext((int)NodeFlags::YieldContext, func); + return doInsideOfContext((int) NodeFlags::YieldContext, func); } template T doInDecoratorContext(const function &func) { - return doInsideOfContext((int)NodeFlags::DecoratorContext, func); + return doInsideOfContext((int) NodeFlags::DecoratorContext, func); } template T doInAwaitContext(const function &func) { - return doInsideOfContext((int)NodeFlags::AwaitContext, func); + return doInsideOfContext((int) NodeFlags::AwaitContext, func); } template T doOutsideOfAwaitContext(const function &func) { - return doOutsideOfContext((int)NodeFlags::AwaitContext, func); + return doOutsideOfContext((int) NodeFlags::AwaitContext, func); } template T doInYieldAndAwaitContext(const function &func) { @@ -3185,7 +3221,7 @@ namespace ts { ); } - NodeArray parseTemplateSpans(bool isTaggedTemplate) { + shared parseTemplateSpans(bool isTaggedTemplate) { auto pos = getNodePos(); vector> list; sharedOpt node; @@ -3202,7 +3238,7 @@ namespace ts { } shared fragment = parseLiteralLikeNode(token()); // Debug::asserts(fragment.kind == SyntaxKind::TemplateHead, "Template head has wrong token kind"); - return dynamic_pointer_cast(fragment); + return reinterpret_pointer_cast(fragment); } shared parseTemplateExpression(bool isTaggedTemplate) { @@ -3229,11 +3265,11 @@ namespace ts { } dotPos = getNodePos(); entity = finishNode( - factory.createQualifiedName( - entity, - parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false) - ), - pos + factory.createQualifiedName( + entity, + parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false) + ), + pos ); } return entity; @@ -3246,21 +3282,21 @@ namespace ts { return parseEntityName(/*allowReservedWords*/ true, Diagnostics::Type_expected); } - optional parseTypeArgumentsOfTypeReference() { + sharedOpt parseTypeArgumentsOfTypeReference() { if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() == SyntaxKind::LessThanToken) { return parseBracketedList(ParsingContext::TypeArguments, CALLBACK(parseType), SyntaxKind::LessThanToken, SyntaxKind::GreaterThanToken); } - return nullopt; + return nullptr; } shared parseTypeReference() { auto pos = getNodePos(); return finishNode( - factory.createTypeReferenceNode( - parseEntityNameOfTypeReference(), - parseTypeArgumentsOfTypeReference() - ), - pos + factory.createTypeReferenceNode( + parseEntityNameOfTypeReference(), + parseTypeArgumentsOfTypeReference() + ), + pos ); } @@ -3271,11 +3307,11 @@ namespace ts { return nodeIsMissing(node->to().typeName); case SyntaxKind::FunctionType: case SyntaxKind::ConstructorType: { - auto f = dynamic_pointer_cast(node); + auto f = reinterpret_pointer_cast(node); return isMissingList(f->parameters) || typeHasArrowFunctionBlockingParseError(f->type); } case SyntaxKind::ParenthesizedType: - return typeHasArrowFunctionBlockingParseError(reinterpret_cast(node).type); + return typeHasArrowFunctionBlockingParseError(reinterpret_cast(node).type); default: return false; } @@ -3400,7 +3436,7 @@ namespace ts { parseExpected(SyntaxKind::TypeOfKeyword); auto entityName = parseEntityName(/*allowReservedWords*/ true); // Make sure we perform ASI to prevent parsing the next line's type arguments as part of an instantiation expression. - optional typeArguments = !scanner.hasPrecedingLineBreak() ? tryParseTypeArguments() : nullopt; + sharedOpt typeArguments = !scanner.hasPrecedingLineBreak() ? tryParseTypeArguments() : nullptr; return finishNode(factory.createTypeQueryNode(entityName, typeArguments), pos); } @@ -3442,8 +3478,7 @@ namespace ts { return false; } - - shared parsePropertyAccessExpressionRest(int pos, shared expression, sharedOpt questionDotToken) { + shared parsePropertyAccessExpressionRest(int pos, const shared &expression, const sharedOpt &questionDotToken) { auto name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true); auto isOptionalChain = questionDotToken || tryReparseOptionalChain(expression); auto propertyAccess = isOptionalChain ? @@ -3455,14 +3490,14 @@ namespace ts { return finishNode(propertyAccess, pos); } - shared parseElementAccessExpressionRest(int pos, shared expression, sharedOpt questionDotToken) { + shared parseElementAccessExpressionRest(int pos, const shared &expression, const sharedOpt &questionDotToken) { sharedOpt argumentExpression; if (token() == SyntaxKind::CloseBracketToken) { argumentExpression = createMissingNode(SyntaxKind::Identifier, /*reportAtCurrentPosition*/ true, Diagnostics::An_element_access_expression_should_take_an_argument); } else { auto argument = allowInAnd>(CALLBACK(parseExpression)); if (isStringOrNumericLiteralLike(argument)) { - dynamic_pointer_cast(argument)->text = internIdentifier(dynamic_pointer_cast(argument)->text); + reinterpret_pointer_cast(argument)->text = internIdentifier(reinterpret_pointer_cast(argument)->text); } argumentExpression = argument; } @@ -3475,7 +3510,7 @@ namespace ts { return finishNode(factory.createElementAccessExpression(expression, argumentExpression), pos); } - shared parseTaggedTemplateRest(int pos, shared tag, sharedOpt questionDotToken, optional typeArguments = {}) { + shared parseTaggedTemplateRest(int pos, shared tag, sharedOpt questionDotToken, sharedOpt typeArguments = {}) { shared templateLiteral = token() == SyntaxKind::NoSubstitutionTemplateLiteral ? (shared) (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) : (shared) parseTemplateExpression(/*isTaggedTemplate*/ true); @@ -3485,7 +3520,7 @@ namespace ts { templateLiteral ); if (questionDotToken || tag->flags & (int) NodeFlags::OptionalChain) { - tagExpression->flags |= (int)NodeFlags::OptionalChain; + tagExpression->flags |= (int) NodeFlags::OptionalChain; } tagExpression->questionDotToken = questionDotToken; return finishNode(tagExpression, pos); @@ -3503,28 +3538,28 @@ namespace ts { return !isStartOfExpression(); } - optional parseTypeArgumentsInExpression() { - if ((contextFlags & (int)NodeFlags::JavaScriptFile) != 0) { + sharedOpt parseTypeArgumentsInExpression() { + if ((contextFlags & (int) NodeFlags::JavaScriptFile) != 0) { // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators. - return nullopt; + return nullptr; } if (reScanLessThanToken() != SyntaxKind::LessThanToken) { - return nullopt; + return nullptr; } nextToken(); auto typeArguments = parseDelimitedList(ParsingContext::TypeArguments, CALLBACK(parseType)); if (!parseExpected(SyntaxKind::GreaterThanToken)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. - return nullopt; + return nullptr; } // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view // it as a relational expression. - return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : nullopt; + return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : nullptr; } shared parseMemberExpressionRest(int pos, shared expression, bool allowOptionalChain) { @@ -3563,14 +3598,14 @@ namespace ts { expression = finishNode(factory.createNonNullExpression(expression), pos); continue; } - auto typeArguments = tryParse>(CALLBACK(CALLBACK(parseTypeArgumentsInExpression))); + auto typeArguments = tryParse>(CALLBACK(parseTypeArgumentsInExpression)); if (typeArguments) { expression = finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos); continue; } } - return dynamic_pointer_cast(expression); + return reinterpret_pointer_cast(expression); } } @@ -3596,7 +3631,8 @@ namespace ts { return finishNode(factory.createDecorator(expression), pos); } - optional parseDecorators() { + sharedOpt parseDecorators() { + ZoneScoped; auto pos = getNodePos(); sharedOpt decorator; vector> list; @@ -3604,7 +3640,7 @@ namespace ts { while (decorator = tryParseDecorator()) { list = append(list, decorator); } - if (list.empty()) return nullopt; + if (list.empty()) return nullptr; return createNodeArray(list, pos); } @@ -3613,6 +3649,7 @@ namespace ts { } sharedOpt tryParseModifier(bool permitInvalidConstAsModifier = false, bool stopOnStartOfClassStaticBlock = false, bool hasSeenStaticModifier = false) { + ZoneScoped; auto pos = getNodePos(); auto kind = token(); @@ -3642,7 +3679,8 @@ namespace ts { * * In such situations, 'permitInvalidConstAsModifier' should be set to true. */ - optional parseModifiers(bool permitInvalidConstAsModifier = false, bool stopOnStartOfClassStaticBlock = false) { + sharedOpt parseModifiers(bool permitInvalidConstAsModifier = false, bool stopOnStartOfClassStaticBlock = false) { + ZoneScoped; auto pos = getNodePos(); auto hasSeenStatic = false; vector> list; @@ -3652,7 +3690,7 @@ namespace ts { list = append(list, modifier); } if (!list.empty()) return createNodeArray(list, pos); - return nullopt; + return nullptr; } bool isParameterNameStart() { @@ -3662,7 +3700,8 @@ namespace ts { return isBindingIdentifier() || token() == SyntaxKind::OpenBracketToken || token() == SyntaxKind::OpenBraceToken; } - shared parseNameOfParameter(optional modifiers) { + shared parseNameOfParameter(const sharedOpt &modifiers) { + ZoneScoped; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] auto name = parseIdentifierOrPattern(Diagnostics::Private_identifiers_cannot_be_used_as_parameters); @@ -3681,6 +3720,7 @@ namespace ts { } sharedOpt parseInitializer() { + ZoneScoped; return parseOptional(SyntaxKind::EqualsToken) ? parseAssignmentExpressionOrHigher() : nullptr; } @@ -3694,7 +3734,7 @@ namespace ts { // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - auto decorators = inOuterAwaitContext ? doInAwaitContext>(CALLBACK(parseDecorators)) : parseDecorators(); + auto decorators = inOuterAwaitContext ? doInAwaitContext>(CALLBACK(parseDecorators)) : parseDecorators(); if (token() == SyntaxKind::ThisKeyword) { auto node = factory.createParameterDeclaration( @@ -3751,15 +3791,13 @@ namespace ts { return parseParameterWorker(inOuterAwaitContext, /*allowAmbiguity*/ false); } - bool shouldParseReturnType(SyntaxKind returnToken, bool isType){ + bool shouldParseReturnType(SyntaxKind returnToken, bool isType) { if (returnToken == SyntaxKind::EqualsGreaterThanToken) { parseExpected(returnToken); return true; - } - else if (parseOptional(SyntaxKind::ColonToken)) { + } else if (parseOptional(SyntaxKind::ColonToken)) { return true; - } - else if (isType && token() == SyntaxKind::EqualsGreaterThanToken) { + } else if (isType && token() == SyntaxKind::EqualsGreaterThanToken) { // This is easy to get backward, especially in type contexts, so parse the type anyway parseErrorAtCurrentToken(Diagnostics::_0_expected, tokenToString(SyntaxKind::ColonToken)); nextToken(); @@ -3770,7 +3808,7 @@ namespace ts { // function parseReturnType(returnToken: SyntaxKind::EqualsGreaterThanToken, isType: boolean): TypeNode; // function parseReturnType(returnToken: SyntaxKind::ColonToken | SyntaxKind::EqualsGreaterThanToken, isType: boolean): TypeNode | undefined; - sharedOpt parseReturnType(SyntaxKind returnToken, bool isType) { + sharedOpt parseReturnType(SyntaxKind returnToken, bool isType) { if (shouldParseReturnType(returnToken, isType)) { return allowConditionalTypesAnd>(CALLBACK(parseTypeOrTypePredicate)); } @@ -3804,13 +3842,13 @@ namespace ts { parseExpected(SyntaxKind::OpenBracketToken); auto elements = parseDelimitedList(ParsingContext::ArrayBindingElements, CALLBACK(parseArrayBindingElement)); parseExpected(SyntaxKind::CloseBracketToken); - return finishNode(factory.createArrayBindingPattern(*elements), pos); + return finishNode(factory.createArrayBindingPattern(elements), pos); } string getTemplateLiteralRawText(SyntaxKind kind) { auto isLast = kind == SyntaxKind::NoSubstitutionTemplateLiteral || kind == SyntaxKind::TemplateTail; auto tokenText = scanner.getTokenText(); - return tokenText.substr(1, tokenText.size() - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2)); + return substring(tokenText, 1, tokenText.size() - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2)); } shared parseLiteralLikeNode(SyntaxKind kind) { @@ -3858,7 +3896,7 @@ namespace ts { return finishNode(factory.createComputedPropertyName(expression), pos); } - string internPrivateIdentifier(string text) { + string internPrivateIdentifier(const string &text) { auto privateIdentifier = get(privateIdentifiers, text); if (!privateIdentifier) { privateIdentifier = text; @@ -3894,6 +3932,7 @@ namespace ts { } shared parseObjectBindingElement() { + ZoneScoped; auto pos = getNodePos(); auto dotDotDotToken = parseOptionalToken(SyntaxKind::DotDotDotToken); auto tokenIsIdentifier = isBindingIdentifier(); @@ -3915,10 +3954,11 @@ namespace ts { parseExpected(SyntaxKind::OpenBraceToken); auto elements = parseDelimitedList(ParsingContext::ObjectBindingElements, CALLBACK(parseObjectBindingElement)); parseExpected(SyntaxKind::CloseBraceToken); - return finishNode(factory.createObjectBindingPattern(*elements), pos); + return finishNode(factory.createObjectBindingPattern(elements), pos); } shared> parseIdentifierOrPattern(optional privateIdentifierDiagnosticMessage = {}) { + ZoneScoped; if (token() == SyntaxKind::OpenBracketToken) { return parseArrayBindingPattern(); } @@ -3990,8 +4030,8 @@ namespace ts { return token() == SyntaxKind::NewKeyword || (token() == SyntaxKind::AbstractKeyword && lookAhead(CALLBACK(nextTokenIsNewKeyword))); } - optional parseModifiersForConstructorType() { - optional modifiers; + sharedOpt parseModifiersForConstructorType() { + sharedOpt modifiers; if (token() == SyntaxKind::AbstractKeyword) { auto pos = getNodePos(); nextToken(); @@ -4090,19 +4130,19 @@ namespace ts { return expression; } - NodeArray parseBracketedList(ParsingContext kind, function()> parseElement, SyntaxKind open, SyntaxKind close) { + shared parseBracketedList(ParsingContext kind, function()> parseElement, SyntaxKind open, SyntaxKind close) { if (parseExpected(open)) { auto result = parseDelimitedList(kind, parseElement); parseExpected(close); - return *result; + return result; } return createMissingList(); } - optional tryParseTypeArguments() { + sharedOpt tryParseTypeArguments() { if (token() == SyntaxKind::LessThanToken) return parseBracketedList(ParsingContext::TypeArguments, CALLBACK(parseType), SyntaxKind::LessThanToken, SyntaxKind::GreaterThanToken); - return nullopt; + return nullptr; } SyntaxKind scanJsxAttributeValue() { @@ -4199,7 +4239,7 @@ namespace ts { return false; } - NodeArray parseJsxChildren(shared openingTag) { + shared parseJsxChildren(shared openingTag) { vector> list; auto listPos = getNodePos(); auto saveParsingContext = parsingContext; @@ -4260,11 +4300,11 @@ namespace ts { auto _opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); sharedOpt result; //JsxElement | JsxSelfClosingElement | JsxFragment if (_opening->kind == SyntaxKind::JsxOpeningElement) { - auto opening = dynamic_pointer_cast(_opening); + auto opening = reinterpret_pointer_cast(_opening); auto children = parseJsxChildren(opening); sharedOpt closingElement; // JsxClosingElement; - auto lastChild = children.list[children.length() - 1]; + auto lastChild = children->list[children->length() - 1]; if (lastChild && lastChild->kind == SyntaxKind::JsxElement && !tagNamesAreEquivalent(getTagName(lastChild->to().openingElement), getTagName(lastChild->to().closingElement)) && tagNamesAreEquivalent(getTagName(opening), getTagName(lastChild->to().closingElement))) { @@ -4272,7 +4312,7 @@ namespace ts { // restructure (
(......
)) --> (
(......)
) // (no need to error; the parent will error) auto jsxElement = lastChild->to(); - auto end = jsxElement.children.end; + auto end = jsxElement.children->end; auto newLast = finishNode(factory.createJsxElement( jsxElement.openingElement, jsxElement.children, @@ -4280,9 +4320,9 @@ namespace ts { jsxElement.openingElement->pos, end); - auto c = children.slice(0, children.length() - 1); + auto c = children->slice(0, children->length() - 1); c.push_back(newLast); - children = createNodeArray(c, children.pos, end); + children = createNodeArray(c, children->pos, end); closingElement = jsxElement.closingElement; } else { closingElement = parseJsxClosingElement(opening, inExpressionContext); @@ -4298,7 +4338,7 @@ namespace ts { } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } else if (_opening->kind == SyntaxKind::JsxOpeningFragment) { - auto opening = dynamic_pointer_cast(_opening); + auto opening = reinterpret_pointer_cast(_opening); result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { assert(_opening->kind == SyntaxKind::JsxSelfClosingElement); @@ -4378,7 +4418,7 @@ namespace ts { return finishNode(factory.createJsxOpeningFragment(), pos); } auto tagName = parseJsxElementName(); - optional typeArguments = (contextFlags & (int) NodeFlags::JavaScriptFile) == 0 ? tryParseTypeArguments() : nullopt; + sharedOpt typeArguments = (contextFlags & (int) NodeFlags::JavaScriptFile) == 0 ? tryParseTypeArguments() : nullptr; auto attributes = parseJsxAttributes(); sharedOpt node; @@ -4414,16 +4454,16 @@ namespace ts { return nextToken() == SyntaxKind::DotToken; } - optional parseTypeParameters() { + sharedOpt parseTypeParameters() { if (token() == SyntaxKind::LessThanToken) { return parseBracketedList(ParsingContext::TypeParameters, CALLBACK(parseTypeParameter), SyntaxKind::LessThanToken, SyntaxKind::GreaterThanToken); } - return nullopt; + return nullptr; } // function parseParametersWorker(SignatureFlags flags, allowAmbiguity: true): NodeArray; // function parseParametersWorker(SignatureFlags flags, allowAmbiguity: false): NodeArray | undefined; - optional parseParametersWorker(int flags, bool allowAmbiguity) { + sharedOpt parseParametersWorker(int flags, bool allowAmbiguity) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -4440,12 +4480,12 @@ namespace ts { auto savedYieldContext = inYieldContext(); auto savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & (int)SignatureFlags::Yield)); - setAwaitContext(!!(flags & (int)SignatureFlags::Await)); + setYieldContext(!!(flags & (int) SignatureFlags::Yield)); + setAwaitContext(!!(flags & (int) SignatureFlags::Await)); - optional parameters = flags & (int)SignatureFlags::JSDoc ? - NodeArray() : //we ignore JSDoc, parseDelimitedList(ParsingContext::JSDocParameters, parseJSDocParameter) : - parseDelimitedList(ParsingContext::Parameters, [this, &allowAmbiguity, savedAwaitContext]()->sharedOpt { return allowAmbiguity ? parseParameter(savedAwaitContext) : parseParameterForSpeculation(savedAwaitContext); }); + sharedOpt parameters = flags & (int) SignatureFlags::JSDoc ? + make_shared() : //we ignore JSDoc, parseDelimitedList(ParsingContext::JSDocParameters, parseJSDocParameter) : + parseDelimitedList(ParsingContext::Parameters, [this, &allowAmbiguity, savedAwaitContext]()->sharedOpt { return allowAmbiguity ? parseParameter(savedAwaitContext) : parseParameterForSpeculation(savedAwaitContext); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); @@ -4453,7 +4493,7 @@ namespace ts { return parameters; } - NodeArray parseParameters(int flags) { + shared parseParameters(int flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -4473,11 +4513,11 @@ namespace ts { auto parameters = parseParametersWorker(flags, /*allowAmbiguity*/ true); parseExpected(SyntaxKind::CloseParenToken); - return *parameters; + return parameters; } - NodeArray parseParameters(SignatureFlags flags) { - return parseParameters((int)flags); + shared parseParameters(SignatureFlags flags) { + return parseParameters((int) flags); } shared parseSignatureMember(SyntaxKind kind) { @@ -4492,8 +4532,8 @@ namespace ts { auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ true); parseTypeMemberSemicolon(); shared node = kind == SyntaxKind::CallSignature - ? (shared)factory.createCallSignature(typeParameters, parameters, type) - : (shared)factory.createConstructSignature(typeParameters, parameters, type); + ? (shared) factory.createCallSignature(typeParameters, parameters, type) + : (shared) factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -4509,8 +4549,8 @@ namespace ts { if (lastError) { auto b = createDetachedDiagnostic(fileName, openPosition, 1, Diagnostics::The_parser_expected_to_find_a_1_to_match_the_0_token_here, {tokenToString(openKind), tokenToString(closeKind)}); addRelatedInfo( - *lastError, - {b} + *lastError, + {b} ); } } @@ -4531,8 +4571,7 @@ namespace ts { } return result; - } - else { + } else { auto statements = createMissingList(); return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ false), pos), hasJSDoc); } @@ -4540,10 +4579,10 @@ namespace ts { shared parseFunctionBlock(int flags, optional diagnosticMessage = {}) { auto savedYieldContext = inYieldContext(); - setYieldContext(!!(flags & (int)SignatureFlags::Yield)); + setYieldContext(!!(flags & (int) SignatureFlags::Yield)); auto savedAwaitContext = inAwaitContext(); - setAwaitContext(!!(flags & (int)SignatureFlags::Await)); + setAwaitContext(!!(flags & (int) SignatureFlags::Await)); auto savedTopLevel = topLevel; topLevel = false; @@ -4555,7 +4594,7 @@ namespace ts { setDecoratorContext(/*val*/ false); } - auto block = parseBlock(!!(flags & (int)SignatureFlags::IgnoreMissingOpenBrace), diagnosticMessage); + auto block = parseBlock(!!(flags & (int) SignatureFlags::IgnoreMissingOpenBrace), diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -4577,15 +4616,15 @@ namespace ts { return parseFunctionBlock(flags, diagnosticMessage); } - shared parseAccessorDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers, SyntaxKind kind) { + shared parseAccessorDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers, SyntaxKind kind) { auto name = parsePropertyName(); auto typeParameters = parseTypeParameters(); auto parameters = parseParameters(SignatureFlags::None); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ false); - auto body = parseFunctionBlockOrSemicolon((int)SignatureFlags::None); + auto body = parseFunctionBlockOrSemicolon((int) SignatureFlags::None); shared node = kind == SyntaxKind::GetAccessor - ? (shared)factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : (shared)factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? (shared) factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) + : (shared) factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors if (node->is()) { node->to().typeParameters = typeParameters; @@ -4625,11 +4664,9 @@ namespace ts { if (isIdentifier()) { return true; } - } - else if (!isIdentifier()) { + } else if (!isIdentifier()) { return false; - } - else { + } else { // Skip the identifier nextToken(); } @@ -4657,15 +4694,15 @@ namespace ts { return token() == SyntaxKind::OpenBracketToken && lookAhead(CALLBACK(isUnambiguouslyIndexSignature)); } - shared parseIndexSignatureDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers) { - auto parameters = parseBracketedList(ParsingContext::Parameters, [this]() -> shared{ return parseParameter(/*inOuterAwaitContext*/ false); }, SyntaxKind::OpenBracketToken, SyntaxKind::CloseBracketToken); + shared parseIndexSignatureDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers) { + auto parameters = parseBracketedList(ParsingContext::Parameters, [this]()->shared { return parseParameter(/*inOuterAwaitContext*/ false); }, SyntaxKind::OpenBracketToken, SyntaxKind::CloseBracketToken); auto type = parseTypeAnnotation(); parseTypeMemberSemicolon(); auto node = factory.createIndexSignature(decorators, modifiers, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } - shared parsePropertyOrMethodSignature(int pos, bool hasJSDoc, optional modifiers) { + shared parsePropertyOrMethodSignature(int pos, bool hasJSDoc, sharedOpt modifiers) { auto name = parsePropertyName(); auto questionToken = parseOptionalToken(SyntaxKind::QuestionToken); shared node; @@ -4676,8 +4713,7 @@ namespace ts { auto parameters = parseParameters(SignatureFlags::Type); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ true); node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type); - } - else { + } else { auto type = parseTypeAnnotation(); auto p = factory.createPropertySignature(modifiers, name, questionToken, type); // Although type literal properties cannot not have initializers, we attempt @@ -4714,8 +4750,8 @@ namespace ts { return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers); } - NodeArray parseObjectTypeMembers() { - NodeArray members; + shared parseObjectTypeMembers() { + shared members; if (parseExpected(SyntaxKind::OpenBraceToken)) { members = parseList(ParsingContext::TypeMembers, CALLBACK(parseTypeMember)); parseExpected(SyntaxKind::CloseBraceToken); @@ -4747,20 +4783,20 @@ namespace ts { return doOutsideOfContext>(disallowInAndDecoratorContext, CALLBACK(parseArgumentOrArrayLiteralElement)); } - NodeArray parseArgumentList() { + shared parseArgumentList() { parseExpected(SyntaxKind::OpenParenToken); auto result = parseDelimitedList(ParsingContext::ArgumentExpressions, CALLBACK(parseArgumentExpression)); parseExpected(SyntaxKind::CloseParenToken); - return *result; + return result; } shared parseCallExpressionRest(int pos, shared expression) { while (true) { expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true); - optional typeArguments; + sharedOpt typeArguments; auto questionDotToken = parseOptionalToken(SyntaxKind::QuestionDotToken); if (questionDotToken) { - typeArguments = tryParse>(CALLBACK(parseTypeArgumentsInExpression)); + typeArguments = tryParse>(CALLBACK(parseTypeArgumentsInExpression)); if (isTemplateStartOfTaggedTemplate()) { expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments); continue; @@ -4774,8 +4810,8 @@ namespace ts { } auto argumentList = parseArgumentList(); auto callExpr = questionDotToken || tryReparseOptionalChain(expression) ? - factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) : - factory.createCallExpression(expression, typeArguments, argumentList); + factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) : + factory.createCallExpression(expression, typeArguments, argumentList); expression = finishNode(callExpr, pos); continue; } @@ -4808,34 +4844,33 @@ namespace ts { return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos); } - shared parseMethodDeclaration( - int pos, - bool hasJSDoc, - optional decorators, - optional modifiers, - sharedOpt asteriskToken, - shared name, - sharedOpt questionToken, - sharedOpt exclamationToken, - optional diagnosticMessage = {} + int pos, + bool hasJSDoc, + sharedOpt decorators, + sharedOpt modifiers, + sharedOpt asteriskToken, + shared name, + sharedOpt questionToken, + sharedOpt exclamationToken, + optional diagnosticMessage = {} ) { auto isGenerator = asteriskToken ? SignatureFlags::Yield : SignatureFlags::None; auto isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags::Await : SignatureFlags::None; auto typeParameters = parseTypeParameters(); - auto parameters = parseParameters((int)isGenerator | (int)isAsync); + auto parameters = parseParameters((int) isGenerator | (int) isAsync); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ false); - auto body = parseFunctionBlockOrSemicolon((int)isGenerator | (int)isAsync, diagnosticMessage); + auto body = parseFunctionBlockOrSemicolon((int) isGenerator | (int) isAsync, diagnosticMessage); auto node = factory.createMethodDeclaration( - decorators, - modifiers, - asteriskToken, - name, - questionToken, - typeParameters, - parameters, - type, - body + decorators, + modifiers, + asteriskToken, + name, + questionToken, + typeParameters, + parameters, + type, + body ); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node->exclamationToken = exclamationToken; @@ -4843,6 +4878,7 @@ namespace ts { } shared parseObjectLiteralElement() { + ZoneScoped; auto pos = getNodePos(); auto hasJSDoc = hasPrecedingJSDocComment(); @@ -4890,8 +4926,7 @@ namespace ts { n->questionToken = questionToken; n->exclamationToken = exclamationToken; node = n; - } - else { + } else { parseExpected(SyntaxKind::ColonToken); auto initializer = allowInAnd>(CALLBACK(parseAssignmentExpressionOrHigher)); auto n = factory.createPropertyAssignment(name, initializer); @@ -4935,15 +4970,15 @@ namespace ts { auto asteriskToken = parseOptionalToken(SyntaxKind::AsteriskToken); auto isGenerator = asteriskToken ? SignatureFlags::Yield : SignatureFlags::None; auto isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags::Await : SignatureFlags::None; - auto name = (int)isGenerator && (int)isAsync ? doInYieldAndAwaitContext>(CALLBACK(parseOptionalBindingIdentifier)) : - (int)isGenerator ? doInYieldContext>(CALLBACK(parseOptionalBindingIdentifier)) : - (int)isAsync ? doInAwaitContext>(CALLBACK(parseOptionalBindingIdentifier)) : - parseOptionalBindingIdentifier(); + auto name = (int) isGenerator && (int) isAsync ? doInYieldAndAwaitContext>(CALLBACK(parseOptionalBindingIdentifier)) : + (int) isGenerator ? doInYieldContext>(CALLBACK(parseOptionalBindingIdentifier)) : + (int) isAsync ? doInAwaitContext>(CALLBACK(parseOptionalBindingIdentifier)) : + parseOptionalBindingIdentifier(); auto typeParameters = parseTypeParameters(); - auto parameters = parseParameters((int)isGenerator | (int)isAsync); + auto parameters = parseParameters((int) isGenerator | (int) isAsync); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ false); - auto body = parseFunctionBlock((int)isGenerator | (int)isAsync); + auto body = parseFunctionBlock((int) isGenerator | (int) isAsync); setDecoratorContext(savedDecoratorContext); @@ -4962,15 +4997,15 @@ namespace ts { // - class with name 'implements' // 'isImplementsClause' helps to disambiguate between these two cases return isBindingIdentifier() && !isImplementsClause() - ? createIdentifier(isBindingIdentifier()) - : nullptr; + ? createIdentifier(isBindingIdentifier()) + : nullptr; } shared parseExpressionWithTypeArguments() { auto pos = getNodePos(); auto expression = parseLeftHandSideExpressionOrHigher(); if (expression->kind == SyntaxKind::ExpressionWithTypeArguments) { - return dynamic_pointer_cast(expression); + return reinterpret_pointer_cast(expression); } auto typeArguments = tryParseTypeArguments(); return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos); @@ -4982,10 +5017,10 @@ namespace ts { Debug::asserts(tok == SyntaxKind::ExtendsKeyword || tok == SyntaxKind::ImplementsKeyword); // isListElement() should ensure this. nextToken(); auto types = parseDelimitedList(ParsingContext::HeritageClauseElement, CALLBACK(parseExpressionWithTypeArguments)); - return finishNode(factory.createHeritageClause(tok, *types), pos); + return finishNode(factory.createHeritageClause(tok, types), pos); } - optional parseHeritageClauses() { + sharedOpt parseHeritageClauses() { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } @@ -4993,7 +5028,7 @@ namespace ts { return parseList(ParsingContext::HeritageClauses, CALLBACK(parseHeritageClause)); } - return nullopt; + return nullptr; } shared parseClassStaticBlockBody() { @@ -5011,7 +5046,7 @@ namespace ts { return body; } - shared parseClassStaticBlockDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers) { + shared parseClassStaticBlockDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers) { parseExpectedToken(SyntaxKind::StaticKeyword); auto body = parseClassStaticBlockBody(); return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); @@ -5022,7 +5057,7 @@ namespace ts { return parseExpected(SyntaxKind::ConstructorKeyword); } if (token() == SyntaxKind::StringLiteral && lookAhead(CALLBACK(nextToken)) == SyntaxKind::OpenParenToken) { - return tryParse([this]() -> bool { + return tryParse([this]()->bool { auto literalNode = parseLiteralNode(); return literalNode->text == "constructor"; }); @@ -5030,14 +5065,13 @@ namespace ts { return false; } - - sharedOpt tryParseConstructorDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers) { - return tryParse>([this, &decorators, &modifiers, &pos, &hasJSDoc]() -> sharedOpt { + sharedOpt tryParseConstructorDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers) { + return tryParse>([this, &decorators, &modifiers, &pos, &hasJSDoc]()->sharedOpt { if (parseConstructorName()) { auto typeParameters = parseTypeParameters(); auto parameters = parseParameters(SignatureFlags::None); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ false); - auto body = parseFunctionBlockOrSemicolon((int)SignatureFlags::None, Diagnostics::or_expected); + auto body = parseFunctionBlockOrSemicolon((int) SignatureFlags::None, Diagnostics::or_expected); auto node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. node->typeParameters = typeParameters; @@ -5053,26 +5087,26 @@ namespace ts { } shared parsePropertyDeclaration( - int pos, - bool hasJSDoc, - optional decorators, - optional modifiers, - shared name, - sharedOpt questionToken + int pos, + bool hasJSDoc, + sharedOpt decorators, + sharedOpt modifiers, + shared name, + sharedOpt questionToken ) { sharedOpt exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(SyntaxKind::ExclamationToken) : nullptr; auto type = parseTypeAnnotation(); - auto initializer = doOutsideOfContext>((int)NodeFlags::YieldContext | (int)NodeFlags::AwaitContext | (int)NodeFlags::DisallowInContext, CALLBACK(parseInitializer)); + auto initializer = doOutsideOfContext>((int) NodeFlags::YieldContext | (int) NodeFlags::AwaitContext | (int) NodeFlags::DisallowInContext, CALLBACK(parseInitializer)); parseSemicolonAfterPropertyName(name, type, initializer); - auto node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken ? (shared)questionToken : (shared)exclamationToken, type, initializer); + auto node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken ? (shared) questionToken : (shared) exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } shared parsePropertyOrMethodDeclaration( - int pos, - bool hasJSDoc, - optional decorators, - optional modifiers + int pos, + bool hasJSDoc, + sharedOpt decorators, + sharedOpt modifiers ) { auto asteriskToken = parseOptionalToken(SyntaxKind::AsteriskToken); auto name = parsePropertyName(); @@ -5128,13 +5162,12 @@ namespace ts { auto isAmbient = some(modifiers, CALLBACK(isDeclareModifier)); if (isAmbient && modifiers) { for (auto &m: modifiers->list) { - m->flags |= (int)NodeFlags::Ambient; + m->flags |= (int) NodeFlags::Ambient; } - return doInsideOfContext>((int)NodeFlags::Ambient, [&]() { + return doInsideOfContext>((int) NodeFlags::Ambient, [&]() { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); }); - } - else { + } else { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); } } @@ -5149,11 +5182,11 @@ namespace ts { throw runtime_error("Should not have attempted to parse class member declaration."); } - NodeArray parseClassMembers() { + shared parseClassMembers() { return parseList(ParsingContext::ClassMembers, CALLBACK(parseClassElement)); } - shared parseClassDeclarationOrExpression(int pos, bool hasJSDoc, optional decorators, optional modifiers, SyntaxKind kind) { + shared parseClassDeclarationOrExpression(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers, SyntaxKind kind) { auto savedAwaitContext = inAwaitContext(); parseExpected(SyntaxKind::ClassKeyword); @@ -5163,25 +5196,24 @@ namespace ts { if (some(modifiers, isExportModifier)) setAwaitContext(/*value*/ true); auto heritageClauses = parseHeritageClauses(); - NodeArray members; + shared members; if (parseExpected(SyntaxKind::OpenBraceToken)) { // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } members = parseClassMembers(); parseExpected(SyntaxKind::CloseBraceToken); - } - else { + } else { members = createMissingList(); } setAwaitContext(savedAwaitContext); auto node = kind == SyntaxKind::ClassDeclaration - ? (shared)factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : (shared)factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? (shared) factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) + : (shared) factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } shared parseClassExpression() { - return dynamic_pointer_cast(parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ {}, /*modifiers*/ {}, SyntaxKind::ClassExpression)); + return reinterpret_pointer_cast(parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ {}, /*modifiers*/ {}, SyntaxKind::ClassExpression)); } shared parseNewExpressionOrNewDotTarget() { @@ -5193,13 +5225,13 @@ namespace ts { } auto expressionPos = getNodePos(); shared expression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false); - optional typeArguments; + sharedOpt typeArguments; // Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments if (expression->kind == SyntaxKind::ExpressionWithTypeArguments) { typeArguments = expression->to().typeArguments; expression = expression->to().expression; } - optional argumentList; + sharedOpt argumentList; if (token() == SyntaxKind::OpenParenToken) argumentList = parseArgumentList(); return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); @@ -5255,6 +5287,7 @@ namespace ts { } shared parseMemberExpressionOrHigher() { + ZoneScoped; // Note: to make our lives simpler, we decompose the NewExpression productions and // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. // like so: @@ -5308,11 +5341,12 @@ namespace ts { } shared parseSuperExpression() { + ZoneScoped; auto pos = getNodePos(); auto expression = parseTokenNode(); if (token() == SyntaxKind::LessThanToken) { auto startPos = getNodePos(); - auto typeArguments = tryParse>(CALLBACK(parseTypeArgumentsInExpression)); + auto typeArguments = tryParse>(CALLBACK(parseTypeArgumentsInExpression)); if (typeArguments) { parseErrorAt(startPos, getNodePos(), Diagnostics::super_may_not_use_type_arguments); } @@ -5330,6 +5364,7 @@ namespace ts { } shared parseLeftHandSideExpressionOrHigher() { + ZoneScoped; // Original Ecma: // LeftHandSideExpression: See 11.2 // NewExpression @@ -5396,12 +5431,14 @@ namespace ts { } shared parseBinaryExpressionOrHigher(int precedence) { + ZoneScoped; auto pos = getNodePos(); auto leftOperand = parseUnaryExpressionOrHigher(); return parseBinaryExpressionRest(precedence, leftOperand, pos); } shared parseBinaryExpressionRest(int precedence, shared leftOperand, int pos) { + ZoneScoped; while (true) { // We either have a binary operator here, or we're finished. We call // reScanGreaterToken so that we merge token sequences like > and = into >= @@ -5431,8 +5468,8 @@ namespace ts { // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand auto consumeCurrentOperator = token() == SyntaxKind::AsteriskAsteriskToken ? - newPrecedence >= (int)precedence : - newPrecedence > (int)precedence; + newPrecedence >= (int) precedence : + newPrecedence > (int) precedence; if (!consumeCurrentOperator) { break; @@ -5450,13 +5487,11 @@ namespace ts { // by a function call to 'as' with the argument 'Bar' if (scanner.hasPrecedingLineBreak()) { break; - } - else { + } else { nextToken(); leftOperand = makeAsExpression(leftOperand, parseType()); } - } - else { + } else { leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos); } @@ -5477,6 +5512,7 @@ namespace ts { * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ shared parseUpdateExpression() { + ZoneScoped; if (token() == SyntaxKind::PlusPlusToken || token() == SyntaxKind::MinusMinusToken) { auto pos = getNodePos(); return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd>(CALLBACK(parseLeftHandSideExpressionOrHigher))), pos); @@ -5550,6 +5586,7 @@ namespace ts { * 9) [+Await] await UnaryExpression[?yield] */ shared parseSimpleUnaryExpression() { + ZoneScoped; switch (token()) { case SyntaxKind::PlusToken: case SyntaxKind::MinusToken: @@ -5573,7 +5610,7 @@ namespace ts { } // falls through default: - return dynamic_pointer_cast(parseUpdateExpression()); + return reinterpret_pointer_cast(parseUpdateExpression()); } } @@ -5586,7 +5623,6 @@ namespace ts { return finishNode(factory.createTypeAssertion(type, expression), pos); } - /** * Parse ES7 exponential expression and await expression * @@ -5596,6 +5632,7 @@ namespace ts { * */ shared parseUnaryExpressionOrHigher() { + ZoneScoped; /** * ES7 UpdateExpression: * 1) LeftHandSideExpression[?Yield] @@ -5680,8 +5717,8 @@ namespace ts { auto parameters = parseParameters(SignatureFlags::Type); auto type = parseReturnType(SyntaxKind::EqualsGreaterThanToken, /*isType*/ false); auto node = isConstructorType - ? (shared)factory.createConstructorTypeNode1(modifiers, typeParameters, parameters, type) - : (shared)factory.createFunctionTypeNode(typeParameters, parameters, type); + ? (shared) factory.createConstructorTypeNode1(modifiers, typeParameters, parameters, type) + : (shared) factory.createFunctionTypeNode(typeParameters, parameters, type); if (!isConstructorType) node->modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -5721,7 +5758,6 @@ namespace ts { return token() == SyntaxKind::DotToken ? nullptr : node; } - shared parseJSDocAllType() { throw runtime_error("JSDoc not supported"); // auto pos = getNodePos(); @@ -5735,7 +5771,7 @@ namespace ts { nextToken(); } shared expression = - token() == SyntaxKind::TrueKeyword || token() == SyntaxKind::FalseKeyword || token() == SyntaxKind::NullKeyword ? + token() == SyntaxKind::TrueKeyword || token() == SyntaxKind::FalseKeyword || token() == SyntaxKind::NullKeyword ? parseTokenNode() : parseLiteralLikeNode(token()); if (negative) { @@ -5750,8 +5786,9 @@ namespace ts { } shared parseAssertEntry() { + ZoneScoped; auto pos = getNodePos(); - shared name = tokenIsIdentifierOrKeyword(token()) ? (shared)parseIdentifierName() : (shared)parseLiteralLikeNode(SyntaxKind::StringLiteral); + shared name = tokenIsIdentifierOrKeyword(token()) ? (shared) parseIdentifierName() : (shared) parseLiteralLikeNode(SyntaxKind::StringLiteral); parseExpected(SyntaxKind::ColonToken); auto value = parseAssignmentExpressionOrHigher(); return finishNode(factory.createAssertEntry(name, value), pos); @@ -5770,14 +5807,13 @@ namespace ts { auto lastError = lastOrUndefined(parseDiagnostics); if (lastError && lastError->code == Diagnostics::_0_expected.code) { addRelatedInfo( - *lastError, - {createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics::The_parser_expected_to_find_a_1_to_match_the_0_token_here, {"{", "}"})} + *lastError, + {createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics::The_parser_expected_to_find_a_1_to_match_the_0_token_here, {"{", "}"})} ); } } - return finishNode(factory.createAssertClause(*elements, multiLine), pos); - } - else { + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } else { auto elements = createNodeArray({}, getNodePos(), /*end*/ {}, /*hasTrailingComma*/ false); return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } @@ -5795,16 +5831,16 @@ namespace ts { auto lastError = lastOrUndefined(parseDiagnostics); if (lastError && lastError->code == Diagnostics::_0_expected.code) { addRelatedInfo( - *lastError, - {createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics::The_parser_expected_to_find_a_1_to_match_the_0_token_here, {"{", "}"})} + *lastError, + {createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics::The_parser_expected_to_find_a_1_to_match_the_0_token_here, {"{", "}"})} ); } } return finishNode(factory.createImportTypeAssertionContainer(clause, multiLine), pos); } - shared parseImportType() { - sourceFlags |= (int)NodeFlags::PossiblyContainsDynamicImport; + shared parseImportType() { + sourceFlags |= (int) NodeFlags::PossiblyContainsDynamicImport; auto pos = getNodePos(); auto isTypeOf = parseOptional(SyntaxKind::TypeOfKeyword); parseExpected(SyntaxKind::ImportKeyword); @@ -5862,7 +5898,7 @@ namespace ts { } auto type = parseTypeAnnotation(); parseSemicolon(); - auto members = parseList(ParsingContext::TypeMembers, [this]() {return parseTypeMember();}); + auto members = parseList(ParsingContext::TypeMembers, [this]() { return parseTypeMember(); }); parseExpected(SyntaxKind::CloseBraceToken); return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } @@ -5912,10 +5948,10 @@ namespace ts { shared parseTupleType() { auto pos = getNodePos(); return finishNode( - factory.createTupleTypeNode( - parseBracketedList(ParsingContext::TupleElementTypes, CALLBACK(parseTupleElementNameOrTupleElementType), SyntaxKind::OpenBracketToken, SyntaxKind::CloseBracketToken) - ), - pos + factory.createTupleTypeNode( + parseBracketedList(ParsingContext::TupleElementTypes, CALLBACK(parseTupleElementNameOrTupleElementType), SyntaxKind::OpenBracketToken, SyntaxKind::CloseBracketToken) + ), + pos ); } @@ -5930,7 +5966,7 @@ namespace ts { shared parseAssertsTypePredicate() { auto pos = getNodePos(); auto assertsModifier = parseExpectedToken(SyntaxKind::AssertsKeyword); - shared parameterName = token() == SyntaxKind::ThisKeyword ? (shared)parseThisTypeNode() : (shared)parseIdentifier(); + shared parameterName = token() == SyntaxKind::ThisKeyword ? (shared) parseThisTypeNode() : (shared) parseIdentifier(); sharedOpt type = parseOptional(SyntaxKind::IsKeyword) ? parseType() : nullptr; return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos); } @@ -5938,34 +5974,33 @@ namespace ts { shared parseTemplateTypeSpan() { auto pos = getNodePos(); return finishNode( - factory.createTemplateLiteralTypeSpan( - parseType(), - parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false) - ), - pos + factory.createTemplateLiteralTypeSpan( + parseType(), + parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false) + ), + pos ); } - NodeArray parseTemplateTypeSpans() { + shared parseTemplateTypeSpans() { auto pos = getNodePos(); vector> list; shared node; do { node = parseTemplateTypeSpan(); list.push_back(node); - } - while (node->literal->kind == SyntaxKind::TemplateMiddle); + } while (node->literal->kind == SyntaxKind::TemplateMiddle); return createNodeArray(list, pos); } shared parseTemplateType() { auto pos = getNodePos(); return finishNode( - factory.createTemplateLiteralType( - parseTemplateHead(/*isTaggedTemplate*/ false), - parseTemplateTypeSpans() - ), - pos + factory.createTemplateLiteralType( + parseTemplateHead(/*isTaggedTemplate*/ false), + parseTemplateTypeSpans() + ), + pos ); } @@ -6021,8 +6056,7 @@ namespace ts { auto thisKeyword = parseThisTypeNode(); if (token() == SyntaxKind::IsKeyword && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); - } - else { + } else { return thisKeyword; } } @@ -6073,8 +6107,7 @@ namespace ts { auto indexType = parseType(); parseExpected(SyntaxKind::CloseBracketToken); type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos); - } - else { + } else { parseExpected(SyntaxKind::CloseBracketToken); type = finishNode(factory.createArrayTypeNode(type), pos); } @@ -6108,14 +6141,12 @@ namespace ts { DiagnosticMessage diagnostic; if (isFunctionTypeNode(type)) { diagnostic = isInUnionType - ? Diagnostics::Function_type_notation_must_be_parenthesized_when_used_in_a_union_type - : Diagnostics::Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; - } - else { + ? Diagnostics::Function_type_notation_must_be_parenthesized_when_used_in_a_union_type + : Diagnostics::Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; + } else { diagnostic = isInUnionType - ? Diagnostics::Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type - : Diagnostics::Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; - + ? Diagnostics::Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type + : Diagnostics::Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; } parseErrorAtRange(type, diagnostic); return type; @@ -6124,9 +6155,9 @@ namespace ts { } shared parseUnionOrIntersectionType( - SyntaxKind operatorKind, - function()> parseConstituentType, - function(NodeArray)> createTypeNode //: (types: NodeArray) => UnionOrIntersectionTypeNode + SyntaxKind operatorKind, + function()> parseConstituentType, + function(shared)> createTypeNode //: (types: NodeArray) => UnionOrIntersectionTypeNode ) { auto pos = getNodePos(); auto isUnionType = operatorKind == SyntaxKind::BarToken; @@ -6247,8 +6278,7 @@ namespace ts { auto type = parseType(); if (typePredicateVariable) { return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ {}, typePredicateVariable, type), pos); - } - else { + } else { return type; } } @@ -6259,6 +6289,7 @@ namespace ts { } shared parseExpression() { + ZoneScoped; // Expression[in]: // AssignmentExpression[in] // Expression[in] , AssignmentExpression[in] @@ -6316,6 +6347,7 @@ namespace ts { } shared parseYieldExpression() { + ZoneScoped; auto pos = getNodePos(); // YieldExpression[In] : @@ -6485,19 +6517,19 @@ namespace ts { return Tristate::False; } - optional parseModifiersForArrowFunction() { + sharedOpt parseModifiersForArrowFunction() { if (token() == SyntaxKind::AsyncKeyword) { auto pos = getNodePos(); nextToken(); auto modifier = finishNode(factory.createToken(SyntaxKind::AsyncKeyword), pos); return factory.createNodeArray({modifier}, pos); } - return nullopt; + return nullptr; } shared parseArrowFunctionExpressionBody(bool isAsync) { if (token() == SyntaxKind::OpenBraceToken) { - return parseFunctionBlock(isAsync ? (int)SignatureFlags::Await : (int)SignatureFlags::None); + return parseFunctionBlock(isAsync ? (int) SignatureFlags::Await : (int) SignatureFlags::None); } if (token() != SyntaxKind::SemicolonToken && @@ -6519,14 +6551,14 @@ namespace ts { // up preemptively closing the containing construct. // // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. - return parseFunctionBlock((int)SignatureFlags::IgnoreMissingOpenBrace | (isAsync ? (int)SignatureFlags::Await : (int)SignatureFlags::None)); + return parseFunctionBlock((int) SignatureFlags::IgnoreMissingOpenBrace | (isAsync ? (int) SignatureFlags::Await : (int) SignatureFlags::None)); } auto savedTopLevel = topLevel; topLevel = false; auto node = isAsync - ? doInAwaitContext>(CALLBACK(parseAssignmentExpressionOrHigher)) - : doOutsideOfAwaitContext>(CALLBACK(parseAssignmentExpressionOrHigher)); + ? doInAwaitContext>(CALLBACK(parseAssignmentExpressionOrHigher)) + : doOutsideOfAwaitContext>(CALLBACK(parseAssignmentExpressionOrHigher)); topLevel = savedTopLevel; return node; } @@ -6545,7 +6577,7 @@ namespace ts { // close paren. auto typeParameters = parseTypeParameters(); - NodeArray parameters; + shared parameters; if (!parseExpected(SyntaxKind::OpenParenToken)) { if (!allowAmbiguity) { return nullptr; @@ -6553,13 +6585,13 @@ namespace ts { parameters = createMissingList(); } else { if (!allowAmbiguity) { - auto maybeParameters = parseParametersWorker((int)isAsync, allowAmbiguity); + auto maybeParameters = parseParametersWorker((int) isAsync, allowAmbiguity); if (!maybeParameters) { return nullptr; } - parameters = *maybeParameters; + parameters = maybeParameters; } else { - parameters = *parseParametersWorker((int)isAsync, allowAmbiguity); + parameters = parseParametersWorker((int) isAsync, allowAmbiguity); } if (!parseExpected(SyntaxKind::CloseParenToken) && !allowAmbiguity) { return nullptr; @@ -6620,6 +6652,7 @@ namespace ts { } sharedOpt tryParseParenthesizedArrowFunctionExpression() { + ZoneScoped; auto triState = isParenthesizedArrowFunctionExpression(); if (triState == Tristate::False) { // It's definitely not a parenthesized arrow function expression. @@ -6647,7 +6680,7 @@ namespace ts { return Tristate::False; } // Check for un-parenthesized AsyncArrowFunction - auto expr = parseBinaryExpressionOrHigher((int)OperatorPrecedence::Lowest); + auto expr = parseBinaryExpressionOrHigher((int) OperatorPrecedence::Lowest); if (!scanner.hasPrecedingLineBreak() && expr->kind == SyntaxKind::Identifier && token() == SyntaxKind::EqualsGreaterThanToken) { return Tristate::True; } @@ -6656,16 +6689,17 @@ namespace ts { return Tristate::False; } - shared parseSimpleArrowFunctionExpression(int pos, shared identifier, optional asyncModifier) { + shared parseSimpleArrowFunctionExpression(int pos, shared identifier, sharedOpt asyncModifier) { + ZoneScoped; Debug::asserts(token() == SyntaxKind::EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); auto parameter = factory.createParameterDeclaration( - /*decorators*/ {}, - /*modifiers*/ {}, - /*dotDotDotToken*/ {}, - identifier, - /*questionToken*/ {}, - /*type*/ {}, - /*initializer*/ {} + /*decorators*/ {}, + /*modifiers*/ {}, + /*dotDotDotToken*/ {}, + identifier, + /*questionToken*/ {}, + /*type*/ {}, + /*initializer*/ {} ); finishNode(parameter, identifier->pos); @@ -6678,12 +6712,13 @@ namespace ts { } sharedOpt tryParseAsyncSimpleArrowFunctionExpression() { + ZoneScoped; // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() == SyntaxKind::AsyncKeyword) { if (lookAhead(CALLBACK(isUnParenthesizedAsyncArrowFunctionWorker)) == Tristate::True) { auto pos = getNodePos(); auto asyncModifier = parseModifiersForArrowFunction(); - auto expr = parseBinaryExpressionOrHigher((int)OperatorPrecedence::Lowest); + auto expr = parseBinaryExpressionOrHigher((int) OperatorPrecedence::Lowest); return parseSimpleArrowFunctionExpression(pos, to(expr), asyncModifier); } } @@ -6691,6 +6726,7 @@ namespace ts { } shared parseConditionalExpressionRest(shared leftOperand, int pos) { + ZoneScoped; // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. auto questionToken = parseOptionalToken(SyntaxKind::QuestionToken); if (!questionToken) { @@ -6701,20 +6737,21 @@ namespace ts { // we do not that for the 'whenFalse' part. sharedOpt colonToken; return finishNode( - factory.createConditionalExpression( - leftOperand, - questionToken, - doOutsideOfContext>(disallowInAndDecoratorContext, CALLBACK(parseAssignmentExpressionOrHigher)), - colonToken = parseExpectedToken(SyntaxKind::ColonToken), - nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() - : createMissingNode(SyntaxKind::Identifier, /*reportAtCurrentPosition*/ false, Diagnostics::_0_expected, tokenToString(SyntaxKind::ColonToken)) - ), - pos + factory.createConditionalExpression( + leftOperand, + questionToken, + doOutsideOfContext>(disallowInAndDecoratorContext, CALLBACK(parseAssignmentExpressionOrHigher)), + colonToken = parseExpectedToken(SyntaxKind::ColonToken), + nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(SyntaxKind::Identifier, /*reportAtCurrentPosition*/ false, Diagnostics::_0_expected, tokenToString(SyntaxKind::ColonToken)) + ), + pos ); } shared parseAssignmentExpressionOrHigher() { + ZoneScoped; // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -6755,7 +6792,7 @@ namespace ts { // binary expression here, so we pass in the 'lowest' precedence here so that it matches // and consumes anything. auto pos = getNodePos(); - auto expr = parseBinaryExpressionOrHigher((int)OperatorPrecedence::Lowest); + auto expr = parseBinaryExpressionOrHigher((int) OperatorPrecedence::Lowest); // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single @@ -7051,6 +7088,7 @@ namespace ts { } shared parseVariableDeclaration(optional allowExclamation = {}) { + ZoneScoped; auto pos = getNodePos(); auto hasJSDoc = hasPrecedingJSDocComment(); auto name = parseIdentifierOrPattern(Diagnostics::Private_identifiers_are_not_allowed_in_variable_declarations); @@ -7070,6 +7108,7 @@ namespace ts { } shared parseVariableDeclarationList(bool inForStatementInitializer) { + ZoneScoped; auto pos = getNodePos(); int flags = 0; @@ -7077,10 +7116,10 @@ namespace ts { case SyntaxKind::VarKeyword: break; case SyntaxKind::LetKeyword: - flags |= (int)NodeFlags::Let; + flags |= (int) NodeFlags::Let; break; case SyntaxKind::ConstKeyword: - flags |= (int)NodeFlags::Const; + flags |= (int) NodeFlags::Const; break; default: Debug::fail(); @@ -7097,18 +7136,17 @@ namespace ts { // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - NodeArray declarations; + shared declarations; if (token() == SyntaxKind::OfKeyword && lookAhead(CALLBACK(canFollowContextualOfKeyword))) { declarations = createMissingList(); - } - else { + } else { auto savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); if (inForStatementInitializer) { - declarations = *parseDelimitedList(ParsingContext::VariableDeclarations, [this]() { return parseVariableDeclaration(); }); + declarations = parseDelimitedList(ParsingContext::VariableDeclarations, [this]() { return parseVariableDeclaration(); }); } else { - declarations = *parseDelimitedList(ParsingContext::VariableDeclarations, CALLBACK(parseVariableDeclarationAllowExclamation)); + declarations = parseDelimitedList(ParsingContext::VariableDeclarations, CALLBACK(parseVariableDeclarationAllowExclamation)); } setDisallowInContext(savedDisallowIn); @@ -7117,7 +7155,8 @@ namespace ts { return finishNode(factory.createVariableDeclarationList(declarations, flags), pos); } - shared parseVariableStatement(int pos, bool hasJSDoc, optional decorators, optional modifiers) { + shared parseVariableStatement(int pos, bool hasJSDoc, const sharedOpt &decorators, const sharedOpt &modifiers) { + ZoneScoped; auto declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); auto node = factory.createVariableStatement(modifiers, declarationList); @@ -7137,27 +7176,123 @@ namespace ts { return lookAhead(CALLBACK(nextTokenIsBindingIdentifierOrStartOfDestructuring)); } - shared parseFunctionDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers) { + shared parseFunctionDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers) { auto savedAwaitContext = inAwaitContext(); auto modifierFlags = modifiersToFlags(modifiers); parseExpected(SyntaxKind::FunctionKeyword); auto asteriskToken = parseOptionalToken(SyntaxKind::AsteriskToken); // We don't parse the name here in await context, instead we will report a grammar error in the checker. - auto name = modifierFlags & (int)ModifierFlags::Default ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); + auto name = modifierFlags & (int) ModifierFlags::Default ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); auto isGenerator = asteriskToken ? SignatureFlags::Yield : SignatureFlags::None; - auto isAsync = modifierFlags & (int)ModifierFlags::Async ? SignatureFlags::Await : SignatureFlags::None; + auto isAsync = modifierFlags & (int) ModifierFlags::Async ? SignatureFlags::Await : SignatureFlags::None; auto typeParameters = parseTypeParameters(); - if (modifierFlags & (int)ModifierFlags::Export) setAwaitContext(/*value*/ true); - auto parameters = parseParameters((int)isGenerator | (int)isAsync); + if (modifierFlags & (int) ModifierFlags::Export) setAwaitContext(/*value*/ true); + auto parameters = parseParameters((int) isGenerator | (int) isAsync); auto type = parseReturnType(SyntaxKind::ColonToken, /*isType*/ false); - auto body = parseFunctionBlockOrSemicolon((int)isGenerator | (int)isAsync, Diagnostics::or_expected); + auto body = parseFunctionBlockOrSemicolon((int) isGenerator | (int) isAsync, Diagnostics::or_expected); setAwaitContext(savedAwaitContext); auto node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } + shared parseDeclaration() { + ZoneScoped; + + // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner + // if we can't reuse the declaration, so that we don't do this work twice? + // + // `parseListElement` attempted to get the reused node at this position, + // but the ambient context flag was not yet set, so the node appeared + // not reusable in that context. + auto a = lookAhead>([this]() { + parseDecorators(); + return parseModifiers(); + }); + auto isAmbient = some(a, CALLBACK(isDeclareModifier)); + if (isAmbient) { + auto node = tryReuseAmbientDeclaration(); + if (node) { + return node; + } + } + + auto pos = getNodePos(); + auto hasJSDoc = hasPrecedingJSDocComment(); + auto decorators = parseDecorators(); + auto modifiers = parseModifiers(); + if (isAmbient) { + for (auto &m: modifiers->list) { + m->flags |= (int) NodeFlags::Ambient; + } + return doInsideOfContext>((int) NodeFlags::Ambient, [this, &pos, &hasJSDoc, &decorators, &modifiers]() { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); }); + } else { + return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); + } + } + + sharedOpt tryReuseAmbientDeclaration() { + ZoneScoped; + return doInsideOfContext>((int) NodeFlags::Ambient, [this]()->sharedOpt { + auto node = currentNode((ParsingContext) parsingContext); + if (node) { + return to(consumeNode(node)); + } + return nullptr; + }); + } + + shared parseDeclarationWorker(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers) { + ZoneScoped; + switch (token()) { + case SyntaxKind::VarKeyword: + case SyntaxKind::LetKeyword: + case SyntaxKind::ConstKeyword: + return parseVariableStatement(pos, hasJSDoc, decorators, modifiers); + case SyntaxKind::FunctionKeyword: + return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::ClassKeyword: +// return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::InterfaceKeyword: +// return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::TypeKeyword: +// return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::EnumKeyword: +// return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::GlobalKeyword: +// case SyntaxKind::ModuleKeyword: +// case SyntaxKind::NamespaceKeyword: +// return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::ImportKeyword: +// return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::ExportKeyword: +// nextToken(); +// switch (token()) { +// case SyntaxKind::DefaultKeyword: +// case SyntaxKind::EqualsToken: +// return parseExportAssignment(pos, hasJSDoc, decorators, modifiers); +// case SyntaxKind::AsKeyword: +// return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers); +// default: +// return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers); +// } +// default: +// if (decorators || modifiers) { +// // We reached this point because we encountered decorators and/or modifiers and assumed a declaration +// // would follow. For recovery and error reporting purposes, return an incomplete declaration. +// auto missing = createMissingNode(SyntaxKind::MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics::Declaration_expected); +// setTextRangePos(missing, pos); +// missing.decorators = decorators; +// missing.modifiers = modifiers; +// return missing; +// } +// return undefined!; // TODO: GH#18217 + } + throw runtime_error("not implemented"); + } + shared parseStatement() { + ZoneScoped; switch (token()) { case SyntaxKind::SemicolonToken: return parseEmptyStatement(); @@ -7202,34 +7337,35 @@ namespace ts { // return parseTryStatement(); // case SyntaxKind::DebuggerKeyword: // return parseDebuggerStatement(); -// case SyntaxKind::AtToken: -// return parseDeclaration(); -// case SyntaxKind::AsyncKeyword: -// case SyntaxKind::InterfaceKeyword: -// case SyntaxKind::TypeKeyword: -// case SyntaxKind::ModuleKeyword: -// case SyntaxKind::NamespaceKeyword: -// case SyntaxKind::DeclareKeyword: -// case SyntaxKind::ConstKeyword: -// case SyntaxKind::EnumKeyword: -// case SyntaxKind::ExportKeyword: -// case SyntaxKind::ImportKeyword: -// case SyntaxKind::PrivateKeyword: -// case SyntaxKind::ProtectedKeyword: -// case SyntaxKind::PublicKeyword: -// case SyntaxKind::AbstractKeyword: -// case SyntaxKind::StaticKeyword: -// case SyntaxKind::ReadonlyKeyword: -// case SyntaxKind::GlobalKeyword: -// if (isStartOfDeclaration()) { -// return parseDeclaration(); -// } -// break; + case SyntaxKind::AtToken: + return parseDeclaration(); + case SyntaxKind::AsyncKeyword: + case SyntaxKind::InterfaceKeyword: + case SyntaxKind::TypeKeyword: + case SyntaxKind::ModuleKeyword: + case SyntaxKind::NamespaceKeyword: + case SyntaxKind::DeclareKeyword: + case SyntaxKind::ConstKeyword: + case SyntaxKind::EnumKeyword: + case SyntaxKind::ExportKeyword: + case SyntaxKind::ImportKeyword: + case SyntaxKind::PrivateKeyword: + case SyntaxKind::ProtectedKeyword: + case SyntaxKind::PublicKeyword: + case SyntaxKind::AbstractKeyword: + case SyntaxKind::StaticKeyword: + case SyntaxKind::ReadonlyKeyword: + case SyntaxKind::GlobalKeyword: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; } return to(parseExpressionOrLabeledStatement()); } shared parseSourceFileWorker(ScriptTarget languageVersion, bool setParentNodes, ScriptKind scriptKind, function)> setExternalModuleIndicator) { + ZoneScoped; auto isDeclarationFile = isDeclarationFileName(fileName); if (isDeclarationFile) { contextFlags |= (int) NodeFlags::Ambient; @@ -7241,11 +7377,14 @@ namespace ts { nextToken(); auto statements = parseList(ParsingContext::SourceElements, CALLBACK(parseStatement)); -// Debug::asserts(token() == SyntaxKind::EndOfFileToken); -// auto endOfFileToken = addJSDocComment(parseTokenNode()); -// -// auto sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator); -// +// auto statements = parseList(ParsingContext::SourceElements, [this]() { +// return this->parseStatement(); +// }); + Debug::asserts(token() == SyntaxKind::EndOfFileToken); + auto endOfFileToken = addJSDocComment(parseTokenNode()); + + auto sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator); + // // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future // processCommentPragmas(sourceFile as {} as PragmaContext, sourceText); // processPragmasIntoFields(sourceFile as {} as PragmaContext, reportPragmaDiagnostic); @@ -7263,7 +7402,7 @@ namespace ts { // fixupParentReferences(sourceFile); // } // -// return sourceFile; + return sourceFile; // // function reportPragmaDiagnostic(int pos, end: number, diagnostic: DiagnosticMessage) { // parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); @@ -7271,98 +7410,12 @@ namespace ts { } // -// function parseDeclaration(): Statement { -// // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner -// // if we can't reuse the declaration, so that we don't do this work twice? -// // -// // `parseListElement` attempted to get the reused node at this position, -// // but the ambient context flag was not yet set, so the node appeared -// // not reusable in that context. -// auto isAmbient = some(lookAhead(() => (parseDecorators(), parseModifiers())), isDeclareModifier); -// if (isAmbient) { -// auto node = tryReuseAmbientDeclaration(); -// if (node) { -// return node; -// } -// } -// -// auto pos = getNodePos(); -// auto hasJSDoc = hasPrecedingJSDocComment(); -// auto decorators = parseDecorators(); -// auto modifiers = parseModifiers(); -// if (isAmbient) { -// for (const m of modifiers!) { -// (m as Mutable).flags |= NodeFlags::Ambient; -// } -// return doInsideOfContext(NodeFlags::Ambient, () => parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers)); -// } -// else { -// return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); -// } -// } -// -// function tryReuseAmbientDeclaration(): Statement | undefined { -// return doInsideOfContext(NodeFlags::Ambient, () => { -// auto node = currentNode(parsingContext); -// if (node) { -// return consumeNode(node) as Statement; -// } -// }); -// } -// -// function parseDeclarationWorker(int pos, bool hasJSDoc, optional decorators, optional modifiers): Statement { -// switch (token()) { -// case SyntaxKind::VarKeyword: -// case SyntaxKind::LetKeyword: -// case SyntaxKind::ConstKeyword: -// return parseVariableStatement(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::FunctionKeyword: -// return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::ClassKeyword: -// return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::InterfaceKeyword: -// return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::TypeKeyword: -// return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::EnumKeyword: -// return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::GlobalKeyword: -// case SyntaxKind::ModuleKeyword: -// case SyntaxKind::NamespaceKeyword: -// return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::ImportKeyword: -// return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::ExportKeyword: -// nextToken(); -// switch (token()) { -// case SyntaxKind::DefaultKeyword: -// case SyntaxKind::EqualsToken: -// return parseExportAssignment(pos, hasJSDoc, decorators, modifiers); -// case SyntaxKind::AsKeyword: -// return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers); -// default: -// return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers); -// } -// default: -// if (decorators || modifiers) { -// // We reached this point because we encountered decorators and/or modifiers and assumed a declaration -// // would follow. For recovery and error reporting purposes, return an incomplete declaration. -// auto missing = createMissingNode(SyntaxKind::MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics::Declaration_expected); -// setTextRangePos(missing, pos); -// missing.decorators = decorators; -// missing.modifiers = modifiers; -// return missing; -// } -// return undefined!; // TODO: GH#18217 -// } -// } -// // // DECLARATIONS -// function parseClassDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): ClassDeclaration { +// function parseClassDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ClassDeclaration { // return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, SyntaxKind::ClassDeclaration) as ClassDeclaration; // } // -// function parseInterfaceDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): InterfaceDeclaration { +// function parseInterfaceDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): InterfaceDeclaration { // parseExpected(SyntaxKind::InterfaceKeyword); // auto name = parseIdentifier(); // auto typeParameters = parseTypeParameters(); @@ -7372,7 +7425,7 @@ namespace ts { // return withJSDoc(finishNode(node, pos), hasJSDoc); // } // -// function parseTypeAliasDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): TypeAliasDeclaration { +// function parseTypeAliasDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): TypeAliasDeclaration { // parseExpected(SyntaxKind::TypeKeyword); // auto name = parseIdentifier(); // auto typeParameters = parseTypeParameters(); @@ -7395,7 +7448,7 @@ namespace ts { // return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc); // } // -// function parseEnumDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): EnumDeclaration { +// function parseEnumDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): EnumDeclaration { // parseExpected(SyntaxKind::EnumKeyword); // auto name = parseIdentifier(); // auto members; @@ -7423,7 +7476,7 @@ namespace ts { // return finishNode(factory.createModuleBlock(statements), pos); // } // -// function parseModuleOrNamespaceDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers, flags: NodeFlags): ModuleDeclaration { +// function parseModuleOrNamespaceDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers, flags: NodeFlags): ModuleDeclaration { // // If we are parsing a dotted namespace name, we want to // // propagate the 'Namespace' flag across the names if set. // auto namespaceFlag = flags & NodeFlags::Namespace; @@ -7435,7 +7488,7 @@ namespace ts { // return withJSDoc(finishNode(node, pos), hasJSDoc); // } // -// function parseAmbientExternalModuleDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): ModuleDeclaration { +// function parseAmbientExternalModuleDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ModuleDeclaration { // auto flags: NodeFlags = 0; // auto name; // if (token() == SyntaxKind::GlobalKeyword) { @@ -7458,7 +7511,7 @@ namespace ts { // return withJSDoc(finishNode(node, pos), hasJSDoc); // } // -// function parseModuleDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): ModuleDeclaration { +// function parseModuleDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ModuleDeclaration { // auto flags: NodeFlags = 0; // if (token() == SyntaxKind::GlobalKeyword) { // // global augmentation @@ -7476,7 +7529,7 @@ namespace ts { // return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags); // } // -// function parseNamespaceExportDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): NamespaceExportDeclaration { +// function parseNamespaceExportDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): NamespaceExportDeclaration { // parseExpected(SyntaxKind::AsKeyword); // parseExpected(SyntaxKind::NamespaceKeyword); // auto name = parseIdentifier(); @@ -7488,7 +7541,7 @@ namespace ts { // return withJSDoc(finishNode(node, pos), hasJSDoc); // } // -// function parseImportDeclarationOrImportEqualsDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): ImportEqualsDeclaration | ImportDeclaration { +// function parseImportDeclarationOrImportEqualsDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ImportEqualsDeclaration | ImportDeclaration { // parseExpected(SyntaxKind::ImportKeyword); // // auto afterImportPos = scanner.getStartPos(); @@ -7545,7 +7598,7 @@ namespace ts { // return token() == SyntaxKind::CommaToken || token() == SyntaxKind::FromKeyword; // } // -// function parseImportEqualsDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers, identifier: Identifier, isTypeOnly: boolean): ImportEqualsDeclaration { +// function parseImportEqualsDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers, identifier: Identifier, isTypeOnly: boolean): ImportEqualsDeclaration { // parseExpected(SyntaxKind::EqualsToken); // auto moduleReference = parseModuleReference(); // parseSemicolon(); @@ -7727,7 +7780,7 @@ namespace ts { // return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos); // } // -// function parseExportDeclaration(int pos, bool hasJSDoc, optional decorators, optional modifiers): ExportDeclaration { +// function parseExportDeclaration(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ExportDeclaration { // auto savedAwaitContext = inAwaitContext(); // setAwaitContext(/*value*/ true); // auto exportClause: NamedExportBindings | undefined; @@ -7761,7 +7814,7 @@ namespace ts { // return withJSDoc(finishNode(node, pos), hasJSDoc); // } // -// function parseExportAssignment(int pos, bool hasJSDoc, optional decorators, optional modifiers): ExportAssignment { +// function parseExportAssignment(int pos, bool hasJSDoc, sharedOpt decorators, sharedOpt modifiers): ExportAssignment { // auto savedAwaitContext = inAwaitContext(); // setAwaitContext(/*value*/ true); // auto isExportEquals: boolean | undefined; @@ -8814,7 +8867,8 @@ namespace ts { // } // } - shared parseSourceFile(string fileName, string sourceText, ScriptTarget languageVersion, bool setParentNodes, optional _scriptKind, optional)>> setExternalModuleIndicatorOverride) { + shared parseSourceFile(const string &fileName, const string &sourceText, ScriptTarget languageVersion, bool setParentNodes, optional _scriptKind, optional)>> setExternalModuleIndicatorOverride) { + ZoneScoped; auto scriptKind = ensureScriptKind(fileName, _scriptKind); // if (scriptKind == ScriptKind.JSON) { @@ -9428,8 +9482,8 @@ namespace ts { // Debug::asserts((oldText.length - textChangeRange.span.length + textChangeRange.newLength) == newText.length); // // if (aggressiveChecks || Debug.shouldAssert(AssertionLevel.VeryAggressive)) { -// auto oldTextPrefix = oldText.substr(0, textChangeRange.span.start); -// auto newTextPrefix = newText.substr(0, textChangeRange.span.start); +// auto oldTextPrefix = substr(oldText, 0, textChangeRange.span.start); +// auto newTextPrefix = substr(newText, 0, textChangeRange.span.start); // Debug::asserts(oldTextPrefix == newTextPrefix); // // auto oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); @@ -9801,10 +9855,16 @@ namespace ts { // return argMap; // } - shared createSourceFile(string fileName, string sourceText, variant languageVersionOrOptions, bool setParentNodes = false, optional scriptKind = {}) { + inline shared createSourceFile( + string fileName, + string sourceText, + variant languageVersionOrOptions, + bool setParentNodes = false, + optional scriptKind = {} + ) { // tracing?.push(tracing.Phase.Parse, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); // performance.mark("beforeParse"); - shared_ptr result = make_shared(); + shared result; optional)>> overrideSetExternalModuleIndicator; optional format; diff --git a/src/path.cpp b/src/path.cpp index f32ff33..c0ad92d 100644 --- a/src/path.cpp +++ b/src/path.cpp @@ -11,7 +11,7 @@ namespace ts { return path.size() > extension.size() && endsWith(path, extension); } - bool fileExtensionIsOneOf(const string &path, vector extensions) { + bool fileExtensionIsOneOf(const string &path, const vector &extensions) { for (auto &extension: extensions) { if (fileExtensionIs(path, extension)) { return true; @@ -21,7 +21,7 @@ namespace ts { return false; } - bool fileExtensionIsOneOf(const string &path, vector extensions) { + bool fileExtensionIsOneOf(const string &path, const vector &extensions) { return fileExtensionIsOneOf(path, charToStringVector(extensions)); } @@ -33,12 +33,12 @@ namespace ts { } //// Path Parsing - bool isVolumeCharacter(CharCode charCode) { + bool isVolumeCharacter(const CharCode &charCode) { return (charCode.code >= CharacterCodes::a && charCode.code <= CharacterCodes::z) || (charCode.code >= CharacterCodes::A && charCode.code <= CharacterCodes::Z); } - int getFileUrlVolumeSeparatorEnd(string url, int start) { + int getFileUrlVolumeSeparatorEnd(const string &url, int start) { auto ch0 = charCodeAt(url, start); if (ch0.code == CharacterCodes::colon) return start + 1; if (ch0.code == CharacterCodes::percent && charCodeAt(url, start + 1).code == CharacterCodes::_3) { @@ -52,7 +52,7 @@ namespace ts { * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). * If the root is part of a URL, the twos-complement of the root length is returned. */ - int getEncodedRootLength(string path) { + int getEncodedRootLength(const string &path) { if (path.empty()) return 0; auto ch0 = charCodeAt(path, 0); @@ -141,7 +141,7 @@ namespace ts { /** * Determines whether a charCode corresponds to `/` or `\`. */ - bool isAnyDirectorySeparator(CharCode charCode) { + bool isAnyDirectorySeparator(const CharCode &charCode) { return charCode.code == CharacterCodes::slash || charCode.code == CharacterCodes::backslash; } @@ -149,7 +149,7 @@ namespace ts { return path.size() > 0 && isAnyDirectorySeparator(charCodeAt(path, path.size() - 1)); } - string ensureTrailingDirectorySeparator(string path) { + string ensureTrailingDirectorySeparator(const string &path) { if (! hasTrailingDirectorySeparator(path)) { return path + directorySeparator; } @@ -175,21 +175,21 @@ namespace ts { * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" * ``` */ - string combinePaths(string path, vector paths) { + string combinePaths(string path, const vector &paths) { if (! path.empty()) path = normalizeSlashes(path); for (auto &relativePath: paths) { if (relativePath.empty()) continue; - relativePath = normalizeSlashes(relativePath); - if (path.empty() || getRootLength(relativePath) != 0) { - path = relativePath; + auto p = normalizeSlashes(relativePath); + if (path.empty() || getRootLength(p) != 0) { + path = p; } else { - path = ensureTrailingDirectorySeparator(path) + relativePath; + path = ensureTrailingDirectorySeparator(path) + p; } } return path; } - vector pathComponents(string path, int rootLength) { + vector pathComponents(const string &path, int rootLength) { auto root = path.substr(0, rootLength); auto rest = split(path.substr(rootLength), directorySeparator); if (rest.size() && ! lastOrUndefined(rest)) rest.pop_back(); @@ -227,9 +227,9 @@ namespace ts { * getPathComponents("file:///") === ["file:///"] * getPathComponents("file://") === ["file://"] */ - vector getPathComponents(string path, const string ¤tDirectory) { - path = combinePaths(currentDirectory, {path}); - return pathComponents(path, getRootLength(path)); + vector getPathComponents(const string &path, const string ¤tDirectory) { + auto p = combinePaths(currentDirectory, {path}); + return pathComponents(p, getRootLength(p)); } /** @@ -275,21 +275,23 @@ namespace ts { string normalizePath(string &_path) { string path = normalizeSlashes(_path); + //todo: rework that to make it faster + return path; // Most paths don't require normalization - if (! regex_search(path, relativePathSegmentRegExp)) { - return path; - } - // Some paths only require cleanup of `/./` or leading `./` - auto simplified = replaceLeading(replaceAll(path, "/./", "/"), "./", ""); - if (simplified != path) { - path = simplified; - if (! regex_search(path, relativePathSegmentRegExp)) { - return path; - } - } - // Other paths require full normalization - auto normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); - if (! normalized.empty() && hasTrailingDirectorySeparator(path)) return ensureTrailingDirectorySeparator(normalized); - return normalized; +// if (! regex_search(path, relativePathSegmentRegExp)) { +// return path; +// } +// // Some paths only require cleanup of `/./` or leading `./` +// auto simplified = replaceLeading(replaceAll(path, "/./", "/"), "./", ""); +// if (simplified != path) { +// path = simplified; +// if (! regex_search(path, relativePathSegmentRegExp)) { +// return path; +// } +// } +// // Other paths require full normalization +// auto normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); +// if (! normalized.empty() && hasTrailingDirectorySeparator(path)) return ensureTrailingDirectorySeparator(normalized); +// return normalized; } } diff --git a/src/path.h b/src/path.h index 0f14627..4b7c834 100644 --- a/src/path.h +++ b/src/path.h @@ -19,9 +19,9 @@ namespace ts { bool fileExtensionIs(const string &path, const string &extension); - bool fileExtensionIsOneOf(const string &path, vector extensions); + bool fileExtensionIsOneOf(const string &path, const vector &extensions); - bool fileExtensionIsOneOf(const string &path, vector extensions); + bool fileExtensionIsOneOf(const string &path, const vector &extensions); /** * Normalize path separators, converting `\` into `/`. @@ -29,15 +29,15 @@ namespace ts { string normalizeSlashes(const string &path); //// Path Parsing - bool isVolumeCharacter(CharCode charCode); + bool isVolumeCharacter(const CharCode &charCode); - int getFileUrlVolumeSeparatorEnd(string url, int start); + int getFileUrlVolumeSeparatorEnd(const string &url, int start); /** * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). * If the root is part of a URL, the twos-complement of the root length is returned. */ - int getEncodedRootLength(string path); + int getEncodedRootLength(const string &path); /** * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). @@ -69,11 +69,11 @@ namespace ts { /** * Determines whether a charCode corresponds to `/` or `\`. */ - bool isAnyDirectorySeparator(CharCode charCode); + bool isAnyDirectorySeparator(const CharCode &charCode); bool hasTrailingDirectorySeparator(const string &path); - string ensureTrailingDirectorySeparator(string path); + string ensureTrailingDirectorySeparator(const string &path); /** * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. @@ -93,9 +93,9 @@ namespace ts { * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" * ``` */ - string combinePaths(string path, vector paths); + string combinePaths(string path, const vector &paths); - vector pathComponents(string path, int rootLength); + vector pathComponents(const string &path, int rootLength); /** * Parse a path into an array containing a root component (at index 0) and zero or more path @@ -127,7 +127,7 @@ namespace ts { * getPathComponents("file:///") === ["file:///"] * getPathComponents("file://") === ["file://"] */ - vector getPathComponents(string path, const string ¤tDirectory = ""); + vector getPathComponents(const string &path, const string ¤tDirectory = ""); /** * Formats a parsed path consisting of a root component (at index 0) and zero or more path diff --git a/src/scanner.cpp b/src/scanner.cpp index d8301eb..6b992e1 100644 --- a/src/scanner.cpp +++ b/src/scanner.cpp @@ -19,7 +19,7 @@ namespace ts { return false; } - bool isWhiteSpaceSingleLine(CharCode ch) { + bool isWhiteSpaceSingleLine(const CharCode &ch) { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. return ch.code == CharacterCodes::space || @@ -43,25 +43,25 @@ namespace ts { auto start = pos; while (true) { if (pos >= end) { - result += substr(text, start, pos); + result += substring(text, start, pos); tokenFlags |= TokenFlags::Unterminated; // error(Diagnostics::Unterminated_string_literal); break; } auto ch = charCodeAt(text, pos); if (ch.code == quote.code) { - result += substr(text, start, pos); + result += substring(text, start, pos); pos++; break; } if (ch.code == CharacterCodes::backslash && !jsxAttributeString) { - result += substr(text, start, pos); + result += substring(text, start, pos); result += scanEscapeSequence(); start = pos; continue; } if (isLineBreak(ch) && !jsxAttributeString) { - result += substr(text, start, pos); + result += substring(text, start, pos); tokenFlags |= TokenFlags::Unterminated; // error(Diagnostics::Unterminated_string_literal); break; @@ -71,11 +71,11 @@ namespace ts { return result; } - bool isDigit(CharCode ch) { + bool isDigit(const CharCode &ch) { return ch.code >= CharacterCodes::_0 && ch.code <= CharacterCodes::_9; } - bool isHexDigit(CharCode ch) { + bool isHexDigit(const CharCode &ch) { return isDigit(ch) || (ch.code >= CharacterCodes::A && ch.code <= CharacterCodes::F) || (ch.code >= CharacterCodes::a && ch.code <= CharacterCodes::f); } @@ -113,7 +113,7 @@ namespace ts { break; } found++; - result.append(substr(text, pos, ch.length)); + result.append(substring(text, pos, ch.length)); pos++; isPreviousTokenSeparator = false; } @@ -125,7 +125,7 @@ namespace ts { return result; } - bool isCodePoint(CharCode ch) { + bool isCodePoint(const CharCode &ch) { return ch.code <= 0x10FFFF; } @@ -193,7 +193,7 @@ namespace ts { if (isTaggedTemplate && pos < end && isDigit(charCodeAt(text, pos))) { pos++; tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } return "\0"; case CharacterCodes::b: @@ -220,7 +220,7 @@ namespace ts { charCodeAt(text, escapePos).code != CharacterCodes::openBrace) { pos = escapePos; tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } } } @@ -231,7 +231,7 @@ namespace ts { // '\u{' if (isTaggedTemplate && !isHexDigit(charCodeAt(text, pos))) { tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } if (isTaggedTemplate) { @@ -244,13 +244,13 @@ namespace ts { // '\u{Not Code Point' or '\u{CodePoint' if (charCodeAt(text, pos).code != CharacterCodes::closeBrace) { tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } else { pos = savePos; } } catch (invalid_argument &error) { tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } } tokenFlags |= TokenFlags::ExtendedUnicodeEscape; @@ -265,11 +265,11 @@ namespace ts { if (isTaggedTemplate) { if (!isHexDigit(charCodeAt(text, pos))) { tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } else if (!isHexDigit(charCodeAt(text, pos + 1))) { pos++; tokenFlags |= TokenFlags::ContainsInvalidEscape; - return substr(text, start, pos); + return substring(text, start, pos); } } // '\xDD' @@ -301,7 +301,7 @@ namespace ts { while (true) { if (pos >= end) { - contents += substr(text, start, pos); + contents += substring(text, start, pos); tokenFlags |= TokenFlags::Unterminated; // error(Diagnostics::Unterminated_template_literal); resultingToken = startedWithBacktick ? SyntaxKind::NoSubstitutionTemplateLiteral : SyntaxKind::TemplateTail; @@ -312,7 +312,7 @@ namespace ts { // '`' if (currChar.code == CharacterCodes::backtick) { - contents += substr(text, start, pos); + contents += substring(text, start, pos); pos++; resultingToken = startedWithBacktick ? SyntaxKind::NoSubstitutionTemplateLiteral : SyntaxKind::TemplateTail; break; @@ -320,7 +320,7 @@ namespace ts { // '${' if (currChar.code == CharacterCodes::$ && pos + 1 < end && charCodeAt(text, pos + 1).code == CharacterCodes::openBrace) { - contents += substr(text, start, pos); + contents += substring(text, start, pos); pos += 2; resultingToken = startedWithBacktick ? SyntaxKind::TemplateHead : SyntaxKind::TemplateMiddle; break; @@ -328,7 +328,7 @@ namespace ts { // Escape character if (currChar.code == CharacterCodes::backslash) { - contents += substr(text, start, pos); + contents += substring(text, start, pos); contents += scanEscapeSequence(isTaggedTemplate); start = pos; continue; @@ -337,7 +337,7 @@ namespace ts { // Speculated ECMAScript 6 Spec 11.8.6.1: // and LineTerminatorSequences are normalized to for Template Values if (currChar.code == CharacterCodes::carriageReturn) { - contents += substr(text, start, pos); + contents += substring(text, start, pos); pos++; if (pos < end && charCodeAt(text, pos).code == CharacterCodes::lineFeed) { @@ -370,7 +370,7 @@ namespace ts { if (allowSeparator) { allowSeparator = false; isPreviousTokenSeparator = true; - result += substr(text, start, pos); + result += substring(text, start, pos); } else if (isPreviousTokenSeparator) { // error(Diagnostics::Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); } else { @@ -391,7 +391,7 @@ namespace ts { if (charCodeAt(text, pos - 1).code == CharacterCodes::_) { // error(Diagnostics::Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return result + substr(text, start, pos); + return result + substring(text, start, pos); } map textToKeyword{ @@ -588,20 +588,36 @@ namespace ts { lookupInUnicodeMap(code, unicodeES3IdentifierStart); } - bool isUnicodeIdentifierPart(CharCode ch, ScriptTarget languageVersion) { + bool isUnicodeIdentifierPart(const CharCode &ch, ScriptTarget languageVersion) { return languageVersion >= ScriptTarget::ES2015 ? lookupInUnicodeMap(ch, unicodeESNextIdentifierPart) : languageVersion == ScriptTarget::ES5 ? lookupInUnicodeMap(ch, unicodeES5IdentifierPart) : lookupInUnicodeMap(ch, unicodeES3IdentifierPart); } - bool isIdentifierStart(CharCode ch, ScriptTarget languageVersion) { + bool isIdentifierStart(const CharCode &ch, ScriptTarget languageVersion) { return (ch.code >= CharacterCodes::A && ch.code <= CharacterCodes::Z) || (ch.code >= CharacterCodes::a && ch.code <= CharacterCodes::z) || ch.code == CharacterCodes::$ || ch.code == CharacterCodes::_ || (ch.code > CharacterCodes::maxAsciiCharacter && isUnicodeIdentifierStart(ch, languageVersion)); } - bool isIdentifierPart(CharCode ch, ScriptTarget languageVersion, LanguageVariant identifierVariant = LanguageVariant::Standard) { + /* @internal */ + bool isIdentifierText(string name, ScriptTarget languageVersion, LanguageVariant identifierVariant) { + auto ch = charCodeAt(name, 0); + if (!isIdentifierStart(ch, languageVersion)) { + return false; + } + + for (int i = ch.length; i < name.size(); i += ch.length) { + if (!isIdentifierPart(ch = charCodeAt(name, i), languageVersion, identifierVariant)) { + return false; + } + } + + return true; + } + + bool isIdentifierPart(const CharCode &ch, ScriptTarget languageVersion, LanguageVariant identifierVariant) { return (ch.code >= CharacterCodes::A && ch.code <= CharacterCodes::Z) || (ch.code >= CharacterCodes::a && ch.code <= CharacterCodes::z) || (ch.code >= CharacterCodes::_0 && ch.code <= CharacterCodes::_9) || ch.code == CharacterCodes::$ || ch.code == CharacterCodes::_ || // "-" and ":" are valid in JSX Identifiers @@ -619,12 +635,13 @@ namespace ts { return pos; } - bool isWhiteSpaceLike(CharCode ch) { + bool isWhiteSpaceLike(const CharCode &ch) { return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); } /* @internal */ int ts::skipTrivia(string &text, int pos, optional stopAfterLineBreak, optional stopAtComments, optional inJSDoc) { + ZoneScoped; if (positionIsSynthesized(pos)) { return pos; } @@ -763,7 +780,7 @@ namespace ts { break; } tokenFlags |= TokenFlags::UnicodeEscape; - result += substr(text, start, pos); + result += substring(text, start, pos); result += fromCharCode(ch.code); // Valid Unicode escape is always six characters pos += 6; @@ -772,7 +789,7 @@ namespace ts { break; } } - result += substr(text, start, pos); + result += substring(text, start, pos); return result; } @@ -809,9 +826,9 @@ namespace ts { // not a bigint, so can convert to number in simplified form // Number() may not support 0b or 0o, so use parseInt() instead auto numericValue = tokenFlags & TokenFlags::BinarySpecifier - ? stoi(substr(tokenValue, 2), 0, 2) // skip "0b" + ? stoi(substring(tokenValue, 2), 0, 2) // skip "0b" : tokenFlags & TokenFlags::OctalSpecifier - ? stoi(substr(tokenValue, 2), 0, 8) // skip "0o" + ? stoi(substring(tokenValue, 2), 0, 8) // skip "0o" : stoi(tokenValue); tokenValue = "" + std::to_string(numericValue); return SyntaxKind::NumericLiteral; @@ -867,8 +884,8 @@ namespace ts { } } // Do not include a trailing namespace separator in the token, since this is against the spec. - if (substr(tokenValue, -1) == ":") { - tokenValue = substr(tokenValue, 0, -1); + if (substring(tokenValue, -1) == ":") { + tokenValue = substring(tokenValue, 0, -1); pos--; } return getIdentifierToken(); @@ -942,12 +959,12 @@ namespace ts { pos++; } - tokenValue = substr(text, startPos, pos); + tokenValue = substring(text, startPos, pos); return firstNonWhitespace == -1 ? SyntaxKind::JsxTextAllWhiteSpaces : SyntaxKind::JsxText; } - bool isLineBreak(CharCode ch) { + bool isLineBreak(const CharCode &ch) { // ES5 7.3: // The ECMAScript line terminator characters are listed in Table 3. // Table 3: Line Terminator Characters @@ -1002,7 +1019,7 @@ namespace ts { if (!finalFragment.size()) { // error(Diagnostics::Digit_expected); } else { - scientificFragment = substr(text, end, preNumericPart) + finalFragment; + scientificFragment = substring(text, end, preNumericPart) + finalFragment; scientificFragmentSet = true; end = pos; } @@ -1017,7 +1034,7 @@ namespace ts { result += scientificFragment; } } else { - result = substr(text, start, end); // No need to use all the fragments; no _ removal needed + result = substring(text, start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragmentSet || tokenFlags & TokenFlags::Scientific) { @@ -1091,7 +1108,7 @@ namespace ts { if (isIdentifierStart(ch, languageVersion)) { pos += ch.length; while (pos < end && isIdentifierPart(ch = charCodeAt(text, pos), languageVersion)) pos += ch.length; - tokenValue = substr(text, tokenPos, pos); + tokenValue = substring(text, tokenPos, pos); if (ch.code == CharacterCodes::backslash) { tokenValue += scanIdentifierParts(); } @@ -1276,7 +1293,7 @@ namespace ts { commentDirectives = appendIfCommentDirective( commentDirectives, - substr(text, tokenPos, pos), + substring(text, tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos ); @@ -1313,7 +1330,7 @@ namespace ts { } } - commentDirectives = appendIfCommentDirective(commentDirectives, substr(text, lastLineStart, pos), + commentDirectives = appendIfCommentDirective(commentDirectives, substring(text, lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { @@ -1576,7 +1593,7 @@ namespace ts { return SyntaxKind::EndOfFileToken; } - bool Scanner::isOctalDigit(CharCode ch) { + bool Scanner::isOctalDigit(const CharCode &ch) { return ch.code >= CharacterCodes::_0 && ch.code <= CharacterCodes::_7; } @@ -1585,40 +1602,7 @@ namespace ts { while (isOctalDigit(charCodeAt(text, pos))) { pos++; } - return stoi(substr(text, start, pos)); - } - - template - T Scanner::lookAhead(function callback) { - return speculationHelper(callback, /*isLookahead*/ true); - } - - template - T Scanner::tryScan(function callback) { - return speculationHelper(callback, /*isLookahead*/ false); - } - - template - T Scanner::speculationHelper(function callback, bool isLookahead) { - auto savePos = pos; - auto saveStartPos = startPos; - auto saveTokenPos = tokenPos; - auto saveToken = token; - auto saveTokenValue = tokenValue; - auto saveTokenFlags = tokenFlags; - auto result = callback(); - - // If our callback returned something 'falsy' or we're just looking ahead, - // then unconditionally restore us to where we were. - if (!result || isLookahead) { - pos = savePos; - startPos = saveStartPos; - tokenPos = saveTokenPos; - token = saveToken; - tokenValue = saveTokenValue; - tokenFlags = saveTokenFlags; - } - return result;; + return stoi(substring(text, start, pos)); } SyntaxKind Scanner::reScanJsxToken(bool allowMultilineJsxText) { @@ -1693,7 +1677,7 @@ namespace ts { p++; } pos = p; - tokenValue = substr(text, tokenPos, pos); + tokenValue = substring(text, tokenPos, pos); token = SyntaxKind::RegularExpressionLiteral; } return token; diff --git a/src/scanner.h b/src/scanner.h index 92e3870..ac28d56 100644 --- a/src/scanner.h +++ b/src/scanner.h @@ -1,5 +1,6 @@ #pragma once +#include "Tracy.hpp" #include #include #include @@ -356,19 +357,19 @@ namespace ts { return token == SyntaxKind::GreaterThanToken || tokenIsIdentifierOrKeyword(token); } - bool isUnicodeIdentifierPart(CharCode code, optional languageVersion = {}); + bool isUnicodeIdentifierPart(const CharCode &code, ScriptTarget languageVersion = ScriptTarget::Latest); - bool isIdentifierPart(CharCode ch, optional languageVersion = {}, optional identifierVariant = {}); + bool isIdentifierPart(const CharCode &ch, ScriptTarget languageVersion = ScriptTarget::Latest, LanguageVariant identifierVariant = LanguageVariant::Standard); /* @internal */ - bool isUnicodeIdentifierStart(CharCode code, optional languageVersion = {}); + bool isUnicodeIdentifierStart(CharCode code, ScriptTarget languageVersion = ScriptTarget::Latest); - bool isIdentifierStart(CharCode ch, optional languageVersion = {}); + bool isIdentifierStart(const CharCode &ch, ScriptTarget languageVersion = ScriptTarget::Latest); /* @internal */ - bool isIdentifierText(string name, optional languageVersion = {}, optional identifierVariant = {}); + bool isIdentifierText(string name, ScriptTarget languageVersion = ScriptTarget::Latest, LanguageVariant identifierVariant = LanguageVariant::Standard); - bool isLineBreak(CharCode ch); + bool isLineBreak(const CharCode &ch); class Scanner { public: @@ -477,13 +478,40 @@ namespace ts { } template - T lookAhead(function callback); + T lookAhead(const function &callback) { + ZoneScoped; + return speculationHelper(callback, /*isLookahead*/ true); + } template - T tryScan(function callback); + T tryScan(const function &callback) { + ZoneScoped; + return speculationHelper(callback, /*isLookahead*/ false); + } template - T speculationHelper(function callback, bool isLookahead); + T speculationHelper(const function &callback, bool isLookahead) { + ZoneScoped; + auto savePos = pos; + auto saveStartPos = startPos; + auto saveTokenPos = tokenPos; + auto saveToken = token; + auto saveTokenValue = tokenValue; + auto saveTokenFlags = tokenFlags; + auto result = callback(); + + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!(bool)result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result;; + } bool hasPrecedingLineBreak() { return (tokenFlags & TokenFlags::PrecedingLineBreak) != 0; @@ -518,7 +546,7 @@ namespace ts { SyntaxKind reScanJsxToken(bool allowMultilineJsxText = false); string getTokenText() { - return text.substr(tokenPos, pos); + return substring(text, tokenPos, pos); } SyntaxKind reScanLessThanToken() { @@ -591,7 +619,7 @@ namespace ts { string scanString(bool jsxAttributeString = false); - bool isOctalDigit(CharCode code); + bool isOctalDigit(const CharCode &code); int error(DiagnosticMessage message, int errPos = -1, int length = -1); diff --git a/src/tests/CmakeLists.txt b/src/tests/CmakeLists.txt index 6abb70c..529dd19 100644 --- a/src/tests/CmakeLists.txt +++ b/src/tests/CmakeLists.txt @@ -61,7 +61,10 @@ foreach(file ${TESTS}) get_filename_component(name ${file} NAME_WE) MESSAGE("Test found typescript_${name}.") add_executable(typescript_${name} ${file}) -# target_link_libraries(typescript_${name} gtest_main) + +# target_link_libraries(typescript_${name} PUBLIC Tracy::TracyClient) + + # target_link_libraries(typescript_${name} gtest_main) target_link_libraries(typescript_${name} gtest gtest_main typescript) # target_link_libraries(typescript_${name} PRIVATE Catch2::Catch2WithMain) # target_link_libraries(typescript_${name} PRIVATE typescript) diff --git a/src/tests/test_core.cpp b/src/tests/test_core.cpp index 13279bd..33aba8d 100644 --- a/src/tests/test_core.cpp +++ b/src/tests/test_core.cpp @@ -345,10 +345,32 @@ TEST(core, startsWith) { EXPECT_EQ(startsWith("this/is/a/path", "this/"), true); } -TEST(core, substrNegative) { +TEST(core, substr) { string a = "abc"; + EXPECT_EQ(substr(a, 0), "abc"); + EXPECT_EQ(substr(a, 1), "bc"); + EXPECT_EQ(substr(a, 0, 2), "ab"); + EXPECT_EQ(substr(a, 1, 0), ""); + EXPECT_EQ(substr(a, 1, 1), "b"); + EXPECT_EQ(substr(a, 1, 2), "bc"); + EXPECT_EQ(substr(a, 1, 3), "bc"); + EXPECT_EQ(substr(a, 1, 5), "bc"); EXPECT_EQ(substr(a, -1), "c"); - EXPECT_EQ(substr(a, 0, -1), "ab"); + EXPECT_EQ(substr(a, 0, -1), ""); +} + +TEST(core, substring) { + string a = "abc"; + EXPECT_EQ(substring(a, 0), "abc"); + EXPECT_EQ(substring(a, 1), "bc"); + EXPECT_EQ(substring(a, 0, 2), "ab"); + EXPECT_EQ(substring(a, 1, 2), "b"); + EXPECT_EQ(substring(a, 1, 3), "bc"); + EXPECT_EQ(substring(a, 1, 5), "bc"); + EXPECT_EQ(substring(a, -1), "abc"); + EXPECT_EQ(substring(a, 0, 0), ""); + EXPECT_EQ(substring(a, 0, -1), ""); + EXPECT_EQ(substring(a, 0, -2), ""); } TEST(core, regex) { @@ -371,6 +393,31 @@ T executeFn(function callback) { return callback(); } +class TestExec { +public: + bool callback() { + return true; + } + + bool executeFn(function callback) { + return callback(); + } + + bool doIt() { + return executeFn([this]{ return callback(); }); + } +}; + +TEST(core, stringView) { + std::string_view s = "abcdefgh"; + +} + TEST(core, passFn) { - auto a = executeFn(test); -} \ No newline at end of file + TestExec test; + + test.doIt(); + +// +// auto a = executeFn([]{ return test(); }); +} diff --git a/src/tests/test_parser.cpp b/src/tests/test_parser.cpp index d1f1ef4..9c4c9ce 100644 --- a/src/tests/test_parser.cpp +++ b/src/tests/test_parser.cpp @@ -1,11 +1,33 @@ #include +#include #include "../parser2.h" using namespace ts; -TEST(parser, basisc) { -// Parser parser("test.ts", "const i = 123;"); -// -// parser.parse(); +TEST(parser, bench) { + Parser parser; + + string code = "const i = 123;"; + /** +ConstKeyword +WhitespaceTrivia +Identifier +WhitespaceTrivia +EqualsToken +WhitespaceTrivia +NumericLiteral +SemicolonToken +EndOfFileToken + */ + + auto start = std::chrono::high_resolution_clock::now(); + + auto i = 0; + for (i = 0; i <10000; i++) { + auto result = parser.parseSourceFile("app.ts", code, ts::types::ScriptTarget::Latest, false, ScriptKind::TS, {}); +// auto sourceFile = parser.createSourceFile("app.ts", ts::types::ScriptTarget::Latest, ScriptKind::TS, false, make_shared(), make_shared(), 0, [](auto s) {}); + } + std::chrono::duration took = std::chrono::high_resolution_clock::now() - start; + debug("parse %d took %fms", i, took.count()); } \ No newline at end of file diff --git a/src/tests/test_scanner.cpp b/src/tests/test_scanner.cpp index bdc26a4..297f10c 100644 --- a/src/tests/test_scanner.cpp +++ b/src/tests/test_scanner.cpp @@ -9,15 +9,35 @@ using namespace ts; using namespace magic_enum; TEST(scanner, basisc) { + + auto start = std::chrono::high_resolution_clock::now(); Scanner scanner("const i = 123;"); - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; - std::cout << enum_name(scanner.scan()) << "\n"; + auto i = 0; + for (i = 0; i <10000; i++) { + scanner.setText("const i = 123"); +// scanner.setOnError([this](auto ...a) { scanError(a...); }); + scanner.setScriptTarget(ts::types::ScriptTarget::Latest); + scanner.setLanguageVariant(ts::types::LanguageVariant::Standard); + + while (scanner.scan() != ts::types::SyntaxKind::EndOfFileToken) { + + } + + scanner.clearCommentDirectives(); + scanner.setText(""); + scanner.setOnError(nullopt); + } + std::chrono::duration took = std::chrono::high_resolution_clock::now() - start; + debug("scan %d took %fms", i, took.count()); + +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; +// std::cout << enum_name(scanner.scan()) << "\n"; } \ No newline at end of file diff --git a/src/types.h b/src/types.h index eae9814..8bc56c3 100644 --- a/src/types.h +++ b/src/types.h @@ -1209,15 +1209,15 @@ namespace ts { }; template - bool some(optional array, function)> callback) { + bool some(sharedOpt array, function)> callback) { if (!array) return false; for (auto &item: array->list) { - if (callback(dynamic_pointer_cast(item))) return true; + if (callback(reinterpret_pointer_cast(item))) return true; } return false; } - inline bool some(optional array) { + inline bool some(sharedOpt array) { return array && !array->empty(); } @@ -1287,8 +1287,8 @@ namespace ts { constexpr static auto KIND = SyntaxKind::Unknown; /* types::NodeFlags */ int flags; /* @internal */ /* types::ModifierFlags */ int modifierFlagsCache; - optional modifiers; // Array of modifiers - optional decorators; // Array of decorators (in document order) + sharedOpt modifiers; // Array of modifiers + sharedOpt decorators; // Array of decorators (in document order) /* @internal */ /* types::TransformFlags */ int transformFlags; // Flags for transforms // /* @internal */ id?: NodeId; // Unique id (used to look up NodeLinks) /* @internal */ sharedOpt original; // The original BaseNode if this is an updated node. @@ -1350,7 +1350,7 @@ namespace ts { return b; }; - inline bool operator==(optional a, optional b) { + inline bool operator==(sharedOpt a, sharedOpt b) { if (!a && !b) return true; if (!a || !b) return false; return *a == *b; @@ -1567,7 +1567,7 @@ namespace ts { /*@internal*/ optional autoGenerateFlags; // Specifies whether to auto-generate the text for an identifier. /*@internal*/ optional autoGenerateId; // Ensures unique generated identifiers get unique names, but clones get the same name. /*@internal*/ sharedOpt generatedImportReference; // Reference to the generated import specifier this identifier refers to - /*@internal*/ optional typeArguments; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help. + /*@internal*/ sharedOpt typeArguments; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help. }; enum class FlowFlags { @@ -1590,7 +1590,7 @@ namespace ts { }; struct Block: BrandKind { - NodeTypeArray(Statement) statements; + shared statements; /*@internal*/ bool multiLine; }; @@ -1657,13 +1657,13 @@ namespace ts { #define ArrayBindingElement BindingElement, OmittedExpression struct ObjectBindingPattern: BrandKind { - NodeTypeArray(BindingElement) elements; + shared elements; ParentProperty(VariableDeclaration, ParameterDeclaration, BindingElement); }; struct ArrayBindingPattern: BrandKind { ParentProperty(VariableDeclaration, ParameterDeclaration, BindingElement); - NodeTypeArray(ArrayBindingElement) elements; + shared elements; }; struct ExpressionStatement: BrandKind { @@ -1719,7 +1719,7 @@ namespace ts { struct CaseBlock: BrandKind { shared parent; - NodeTypeArray(CaseClause, DefaultClause) clauses; + shared clauses; }; struct SwitchStatement: BrandKind { @@ -1731,12 +1731,12 @@ namespace ts { struct CaseClause: BrandKind { Property(parent, CaseBlock); Property(expression, Expression); - NodeTypeArray(Statement) statements; + shared statements; }; struct DefaultClause: BrandKind { shared parent; - NodeTypeArray(Statement) statements; + shared statements; }; // export type CaseOrDefaultClause = @@ -1790,11 +1790,11 @@ namespace ts { struct VariableDeclarationList: BrandKind { ParentProperty(VariableStatement, ForStatement, ForOfStatement, ForInStatement); - NodeTypeArray(VariableDeclaration) declarations; + shared declarations; }; struct VariableStatement: BrandKind { -// /* @internal*/ optional decorators; // Present for use with reporting a grammar error +// /* @internal*/ sharedOpt decorators; // Present for use with reporting a grammar error Property(declarationList, VariableDeclarationList); }; @@ -1866,7 +1866,7 @@ namespace ts { }; struct TypeLiteralNode: BrandKind { - NodeTypeArray(TypeElement) members; + shared members; }; #define ClassLikeDeclaration ClassDeclaration, ClassExpression @@ -1922,10 +1922,10 @@ namespace ts { struct SignatureDeclarationBase: NamedDeclaration { OptionalUnionProperty(name, PropertyName); - optional typeParameters; - NodeTypeArray(ParameterDeclaration) parameters; + sharedOpt typeParameters; + shared parameters; OptionalProperty(type, TypeNode); - optional typeArguments; + sharedOpt typeArguments; }; struct PropertyAssignment: BrandKind { @@ -1957,14 +1957,14 @@ namespace ts { struct ClassLikeDeclarationBase { OptionalProperty(name, Identifier); - optional typeParameters; - optional heritageClauses; - NodeTypeArray(ClassElement) members; + sharedOpt typeParameters; + sharedOpt heritageClauses; + shared members; }; struct DeclarationStatement: Statement { -// optional decorators; // Array of decorators (in document order) -// optional modifiers; // Array of modifiers +// sharedOpt decorators; // Array of decorators (in document order) +// sharedOpt modifiers; // Array of modifiers OptionalUnionProperty(name, Identifier, StringLiteral, NumericLiteral); }; @@ -1973,7 +1973,7 @@ namespace ts { struct DebuggerStatement: BrandKind {}; struct CommaListExpression: BrandKind { - NodeTypeArray(Expression) elements; + shared elements; }; struct MissingDeclaration: BrandKind { @@ -1981,27 +1981,27 @@ namespace ts { }; struct ClassDeclaration: BrandKind { -// optional decorators; // Array of decorators (in document order) -// optional modifiers; // Array of modifiers +// sharedOpt decorators; // Array of decorators (in document order) +// sharedOpt modifiers; // Array of modifiers OptionalProperty(name, Identifier); }; struct ClassExpression: BrandKind { - optional decorators; // Array of decorators (in document order) - optional modifiers; // Array of modifiers + sharedOpt decorators; // Array of decorators (in document order) + sharedOpt modifiers; // Array of modifiers }; struct HeritageClause; struct InterfaceDeclaration: BrandKind { Property(name, Identifier); - optional typeParameters; - optional heritageClauses; - NodeTypeArray(TypeElement) members; + sharedOpt typeParameters; + sharedOpt heritageClauses; + shared members; }; struct NodeWithTypeArguments { - optional typeArguments; + sharedOpt typeArguments; }; struct ExpressionWithTypeArguments: BrandKind { @@ -2011,12 +2011,12 @@ namespace ts { struct HeritageClause: BrandKind { ParentProperty(InterfaceDeclaration, ClassLikeDeclaration); SyntaxKind token; //SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword - NodeTypeArray(ExpressionWithTypeArguments) types; + shared types; }; struct TypeAliasDeclaration: BrandKind { Property(name, Identifier); - optional typeParameters; + sharedOpt typeParameters; Property(type, TypeNode); }; @@ -2024,7 +2024,7 @@ namespace ts { struct EnumDeclaration: BrandKind { Property(name, Identifier); - NodeTypeArray(EnumMember) members; + shared members; }; struct EnumMember: BrandKind { @@ -2067,7 +2067,7 @@ namespace ts { struct ModuleBlock: BrandKind { shared parent; - NodeTypeArray(Statement) statements; + shared statements; }; struct NamespaceDeclaration: BrandKind { @@ -2118,7 +2118,7 @@ namespace ts { struct NamedImports: BrandKind { shared parent; - NodeTypeArray(ImportSpecifier) elements; + shared elements; }; #define NamedImportBindings NamespaceImport, NamedImports @@ -2136,7 +2136,7 @@ namespace ts { struct ExportDeclaration; struct AssertClause: BrandKind { ParentProperty(ImportDeclaration, ExportDeclaration); - NodeTypeArray(AssertEntry) elements; + shared elements; bool multiLine; }; @@ -2180,12 +2180,12 @@ namespace ts { struct NamedExports: BrandKind { shared parent; - NodeTypeArray(ExportSpecifier) elements; + shared elements; }; struct NamespaceExportDeclaration: BrandKind { Property(name, Identifier); - /* @internal */ optional decorators; // Present for use with reporting a grammar error + /* @internal */ sharedOpt decorators; // Present for use with reporting a grammar error /* @internal */ OptionalProperty(modifiers, ModifiersArray); // Present for use with reporting a grammar error }; @@ -2255,8 +2255,8 @@ namespace ts { struct IndexSignatureDeclaration: BrandKind { using TypeElement::name; shared parent; -// optional decorators; // Array of decorators (in document order) -// optional modifiers; // Array of modifiers +// sharedOpt decorators; // Array of decorators (in document order) +// sharedOpt modifiers; // Array of modifiers Property(type, TypeNode); }; @@ -2296,7 +2296,7 @@ namespace ts { shared parent; OptionalProperty(body, FunctionBody); - /* @internal */ optional typeParameters; // Present for use with reporting a grammar error + /* @internal */ sharedOpt typeParameters; // Present for use with reporting a grammar error /* @internal */ OptionalProperty(type, TypeNode); // Present for use with reporting a grammar error }; @@ -2308,7 +2308,7 @@ namespace ts { ParentProperty(ClassLikeDeclaration, ObjectLiteralExpression, TypeLiteralNode, InterfaceDeclaration); UnionProperty(name, PropertyName); OptionalProperty(body, FunctionBody); - /* @internal */ optional typeParameters; // Present for use with reporting a grammar error + /* @internal */ sharedOpt typeParameters; // Present for use with reporting a grammar error }; // See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a @@ -2317,7 +2317,7 @@ namespace ts { ParentProperty(ClassLikeDeclaration, ObjectLiteralExpression, TypeLiteralNode, InterfaceDeclaration); UnionProperty(name, PropertyName); OptionalUnionProperty(body, FunctionBody); - /* @internal */ optional typeParameters; // Present for use with reporting a grammar error + /* @internal */ sharedOpt typeParameters; // Present for use with reporting a grammar error /* @internal */ OptionalProperty(type, TypeNode); // Present for use with reporting a grammar error }; @@ -2327,7 +2327,7 @@ namespace ts { template struct ObjectLiteralExpressionBase: PrimaryExpression { - NodeTypeArray(T) properties; + shared properties; }; struct ObjectLiteralExpression: BrandKind> { @@ -2432,7 +2432,7 @@ namespace ts { }; struct ArrayLiteralExpression: BrandKind { - NodeTypeArray(Expression) elements; + shared elements; /* @internal */ bool multiLine; //optional }; @@ -2445,8 +2445,8 @@ namespace ts { struct CallExpression: BrandKind { Property(expression, LeftHandSideExpression); OptionalProperty(questionDotToken, QuestionDotToken); - optional typeArguments; - NodeTypeArray(Expression) arguments; + sharedOpt typeArguments; + shared arguments; }; using CallChain = CallExpression; @@ -2457,8 +2457,8 @@ namespace ts { struct NewExpression: BrandKind { Property(expression, LeftHandSideExpression); - optional typeArguments; - optional arguments; + sharedOpt typeArguments; + sharedOpt arguments; }; struct TypeAssertion: BrandKind { @@ -2497,19 +2497,19 @@ namespace ts { struct TemplateLiteralTypeNode: BrandKind { Property(head, TemplateHead); - NodeTypeArray(TemplateLiteralTypeSpan) templateSpans; + shared templateSpans; }; struct TemplateExpression: BrandKind { Property(head, TemplateHead); - NodeTypeArray(TemplateSpan) templateSpans; + shared templateSpans; }; #define TemplateLiteral TemplateExpression, NoSubstitutionTemplateLiteral struct TaggedTemplateExpression: BrandKind { Property(tag, LeftHandSideExpression); - optional typeArguments; + sharedOpt typeArguments; UnionProperty(templateLiteral, TemplateLiteral); /*@internal*/ OptionalProperty(questionDotToken, QuestionDotToken); // NOTE: Invalid syntax, only used to report a grammar error. }; @@ -2564,11 +2564,11 @@ namespace ts { }; struct UnionTypeNode: BrandKind { - NodeTypeArray(TypeNode) types; + shared types; }; struct IntersectionTypeNode: BrandKind { - NodeTypeArray(TypeNode) types; + shared types; }; #define UnionOrIntersectionTypeNode UnionTypeNode, IntersectionTypeNode @@ -2610,7 +2610,7 @@ namespace ts { OptionalUnionProperty(questionToken, QuestionToken, PlusToken, MinusToken); OptionalProperty(type, TypeNode); /** Used only to produce grammar errors */ - optional members; + sharedOpt members; }; #define JsxChild JsxText, JsxExpression, JsxElement, JsxSelfClosingElement, JsxFragment @@ -2647,14 +2647,14 @@ namespace ts { struct JsxAttributes: BrandKind { OptionalUnionProperty(parent, JsxOpeningLikeElement); - NodeTypeArray(JsxAttributeLike) properties; + shared properties; }; // The opening element of a ... JsxElement struct JsxOpeningElement: BrandKind { shared parent; UnionProperty(tagName, JsxTagNameExpression); - optional typeArguments; + sharedOpt typeArguments; Property(attributes, JsxAttributes); }; @@ -2671,7 +2671,7 @@ namespace ts { /// A JSX expression of the form ... struct JsxElement: BrandKind { Property(openingElement, JsxOpeningElement); - NodeTypeArray(JsxChild) children; + shared children; Property(closingElement, JsxClosingElement); }; @@ -2683,7 +2683,7 @@ namespace ts { // A JSX expression of the form struct JsxSelfClosingElement: BrandKind { UnionProperty(tagName, JsxTagNameExpression); - optional typeArguments; + sharedOpt typeArguments; Property(attributes, JsxAttributes); }; @@ -2701,7 +2701,7 @@ namespace ts { /// A JSX expression of the form <>... struct JsxFragment: BrandKind { Property(openingFragment, JsxOpeningFragment); - NodeTypeArray(JsxChild) children; + shared children; Property(closingFragment, JsxClosingFragment); }; @@ -2715,7 +2715,7 @@ namespace ts { }; struct TupleTypeNode: BrandKind { - NodeTypeArray(TypeNode, NamedTupleMember) elements; + shared elements; }; // using AccessibilityModifier = NodeType; @@ -2731,11 +2731,128 @@ namespace ts { struct SourceFile: BrandKind { string fileName; - NodeTypeArray(Statement) statements; + string text; + + shared statements; Property(endOfFileToken, EndOfFileToken); - optional impliedNodeFormat; + /* @internal */ string path; + /** Resolved path can be different from path property, + * when file is included through project reference is mapped to its output instead of source + * in that case resolvedPath = path to output file + * path = input file's path + */ + /* @internal */ string resolvedPath; + + /** Original file name that can be different from fileName, + * when file is included through project reference is mapped to its output instead of source + * in that case originalFileName = name of input file + * fileName = output file's name + */ + /* @internal */ string originalFileName; + +// amdDependencies: readonly AmdDependency[]; + optional moduleName; +// referencedFiles: readonly FileReference[]; +// typeReferenceDirectives: readonly FileReference[]; +// libReferenceDirectives: readonly FileReference[]; + types::LanguageVariant languageVariant; + bool isDeclarationFile; +// +// // this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling) +// /* @internal */ +// renamedDependencies?: ReadonlyESMap; +// + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + bool hasNoDefaultLib; + + types::ScriptTarget languageVersion; + + /** + * When `module` is `Node16` or `NodeNext`, this field controls whether the + * source file in question is an ESNext-output-format file, or a CommonJS-output-format + * module. This is derived by the module resolver as it looks up the file, since + * it is derived from either the file extension of the module, or the containing + * `package.json` context, and affects both checking and emit. + * + * It is _public_ so that (pre)transformers can set this field, + * since it switches the builtin `node` module transform. Generally speaking, if unset, + * the field is treated as though it is `ModuleKind.CommonJS`. + */ + optional impliedNodeFormat; //?: ModuleKind.ESNext | ModuleKind.CommonJS; + + /* @internal */ types::ScriptKind scriptKind; + + /** + * The first "most obvious" node that makes a file an external module. + * This is intended to be the first top-level import/export, + * but could be arbitrarily nested (e.g. `import.meta`). + */ + /* @internal */ sharedOpt externalModuleIndicator; //?: Node | true; + + /** + * The callback used to set the external module indicator - this is saved to + * be later reused during incremental reparsing, which otherwise lacks the information + * to set this field + */ + /* @internal */ optional)>> setExternalModuleIndicator; //?: (file: SourceFile) => void; +// // The first node that causes this file to be a CommonJS module +// /* @internal */ commonJsModuleIndicator?: Node; +// // JS identifier-declarations that are intended to merge with globals +// /* @internal */ jsGlobalAugmentations?: SymbolTable; +// +// /* @internal */ identifiers: ESMap; // Map from a string to an interned string +// /* @internal */ nodeCount: number; +// /* @internal */ identifierCount: number; +// /* @internal */ symbolCount: number; +// +// // File-level diagnostics reported by the parser (includes diagnostics about /// references +// // as well as code diagnostics). +// /* @internal */ parseDiagnostics: DiagnosticWithLocation[]; +// +// // File-level diagnostics reported by the binder. +// /* @internal */ bindDiagnostics: DiagnosticWithLocation[]; +// /* @internal */ bindSuggestionDiagnostics?: DiagnosticWithLocation[]; +// +// // File-level JSDoc diagnostics reported by the JSDoc parser +// /* @internal */ jsDocDiagnostics?: DiagnosticWithLocation[]; +// +// // Stores additional file-level diagnostics reported by the program +// /* @internal */ additionalSyntacticDiagnostics?: readonly DiagnosticWithLocation[]; +// +// // Stores a line map for the file. +// // This field should never be used directly to obtain line map, use getLineMap function instead. +// /* @internal */ lineMap: readonly number[]; +// /* @internal */ classifiableNames?: ReadonlySet<__String>; +// // Comments containing @ts-* directives, in order. +// /* @internal */ commentDirectives?: CommentDirective[]; +// // Stores a mapping 'external module reference text' -> 'resolved file name' | undefined +// // It is used to resolve module names in the checker. +// // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead +// /* @internal */ resolvedModules?: ModeAwareCache; +// /* @internal */ resolvedTypeReferenceDirectiveNames: ModeAwareCache; +// /* @internal */ imports: readonly StringLiteralLike[]; +// // Identifier only if `declare global` +// /* @internal */ moduleAugmentations: readonly (StringLiteral | Identifier)[]; +// /* @internal */ patternAmbientModules?: PatternAmbientModule[]; +// /* @internal */ ambientModuleNames: readonly string[]; +// /* @internal */ checkJsDirective?: CheckJsDirective; +// /* @internal */ version: string; +// /* @internal */ pragmas: ReadonlyPragmaMap; +// /* @internal */ localJsxNamespace?: __String; +// /* @internal */ localJsxFragmentNamespace?: __String; +// /* @internal */ localJsxFactory?: EntityName; +// /* @internal */ localJsxFragmentFactory?: EntityName; +// +// /* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit; +// /* @internal */ endFlowNode?: FlowNode; - sharedOpt externalModuleIndicator; }; } \ No newline at end of file diff --git a/src/utilities.cpp b/src/utilities.cpp index 75f56c4..5f54441 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -1,15 +1,17 @@ #pragma once +#include "Tracy.hpp" +#include "types.h" #include "utilities.h" #include "core.h" namespace ts { - static LanguageVariant getLanguageVariant(ScriptKind scriptKind) { + LanguageVariant getLanguageVariant(ScriptKind scriptKind) { // .tsx and .jsx files are treated as jsx language variant. return scriptKind == ScriptKind::TSX || scriptKind == ScriptKind::JSX || scriptKind == ScriptKind::JS || scriptKind == ScriptKind::JSON ? LanguageVariant::JSX : LanguageVariant::Standard; } - sharedOpt lastOrUndefined(optional array) { + sharedOpt lastOrUndefined(sharedOpt array) { if (!array) return nullptr; auto last = lastOrUndefined(array->list); if (last) *last; @@ -426,6 +428,7 @@ namespace ts { } shared skipPartiallyEmittedExpressions(shared node) { + ZoneScoped; return skipOuterExpressions(node, (int) OuterExpressionKinds::PartiallyEmittedExpressions); } @@ -610,6 +613,7 @@ namespace ts { } bool isLeftHandSideExpression(shared node) { + ZoneScoped; return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node)->kind); } diff --git a/src/utilities.h b/src/utilities.h index be9f22a..fb5998c 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -23,9 +23,9 @@ namespace ts { using types::DiagnosticCategory; using types::DiagnosticWithDetachedLocation; - static vector supportedDeclarationExtensions{Extension::Dts, Extension::Dcts, Extension::Dmts}; + inline vector supportedDeclarationExtensions{Extension::Dts, Extension::Dcts, Extension::Dmts}; - static LanguageVariant getLanguageVariant(ScriptKind scriptKind); + extern LanguageVariant getLanguageVariant(ScriptKind scriptKind); /* @internal */ template @@ -35,7 +35,12 @@ namespace ts { return range; } - sharedOpt lastOrUndefined(optional array); + template + T setTextRange(T range, T2 location) { + return location ? setTextRangePosEnd(range, location->pos, location->end) : range; + } + + sharedOpt lastOrUndefined(sharedOpt array); NodeArray &setTextRangePosEnd(NodeArray &range, int pos, int end); @@ -57,11 +62,6 @@ namespace ts { bool nodeIsSynthesized(shared range); - template - T setTextRange(T range, sharedOpt location) { - return location ? setTextRangePosEnd(range, location->pos, location->end) : range; - } - NodeArray setTextRange(NodeArray range, optional location); string parsePseudoBigInt(string &stringValue);