Partial migration of utilities.ts, data property dispatch

This commit is contained in:
Ron Buckton 2024-10-02 18:35:44 -04:00
Родитель 6418f9c991
Коммит 29d90a6d04
Не найден ключ, соответствующий данной подписи
31 изменённых файлов: 6137 добавлений и 1630 удалений

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -757,13 +757,13 @@ const astForEachChildTable: AstForEachChildTable = {
visitNode(cbNode, node.data.type);
},
[SyntaxKind.JSDoc]: function forEachChildInJSDoc<T>(node: AstJSDoc, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return (typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment))
return visitNodes(cbNode, cbNodes, node.data.commentArray)
|| visitNodes(cbNode, cbNodes, node.data.tags);
},
[SyntaxKind.JSDocSeeTag]: function forEachChildInJSDocSeeTag<T>(node: AstJSDocSeeTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.name) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocNameReference]: function forEachChildInJSDocNameReference<T>(node: AstJSDocNameReference, cbNode: (node: AstNode) => T | undefined, _cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.name);
@ -776,23 +776,23 @@ const astForEachChildTable: AstForEachChildTable = {
[SyntaxKind.JSDocPropertyTag]: forEachChildInJSDocParameterOrPropertyTag,
[SyntaxKind.JSDocAuthorTag]: function forEachChildInJSDocAuthorTag<T>(node: AstJSDocAuthorTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocImplementsTag]: function forEachChildInJSDocImplementsTag<T>(node: AstJSDocImplementsTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.class) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocAugmentsTag]: function forEachChildInJSDocAugmentsTag<T>(node: AstJSDocAugmentsTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.class) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocTemplateTag]: function forEachChildInJSDocTemplateTag<T>(node: AstJSDocTemplateTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.constraint) ||
visitNodes(cbNode, cbNodes, node.data.typeParameters) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocTypedefTag]: function forEachChildInJSDocTypedefTag<T>(node: AstJSDocTypedefTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
@ -800,16 +800,16 @@ const astForEachChildTable: AstForEachChildTable = {
node.data.typeExpression.kind === SyntaxKind.JSDocTypeExpression
? visitNode(cbNode, node.data.typeExpression) ||
visitNode(cbNode, node.data.fullName) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment))
visitNodes(cbNode, cbNodes, node.data.commentArray)
: visitNode(cbNode, node.data.fullName) ||
visitNode(cbNode, node.data.typeExpression) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment)));
visitNodes(cbNode, cbNodes, node.data.commentArray));
},
[SyntaxKind.JSDocCallbackTag]: function forEachChildInJSDocCallbackTag<T>(node: AstJSDocCallbackTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.fullName) ||
visitNode(cbNode, node.data.typeExpression) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
},
[SyntaxKind.JSDocReturnTag]: forEachChildInJSDocTypeLikeTag,
[SyntaxKind.JSDocTypeTag]: forEachChildInJSDocTypeLikeTag,
@ -901,13 +901,13 @@ function forEachChildInJSDocParameterOrPropertyTag<T>(node: AstJSDocParameterTag
(node.data.isNameFirst
? visitNode(cbNode, node.data.name) || visitNode(cbNode, node.data.typeExpression)
: visitNode(cbNode, node.data.typeExpression) || visitNode(cbNode, node.data.name)) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
}
function forEachChildInJSDocTypeLikeTag<T>(node: AstJSDocReturnTag | AstJSDocTypeTag | AstJSDocThisTag | AstJSDocEnumTag | AstJSDocThrowsTag | AstJSDocOverloadTag | AstJSDocSatisfiesTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName) ||
visitNode(cbNode, node.data.typeExpression) ||
(typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
visitNodes(cbNode, cbNodes, node.data.commentArray);
}
function forEachChildInJSDocLinkCodeOrPlain<T>(node: AstJSDocLink | AstJSDocLinkCode | AstJSDocLinkPlain, cbNode: (node: AstNode) => T | undefined, _cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
@ -916,7 +916,7 @@ function forEachChildInJSDocLinkCodeOrPlain<T>(node: AstJSDocLink | AstJSDocLink
function forEachChildInJSDocTag<T>(node: AstJSDocUnknownTag | AstJSDocClassTag | AstJSDocPublicTag | AstJSDocPrivateTag | AstJSDocProtectedTag | AstJSDocReadonlyTag | AstJSDocDeprecatedTag | AstJSDocOverrideTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
return visitNode(cbNode, node.data.tagName)
|| (typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
|| visitNodes(cbNode, cbNodes, node.data.commentArray);
}
function forEachChildInJSDocImportTag<T>(node: AstJSDocImportTag, cbNode: (node: AstNode) => T | undefined, cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {
@ -924,7 +924,7 @@ function forEachChildInJSDocImportTag<T>(node: AstJSDocImportTag, cbNode: (node:
|| visitNode(cbNode, node.data.importClause)
|| visitNode(cbNode, node.data.moduleSpecifier)
|| visitNode(cbNode, node.data.attributes)
|| (typeof node.data.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.data.comment));
|| visitNodes(cbNode, cbNodes, node.data.commentArray);
}
function forEachChildInPartiallyEmittedExpression<T>(node: AstPartiallyEmittedExpression, cbNode: (node: AstNode) => T | undefined, _cbNodes?: (nodes: AstNodeArray<AstNode>) => T | undefined): T | undefined {

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1134,6 +1134,7 @@ import {
hasName,
canHaveQuestionToken,
hasAsteriskToken,
AstDeclaration,
} from "./_namespaces/ts.js";
import * as moduleSpecifiers from "./_namespaces/ts.moduleSpecifiers.js";
import * as performance from "./_namespaces/ts.performance.js";
@ -1539,11 +1540,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
var globals = createSymbolTable();
var undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined" as __String);
undefinedSymbol.declarations = [];
undefinedSymbol.astDeclarations = [];
var globalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis" as __String, CheckFlags.Readonly);
globalThisSymbol.exports = globals;
globalThisSymbol.declarations = [];
globalThisSymbol.astDeclarations = [];
globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments" as __String);
@ -2545,8 +2546,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return diagnostic;
}
function addDeprecatedSuggestionWorker(declarations: Node | Node[], diagnostic: DiagnosticWithLocation) {
const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations);
function addDeprecatedSuggestionWorker(declarations: Node | readonly Node[], diagnostic: DiagnosticWithLocation) {
const deprecatedTag = isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations);
if (deprecatedTag) {
addRelatedInfo(
diagnostic,
@ -2571,7 +2572,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return !!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Deprecated);
}
function addDeprecatedSuggestion(location: Node, declarations: Node[], deprecatedEntity: string) {
function addDeprecatedSuggestion(location: Node, declarations: readonly Node[], deprecatedEntity: string) {
const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity);
return addDeprecatedSuggestionWorker(declarations, diagnostic);
}
@ -2634,9 +2635,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function cloneSymbol(symbol: Symbol): TransientSymbol {
const result = createSymbol(symbol.flags, symbol.escapedName);
result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
result.astDeclarations = symbol.astDeclarations ? symbol.astDeclarations.slice() : [];
result.parent = symbol.parent;
if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
if (symbol.astValueDeclaration) result.astValueDeclaration = symbol.astValueDeclaration;
if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
if (symbol.members) result.members = new Map(symbol.members);
if (symbol.exports) result.exports = new Map(symbol.exports);
@ -2683,7 +2684,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (source.valueDeclaration) {
setValueDeclaration(target, source.valueDeclaration);
}
addRange(target.declarations, source.declarations);
addRange(target.astDeclarations, source.astDeclarations);
if (source.members) {
if (!target.members) target.members = createSymbolTable();
mergeSymbolTable(target.members, source.members, unidirectional);
@ -3906,9 +3907,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
Debug.assert(valueSymbol.declarations || typeSymbol.declarations);
result.declarations = deduplicate(concatenate(valueSymbol.declarations!, typeSymbol.declarations), equateValues);
result.astDeclarations = deduplicate(concatenate(valueSymbol.astDeclarations!, typeSymbol.astDeclarations), equateValues);
result.parent = valueSymbol.parent || typeSymbol.parent;
if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration;
if (valueSymbol.astValueDeclaration) result.astValueDeclaration = valueSymbol.astValueDeclaration;
if (typeSymbol.members) result.members = new Map(typeSymbol.members);
if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports);
return result;
@ -4964,11 +4965,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
*/
function cloneTypeAsModuleType(symbol: Symbol, moduleType: Type, referenceParent: ImportDeclaration | ImportCall) {
const result = createSymbol(symbol.flags, symbol.escapedName);
result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
result.astDeclarations = symbol.astDeclarations ? symbol.astDeclarations.slice() : [];
result.parent = symbol.parent;
result.links.target = symbol;
result.links.originatingImport = referenceParent;
if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
if (symbol.astValueDeclaration) result.astValueDeclaration = symbol.astValueDeclaration;
if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
if (symbol.members) result.members = new Map(symbol.members);
if (symbol.exports) result.exports = new Map(symbol.exports);
@ -9727,7 +9728,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
);
}
function getSomeTargetNameFromDeclarations(declarations: Declaration[] | undefined) {
function getSomeTargetNameFromDeclarations(declarations: readonly Declaration[] | undefined) {
return firstDefined(declarations, d => {
if (isImportSpecifier(d) || isExportSpecifier(d)) {
return moduleExportNameTextUnescaped(d.propertyName || d.name);
@ -10729,7 +10730,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
return result;
function buildVisibleNodeList(declarations: Declaration[] | undefined) {
function buildVisibleNodeList(declarations: readonly Declaration[] | undefined) {
forEach(declarations, declaration => {
const resultNode = getAnyImportSyntax(declaration) || declaration;
if (setVisibility) {
@ -11560,8 +11561,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
const union = createSymbol(s.flags | exportedMember.flags, name);
union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
union.valueDeclaration = exportedMember.valueDeclaration;
union.declarations = concatenate(exportedMember.declarations, s.declarations);
union.astValueDeclaration = exportedMember.astValueDeclaration;
union.astDeclarations = concatenate(exportedMember.astDeclarations, s.astDeclarations);
members.set(name, union);
}
else {
@ -11618,7 +11619,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
(thisContainer.kind === SyntaxKind.FunctionExpression && !isPrototypePropertyAssignment(thisContainer.parent));
}
function getConstructorDefinedThisAssignmentTypes(types: Type[], declarations: Declaration[]): Type[] | undefined {
function getConstructorDefinedThisAssignmentTypes(types: Type[], declarations: readonly Declaration[]): Type[] | undefined {
Debug.assert(types.length === declarations.length);
return types.filter((_, i) => {
const declaration = declarations[i];
@ -11846,10 +11847,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (symbol.flags & SymbolFlags.ModuleExports && symbol.valueDeclaration) {
const fileSymbol = getSymbolOfDeclaration(getSourceFileOfNode(symbol.valueDeclaration));
const result = createSymbol(fileSymbol.flags, "exports" as __String);
result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
result.astDeclarations = fileSymbol.astDeclarations ? fileSymbol.astDeclarations.slice() : [];
result.parent = symbol;
result.links.target = fileSymbol;
if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration;
if (fileSymbol.astValueDeclaration) result.astValueDeclaration = fileSymbol.astValueDeclaration;
if (fileSymbol.members) result.members = new Map(fileSymbol.members);
if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports);
const members = createSymbolTable();
@ -13118,15 +13119,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
Debug.assert(!!(getCheckFlags(symbol) & CheckFlags.Late), "Expected a late-bound symbol.");
symbol.flags |= symbolFlags;
getSymbolLinks(member.symbol).lateSymbol = symbol;
if (!symbol.declarations) {
symbol.declarations = [member];
if (!symbol.astDeclarations) {
symbol.astDeclarations = [member.ast];
}
else if (!member.symbol.isReplaceableByMethod) {
symbol.declarations.push(member);
symbol.astDeclarations.push(member.ast);
}
if (symbolFlags & SymbolFlags.Value) {
if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
symbol.valueDeclaration = member;
if (!symbol.astValueDeclaration || symbol.astValueDeclaration.kind !== member.kind) {
symbol.astValueDeclaration = member.ast;
}
}
}
@ -13219,11 +13220,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// Then just add the computed name as a late bound declaration
// (note: unlike `addDeclarationToLateBoundSymbol` we do not set up a `.lateSymbol` on `decl`'s links,
// since that would point at an index symbol and not a single property symbol, like most consumers would expect)
if (!indexSymbol.declarations) {
indexSymbol.declarations = [decl];
if (!indexSymbol.astDeclarations) {
indexSymbol.astDeclarations = [decl.ast];
}
else if (!decl.symbol.isReplaceableByMethod) {
indexSymbol.declarations.push(decl);
indexSymbol.astDeclarations.push(decl.ast);
}
}
@ -14010,7 +14011,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0);
const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.escapedName, checkFlags) as ReverseMappedSymbol;
inferredProp.declarations = prop.declarations;
inferredProp.astDeclarations = prop.astDeclarations;
inferredProp.links.nameType = getSymbolLinks(prop).nameType;
inferredProp.links.propertyType = getTypeOfSymbol(prop);
if (
@ -14146,7 +14147,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
prop.links.keyType = keyType;
if (modifiersProp) {
prop.links.syntheticOrigin = modifiersProp;
prop.declarations = shouldLinkPropDeclarations ? modifiersProp.declarations : undefined;
prop.astDeclarations = shouldLinkPropDeclarations ? modifiersProp.astDeclarations : undefined;
}
members.set(propName, prop);
}
@ -14948,7 +14949,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
const props = propSet ? arrayFrom(propSet.values()) : [singleProp];
let declarations: Declaration[] | undefined;
let declarations: AstDeclaration[] | undefined;
let firstType: Type | undefined;
let nameType: Type | undefined;
const propTypes: Type[] = [];
@ -14962,7 +14963,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
hasNonUniformValueDeclaration = true;
}
declarations = addRange(declarations, prop.declarations);
declarations = addRange(declarations, prop.astDeclarations);
const type = getTypeOfSymbol(prop);
if (!firstType) {
firstType = type;
@ -14987,7 +14988,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const result = createSymbol(SymbolFlags.Property | (optionalFlag ?? 0), name, syntheticFlag | checkFlags);
result.links.containingType = containingType;
if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
result.valueDeclaration = firstValueDeclaration;
result.astValueDeclaration = firstValueDeclaration.ast;
// Inherit information about parent type.
if (firstValueDeclaration.symbol.parent) {
@ -14995,7 +14996,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
result.declarations = declarations;
result.astDeclarations = declarations;
result.links.nameType = nameType;
if (propTypes.length > 2) {
// When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
@ -15935,8 +15936,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// type variables by `couldContainTypeVariables`
const type = createObjectType(ObjectFlags.Anonymous | ObjectFlags.SingleSignatureType, createSymbol(SymbolFlags.Function, InternalSymbolName.Function)) as SingleSignatureType;
if (signature.declaration && !nodeIsSynthesized(signature.declaration)) { // skip synthetic declarations - keeping those around could be bad, since they lack a parent pointer
type.symbol.declarations = [signature.declaration];
type.symbol.valueDeclaration = signature.declaration;
type.symbol.astDeclarations = [signature.declaration.ast];
type.symbol.astValueDeclaration = signature.declaration.ast;
}
outerTypeParameters ||= signature.declaration && getOuterTypeParameters(signature.declaration, /*includeThisTypes*/ true);
type.outerTypeParameters = outerTypeParameters;
@ -19424,7 +19425,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const flags = SymbolFlags.Property | SymbolFlags.Optional;
const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? CheckFlags.Readonly : 0));
result.links.type = isSetonlyAccessor ? undefinedType : addOptionality(getTypeOfSymbol(prop), /*isProperty*/ true);
result.declarations = prop.declarations;
result.astDeclarations = prop.astDeclarations;
result.links.nameType = getSymbolLinks(prop).nameType;
result.links.syntheticOrigin = prop;
members.set(prop.escapedName, result);
@ -19508,7 +19509,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const rightProp = members.get(leftProp.escapedName)!;
const rightType = getTypeOfSymbol(rightProp);
if (rightProp.flags & SymbolFlags.Optional) {
const declarations = concatenate(leftProp.declarations, rightProp.declarations);
const declarations = concatenate(leftProp.astDeclarations, rightProp.astDeclarations);
const flags = SymbolFlags.Property | (leftProp.flags & SymbolFlags.Optional);
const result = createSymbol(flags, leftProp.escapedName);
// Optimization: avoid calculating the union type if spreading into the exact same type.
@ -19521,7 +19522,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
result.links.type = leftTypeWithoutUndefined === rightTypeWithoutUndefined ? leftType : getUnionType([leftType, rightTypeWithoutUndefined], UnionReduction.Subtype);
result.links.leftSpread = leftProp;
result.links.rightSpread = rightProp;
result.declarations = declarations;
result.astDeclarations = declarations;
result.links.nameType = getSymbolLinks(leftProp).nameType;
members.set(leftProp.escapedName, result);
}
@ -19551,7 +19552,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const flags = SymbolFlags.Property | (prop.flags & SymbolFlags.Optional);
const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? CheckFlags.Readonly : 0));
result.links.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.astDeclarations = prop.astDeclarations;
result.links.nameType = getSymbolLinks(prop).nameType;
result.links.syntheticOrigin = prop;
return result;
@ -20003,12 +20004,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
// also transient so that we can just store data on it directly.
const result = createSymbol(symbol.flags, symbol.escapedName, CheckFlags.Instantiated | getCheckFlags(symbol) & (CheckFlags.Readonly | CheckFlags.Late | CheckFlags.OptionalParameter | CheckFlags.RestParameter));
result.declarations = symbol.declarations;
result.astDeclarations = symbol.astDeclarations;
result.parent = symbol.parent;
result.links.target = symbol;
result.links.mapper = mapper;
if (symbol.valueDeclaration) {
result.valueDeclaration = symbol.valueDeclaration;
if (symbol.astValueDeclaration) {
result.astValueDeclaration = symbol.astValueDeclaration;
}
if (links.nameType) {
result.links.nameType = links.nameType;
@ -20035,7 +20036,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
outerTypeParameters = addRange(outerTypeParameters, templateTagParameters);
}
typeParameters = outerTypeParameters || emptyArray;
const allDeclarations = type.objectFlags & (ObjectFlags.Reference | ObjectFlags.InstantiationExpressionType) ? [declaration] : type.symbol.declarations!;
const allDeclarations: readonly Node[] = type.objectFlags & (ObjectFlags.Reference | ObjectFlags.InstantiationExpressionType) ? [declaration] : type.symbol.declarations!;
typeParameters = (target.objectFlags & (ObjectFlags.Reference | ObjectFlags.InstantiationExpressionType) || target.symbol.flags & SymbolFlags.Method || target.symbol.flags & SymbolFlags.TypeLiteral) && !target.aliasTypeArguments ?
filter(typeParameters, tp => some(allDeclarations, d => isTypeParameterPossiblyReferenced(tp, d))) :
typeParameters;
@ -25102,12 +25103,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function createSymbolWithType(source: Symbol, type: Type | undefined) {
const symbol = createSymbol(source.flags, source.escapedName, getCheckFlags(source) & CheckFlags.Readonly);
symbol.declarations = source.declarations;
symbol.astDeclarations = source.astDeclarations;
symbol.parent = source.parent;
symbol.links.type = type;
symbol.links.target = source;
if (source.valueDeclaration) {
symbol.valueDeclaration = source.valueDeclaration;
if (source.astValueDeclaration) {
symbol.astValueDeclaration = source.astValueDeclaration;
}
const nameType = getSymbolLinks(source).nameType;
if (nameType) {
@ -25647,8 +25648,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const literalProp = createSymbol(SymbolFlags.Property, name);
literalProp.links.type = anyType;
if (t.symbol) {
literalProp.declarations = t.symbol.declarations;
literalProp.valueDeclaration = t.symbol.valueDeclaration;
literalProp.astDeclarations = t.symbol.astDeclarations;
literalProp.astValueDeclaration = t.symbol.astValueDeclaration;
}
members.set(name, literalProp);
});
@ -32746,10 +32747,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
prop.declarations = member.declarations;
prop.astDeclarations = member.astDeclarations;
prop.parent = member.parent;
if (member.valueDeclaration) {
prop.valueDeclaration = member.valueDeclaration;
if (member.astValueDeclaration) {
prop.astValueDeclaration = member.astValueDeclaration;
}
prop.links.type = type;
@ -32979,10 +32980,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
objectFlags |= getObjectFlags(exprType) & ObjectFlags.PropagatingFlags;
const attributeSymbol = createSymbol(SymbolFlags.Property | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.astDeclarations = member.astDeclarations;
attributeSymbol.parent = member.parent;
if (member.valueDeclaration) {
attributeSymbol.valueDeclaration = member.valueDeclaration;
if (member.astValueDeclaration) {
attributeSymbol.astValueDeclaration = member.astValueDeclaration;
}
attributeSymbol.links.type = exprType;
attributeSymbol.links.target = member;
@ -33059,9 +33060,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
createArrayType(getUnionType(childrenTypes));
// Fake up a property declaration for the children
childrenPropSymbol.valueDeclaration = factory.createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
childrenPropSymbol.astValueDeclaration = factory.createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined).ast;
setParent(childrenPropSymbol.valueDeclaration, attributeParent);
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
childrenPropSymbol.valueDeclaration!.symbol = childrenPropSymbol;
const childPropMap = createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
spread = getSpreadType(spread, createAnonymousType(attributesSymbol, childPropMap, emptyArray, emptyArray, emptyArray), attributesSymbol, objectFlags, /*readonly*/ false);
@ -42095,7 +42096,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
}
function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration | undefined, flagsToCheck: ModifierFlags, someOverloadFlags: ModifierFlags, allOverloadFlags: ModifierFlags): void {
function checkFlagAgreementBetweenOverloads(overloads: readonly Declaration[], implementation: FunctionLikeDeclaration | undefined, flagsToCheck: ModifierFlags, someOverloadFlags: ModifierFlags, allOverloadFlags: ModifierFlags): void {
// Error if some overloads have a flag that is not shared by all overloads. To find the
// deviations, we XOR someOverloadFlags with allOverloadFlags
const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
@ -42135,7 +42136,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
function checkQuestionTokenAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration | undefined, someHaveQuestionToken: boolean, allHaveQuestionToken: boolean): void {
function checkQuestionTokenAgreementBetweenOverloads(overloads: readonly Declaration[], implementation: FunctionLikeDeclaration | undefined, someHaveQuestionToken: boolean, allHaveQuestionToken: boolean): void {
if (someHaveQuestionToken !== allHaveQuestionToken) {
const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation));
forEach(overloads, o => {
@ -45732,7 +45733,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// and properties with literal names were already checked.
if (!isStatic(member) && !hasBindableName(member)) {
const symbol = getSymbolOfDeclaration(member);
checkIndexConstraintForProperty(type, symbol, getTypeOfExpression((member as DynamicNamedDeclaration).name.expression), getNonMissingTypeOfSymbol(symbol));
checkIndexConstraintForProperty(type, symbol, getTypeOfExpression((member as NamedDeclaration as DynamicNamedDeclaration).name.expression), getNonMissingTypeOfSymbol(symbol));
}
}
}
@ -47964,7 +47965,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
function isDuplicatedCommonJSExport(declarations: Declaration[] | undefined) {
function isDuplicatedCommonJSExport(declarations: readonly Declaration[] | undefined) {
return declarations
&& declarations.length > 1
&& declarations.every(d => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression)));
@ -48982,8 +48983,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
else {
const copy = createSymbol(SymbolFlags.Signature, InternalSymbolName.Index);
copy.declarations = mapDefined(infos, i => i.declaration);
copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent);
copy.astDeclarations = mapDefined(infos, i => i.declaration?.ast);
copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.astDeclarations[0].parent.node);
symbolLinks.filteredIndexSymbolCache.set(nodeListId, copy);
return copy;
}
@ -50133,7 +50134,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return true;
}
return false;
});
})?.slice();
}
}
}

Просмотреть файл

@ -10,6 +10,7 @@ import {
SortedReadonlyArray,
TextSpan,
} from "./_namespaces/ts.js";
import { ReadonlyArrayView } from "./readonlyArray.js";
/* eslint-disable @typescript-eslint/prefer-for-of */
@ -1749,7 +1750,7 @@ export function createSet<TElement, THash = number>(getHashCode: (element: TElem
*/
export function isArray(value: any): value is readonly unknown[] {
// See: https://github.com/microsoft/TypeScript/issues/17002
return Array.isArray(value);
return Array.isArray(value) || ReadonlyArrayView.isReadonlyArrayView(value);
}
/** @internal */
@ -2591,3 +2592,8 @@ export function isNodeLikeSystem(): boolean {
&& !(process as any).browser
&& typeof require !== "undefined";
}
/** @internal */
export function createReadOnlyArrayView<T, U>(source: readonly T[], mapper: (value: T) => U): readonly U[] {
return new ReadonlyArrayView(source, mapper);
}

Просмотреть файл

@ -233,6 +233,8 @@ export namespace Debug {
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
}
export function assertNeverTypeOnly(_: never): void {}
export function assertEachNode<T extends Node, U extends T>(nodes: NodeArray<T>, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is NodeArray<U>;
export function assertEachNode<T extends Node, U extends T>(nodes: readonly T[], test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is readonly U[];
export function assertEachNode<T extends Node, U extends T>(nodes: NodeArray<T> | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is NodeArray<U> | undefined;

Просмотреть файл

@ -293,22 +293,21 @@ import {
getSyntheticLeadingComments,
getSyntheticTrailingComments,
identity,
isAstBinaryExpression,
isAstCallChain,
isAstCommaListExpression,
isAstCommaToken,
isAstElementAccessChain,
isAstExclamationToken,
isAstIdentifier,
isAstNonNullChain,
isAstNotEmittedStatement,
isAstOmittedExpression,
isAstOuterExpression,
isAstParenthesizedExpression,
isAstPrivateIdentifier,
isAstPropertyAccessChain,
isAstQuestionToken,
isAstVariableDeclaration,
astIsBinaryExpression,
astIsCallChain,
astIsCommaListExpression,
astIsCommaToken,
astIsElementAccessChain,
astIsExclamationToken,
astIsIdentifier,
astIsNonNullChain,
astIsNotEmittedStatement,
astIsOmittedExpression,
astIsParenthesizedExpression,
astIsPrivateIdentifier,
astIsPropertyAccessChain,
astIsQuestionToken,
astIsVariableDeclaration,
isParseTreeNode,
KeywordSyntaxKind,
KeywordTypeSyntaxKind,
@ -347,6 +346,11 @@ import {
TokenSyntaxKind,
TransformFlags,
Type,
astIsOuterExpression,
astNodeIsSynthesized,
astSetComment,
astGetComment,
AstHasComment,
} from "../_namespaces/ts.js";
/** @internal */
@ -2006,8 +2010,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
const node = AstNode.PropertyDeclaration();
node.data.modifiers = asNodeArray(modifiers);
node.data.name = asName(name);
node.data.questionToken = questionOrExclamationToken && isAstQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
node.data.exclamationToken = questionOrExclamationToken && isAstExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
node.data.questionToken = questionOrExclamationToken && astIsQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
node.data.exclamationToken = questionOrExclamationToken && astIsExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
node.data.type = type;
node.data.initializer = asInitializer(initializer);
return finish(node);
@ -2024,8 +2028,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
) {
return !sameNodeArray(node.data.modifiers, modifiers)
|| node.data.name !== name
|| node.data.questionToken !== (questionOrExclamationToken !== undefined && isAstQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
|| node.data.exclamationToken !== (questionOrExclamationToken !== undefined && isAstExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
|| node.data.questionToken !== (questionOrExclamationToken !== undefined && astIsQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
|| node.data.exclamationToken !== (questionOrExclamationToken !== undefined && astIsExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
|| node.data.type !== type
|| node.data.initializer !== initializer
? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node)
@ -2856,7 +2860,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like
// a trailing comma.
const lastElement = elements && lastOrUndefined(arrayItems(elements));
const elementsArray = createNodeArray(elements, lastElement && isAstOmittedExpression(lastElement) ? true : undefined);
const elementsArray = createNodeArray(elements, lastElement && astIsOmittedExpression(lastElement) ? true : undefined);
node.data.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray);
node.data.multiLine = multiLine;
return finish(node);
@ -2902,8 +2906,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function updatePropertyAccessExpression(node: AstPropertyAccessExpression, expression: AstExpression, name: AstIdentifier | AstPrivateIdentifier) {
if (isAstPropertyAccessChain(node)) {
return updatePropertyAccessChain(node, expression, node.data.questionDotToken, cast(name, isAstIdentifier));
if (astIsPropertyAccessChain(node)) {
return updatePropertyAccessChain(node, expression, node.data.questionDotToken, cast(name, astIsIdentifier));
}
return node.data.expression !== expression
|| node.data.name !== name
@ -2950,7 +2954,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function updateElementAccessExpression(node: AstElementAccessExpression, expression: AstExpression, argumentExpression: AstExpression) {
if (isAstElementAccessChain(node)) {
if (astIsElementAccessChain(node)) {
return updateElementAccessChain(node, expression, node.data.questionDotToken, argumentExpression);
}
return node.data.expression !== expression
@ -2990,7 +2994,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function updateCallExpression(node: AstCallExpression, expression: AstExpression, typeArguments: AstNodeArrayLike<AstTypeNode> | undefined, argumentsArray: AstNodeArrayLike<AstExpression>) {
if (isAstCallChain(node)) {
if (astIsCallChain(node)) {
return updateCallChain(node, expression, node.data.questionDotToken, typeArguments, argumentsArray);
}
return node.data.expression !== expression
@ -3528,7 +3532,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function updateNonNullExpression(node: AstNonNullExpression, expression: AstExpression) {
if (isAstNonNullChain(node)) {
if (astIsNonNullChain(node)) {
return updateNonNullChain(node, expression);
}
return node.data.expression !== expression
@ -4695,7 +4699,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocTemplateTag(tagName: AstIdentifier | undefined, constraint: AstJSDocTypeExpression | undefined, typeParameters: AstNodeArrayLike<AstTypeParameterDeclaration>, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocTemplateTag {
const node = AstNode.JSDocTemplateTag();
node.data.tagName = tagName ?? createIdentifier("template");
node.data.comment = comment;
astSetComment(node, comment);
node.data.constraint = constraint;
node.data.typeParameters = createNodeArray(typeParameters);
return finish(node);
@ -4706,7 +4710,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
return node.data.tagName !== tagName
|| node.data.constraint !== constraint
|| !sameNodeArray(node.data.typeParameters, typeParameters)
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
: node;
}
@ -4715,7 +4719,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocTypedefTag(tagName: AstIdentifier | undefined, typeExpression?: AstJSDocTypeExpression, fullName?: AstIdentifier | AstJSDocNamespaceDeclaration, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocTypedefTag {
const node = AstNode.JSDocTypedefTag();
node.data.tagName = tagName ?? createIdentifier("typedef");
node.data.comment = comment;
astSetComment(node, comment);
node.data.typeExpression = typeExpression;
node.data.fullName = fullName;
node.data.name = getJSDocTypeAliasName(fullName);
@ -4727,7 +4731,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
return node.data.tagName !== tagName
|| node.data.typeExpression !== typeExpression
|| node.data.fullName !== fullName
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
: node;
}
@ -4736,7 +4740,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocParameterTag(tagName: AstIdentifier | undefined, name: AstEntityName, isBracketed: boolean, typeExpression?: AstJSDocTypeExpression, isNameFirst?: boolean, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocParameterTag {
const node = AstNode.JSDocParameterTag();
node.data.tagName = tagName ?? createIdentifier("param");
node.data.comment = comment;
astSetComment(node, comment);
node.data.typeExpression = typeExpression;
node.data.name = name;
node.data.isNameFirst = !!isNameFirst;
@ -4751,7 +4755,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
|| node.data.isBracketed !== isBracketed
|| node.data.typeExpression !== typeExpression
|| node.data.isNameFirst !== isNameFirst
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
: node;
}
@ -4760,7 +4764,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocPropertyTag(tagName: AstIdentifier | undefined, name: AstEntityName, isBracketed: boolean, typeExpression?: AstJSDocTypeExpression, isNameFirst?: boolean, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocPropertyTag {
const node = AstNode.JSDocPropertyTag();
node.data.tagName = tagName ?? createIdentifier("prop");
node.data.comment = comment;
astSetComment(node, comment);
node.data.typeExpression = typeExpression;
node.data.name = name;
node.data.isNameFirst = !!isNameFirst;
@ -4775,7 +4779,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
|| node.data.isBracketed !== isBracketed
|| node.data.typeExpression !== typeExpression
|| node.data.isNameFirst !== isNameFirst
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
: node;
}
@ -4784,7 +4788,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocCallbackTag(tagName: AstIdentifier | undefined, typeExpression: AstJSDocSignature, fullName?: AstIdentifier | AstJSDocNamespaceDeclaration, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocCallbackTag {
const node = AstNode.JSDocCallbackTag();
node.data.tagName = tagName ?? createIdentifier("callback");
node.data.comment = comment;
astSetComment(node, comment);
node.data.typeExpression = typeExpression;
node.data.fullName = fullName;
node.data.name = getJSDocTypeAliasName(fullName);
@ -4799,7 +4803,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
return node.data.tagName !== tagName
|| node.data.typeExpression !== typeExpression
|| node.data.fullName !== fullName
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
: node;
}
@ -4808,7 +4812,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocOverloadTag(tagName: AstIdentifier | undefined, typeExpression: AstJSDocSignature, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocOverloadTag {
const node = AstNode.JSDocOverloadTag();
node.data.tagName = tagName ?? createIdentifier("overload");
node.data.comment = comment;
astSetComment(node, comment);
node.data.typeExpression = typeExpression;
return finish(node);
}
@ -4817,7 +4821,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocOverloadTag(node: AstJSDocOverloadTag, tagName: AstIdentifier = getDefaultTagName(node), typeExpression: AstJSDocSignature, comment: string | AstNodeArray<AstJSDocComment> | undefined): AstJSDocOverloadTag {
return node.data.tagName !== tagName
|| node.data.typeExpression !== typeExpression
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocOverloadTag(tagName, typeExpression, comment), node)
: node;
}
@ -4826,7 +4830,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocAugmentsTag(tagName: AstIdentifier | undefined, className: AstJSDocAugmentsTag["data"]["class"], comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocAugmentsTag {
const node = AstNode.JSDocAugmentsTag();
node.data.tagName = tagName ?? createIdentifier("augments");
node.data.comment = comment;
astSetComment(node, comment);
node.data.class = className;
return finish(node);
}
@ -4835,7 +4839,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocAugmentsTag(node: AstJSDocAugmentsTag, tagName: AstIdentifier = getDefaultTagName(node), className: AstJSDocAugmentsTag["data"]["class"], comment: string | AstNodeArray<AstJSDocComment> | undefined): AstJSDocAugmentsTag {
return node.data.tagName !== tagName
|| node.data.class !== className
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocAugmentsTag(tagName, className, comment), node)
: node;
}
@ -4844,7 +4848,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocImplementsTag(tagName: AstIdentifier | undefined, className: AstJSDocImplementsTag["data"]["class"], comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocImplementsTag {
const node = AstNode.JSDocImplementsTag();
node.data.tagName = tagName ?? createIdentifier("implements");
node.data.comment = comment;
astSetComment(node, comment);
node.data.class = className;
return finish(node);
}
@ -4853,7 +4857,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocSeeTag(tagName: AstIdentifier | undefined, name: AstJSDocNameReference | undefined, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocSeeTag {
const node = AstNode.JSDocSeeTag();
node.data.tagName = tagName ?? createIdentifier("see");
node.data.comment = comment;
astSetComment(node, comment);
node.data.name = name;
return finish(node);
}
@ -4862,7 +4866,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocSeeTag(node: AstJSDocSeeTag, tagName: AstIdentifier | undefined, name: AstJSDocNameReference | undefined, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocSeeTag {
return node.data.tagName !== tagName
|| node.data.name !== name
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocSeeTag(tagName, name, comment), node)
: node;
}
@ -4946,7 +4950,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocImplementsTag(node: AstJSDocImplementsTag, tagName: AstIdentifier = getDefaultTagName(node), className: AstJSDocImplementsTag["data"]["class"], comment: string | AstNodeArray<AstJSDocComment> | undefined): AstJSDocImplementsTag {
return node.data.tagName !== tagName
|| node.data.class !== className
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocImplementsTag(tagName, className, comment), node)
: node;
}
@ -4962,7 +4966,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocSimpleTag<T extends AstJSDocTag>(makeTag: () => T, tagName: AstIdentifier | undefined, comment?: string | AstNodeArray<AstJSDocComment>) {
const node = makeTag();
node.data.tagName = tagName ?? createIdentifier(getDefaultTagNameForKind(node.kind));
node.data.comment = comment;
astSetComment(node as AstHasComment, comment);
return finish(node);
}
@ -4976,7 +4980,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// updateJSDocDeprecatedTag
function updateJSDocSimpleTag<T extends AstJSDocTag>(makeTag: () => T, node: T, tagName: AstIdentifier = getDefaultTagName(node), comment: string | AstNodeArray<AstJSDocComment> | undefined) {
return node.data.tagName !== tagName
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocSimpleTag(makeTag, tagName, comment), node) :
node;
}
@ -5002,7 +5006,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocTypeLikeTag<T extends AstJSDocTag & { readonly data: { typeExpression?: AstJSDocTypeExpression; }; }>(makeTag: () => T, node: T, tagName: AstIdentifier = getDefaultTagName(node), typeExpression: AstJSDocTypeExpression | undefined, comment: string | AstNodeArray<AstJSDocComment> | undefined) {
return node.data.tagName !== tagName
|| node.data.typeExpression !== typeExpression
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocTypeLikeTag(makeTag, tagName, typeExpression, comment), node)
: node;
}
@ -5016,7 +5020,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function updateJSDocUnknownTag(node: AstJSDocUnknownTag, tagName: AstIdentifier, comment: string | AstNodeArray<AstJSDocComment> | undefined): AstJSDocUnknownTag {
return node.data.tagName !== tagName
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocUnknownTag(tagName, comment), node)
: node;
}
@ -5032,7 +5036,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function updateJSDocEnumTag(node: AstJSDocEnumTag, tagName: AstIdentifier = getDefaultTagName(node), typeExpression: AstJSDocTypeExpression, comment: string | AstNodeArray<AstJSDocComment> | undefined) {
return node.data.tagName !== tagName
|| node.data.typeExpression !== typeExpression
|| node.data.comment !== comment
|| astGetComment(node) !== comment
? update(createJSDocEnumTag(tagName, typeExpression, comment), node)
: node;
}
@ -5041,17 +5045,17 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function createJSDocImportTag(tagName: AstIdentifier | undefined, importClause: AstImportClause | undefined, moduleSpecifier: AstExpression, attributes?: AstImportAttributes, comment?: string | AstNodeArray<AstJSDocComment>): AstJSDocImportTag {
const node = AstNode.JSDocImportTag();
node.data.tagName = tagName ?? createIdentifier("import");
node.data.comment = comment;
astSetComment(node, comment);
node.data.importClause = importClause;
node.data.moduleSpecifier = moduleSpecifier;
node.data.attributes = attributes;
node.data.comment = comment;
astSetComment(node, comment);
return finish(node);
}
function updateJSDocImportTag(node: AstJSDocImportTag, tagName: AstIdentifier | undefined, importClause: AstImportClause | undefined, moduleSpecifier: AstExpression, attributes: AstImportAttributes | undefined, comment: string | AstNodeArray<AstJSDocComment> | undefined): AstJSDocImportTag {
return node.data.tagName !== tagName
|| node.data.comment !== comment
|| astGetComment(node) !== comment
|| node.data.importClause !== importClause
|| node.data.moduleSpecifier !== moduleSpecifier
|| node.data.attributes !== attributes
@ -5076,14 +5080,14 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
// @api
function createJSDocComment(comment?: string | AstNodeArray<AstJSDocComment> | undefined, tags?: AstNodeArrayLike<AstBaseJSDocTag> | undefined) {
const node = AstNode.JSDocNode();
node.data.comment = comment;
astSetComment(node, comment);
node.data.tags = asNodeArray(tags);
return finish(node);
}
// @api
function updateJSDocComment(node: AstJSDoc, comment: string | AstNodeArray<AstJSDocComment> | undefined, tags: AstNodeArrayLike<AstJSDocTag> | undefined) {
return node.data.comment !== comment
return astGetComment(node) !== comment
|| !sameNodeArray(node.data.tags, tags)
? update(createJSDocComment(comment, tags), node)
: node;
@ -5588,11 +5592,11 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
}
function flattenCommaElements(node: AstExpression): AstExpression | readonly AstExpression[] {
if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
if (isAstCommaListExpression(node)) {
if (astNodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
if (astIsCommaListExpression(node)) {
return node.data.elements.items;
}
if (isAstBinaryExpression(node) && isAstCommaToken(node.data.operatorToken)) {
if (astIsBinaryExpression(node) && astIsCommaToken(node.data.operatorToken)) {
return [node.data.left, node.data.right];
}
}
@ -5645,8 +5649,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
clone.emitNode = undefined;
setOriginal(clone, node);
if (isAstIdentifier(node)) {
Debug.assert(isAstIdentifier(clone));
if (astIsIdentifier(node)) {
Debug.assert(astIsIdentifier(clone));
const typeArguments = getIdentifierTypeArguments(node);
if (typeArguments) setIdentifierTypeArguments(clone, typeArguments);
@ -5654,8 +5658,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
const autoGenerate = getIdentifierAutoGenerate(node);
if (autoGenerate) setIdentifierAutoGenerate(clone, { ...autoGenerate });
}
else if (isAstPrivateIdentifier(node)) {
Debug.assert(isAstPrivateIdentifier(clone));
else if (astIsPrivateIdentifier(node)) {
Debug.assert(astIsPrivateIdentifier(clone));
const autoGenerate = getIdentifierAutoGenerate(node);
if (autoGenerate) setIdentifierAutoGenerate(clone, { ...autoGenerate });
@ -5702,8 +5706,8 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
* the containing expression is created/updated.
*/
function isIgnorableParen(node: AstExpression) {
return isAstParenthesizedExpression(node)
&& nodeIsSynthesized(node)
return astIsParenthesizedExpression(node)
&& astNodeIsSynthesized(node)
&& nodeIsSynthesized(getSourceMapRange(node))
&& nodeIsSynthesized(getCommentRange(node))
&& !some(getSyntheticLeadingComments(node))
@ -5711,7 +5715,7 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
}
function restoreOuterExpressions(outerExpression: AstExpression | undefined, innerExpression: AstExpression, kinds = OuterExpressionKinds.All): AstExpression {
if (outerExpression && isAstOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
if (outerExpression && astIsOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
return updateOuterExpression(
outerExpression,
restoreOuterExpressions(outerExpression.data.expression, innerExpression),
@ -5749,11 +5753,11 @@ export function createAstNodeFactory(flags: NodeFactoryFlags, onFinishNode?: (no
function asEmbeddedStatement<T extends AstNode>(statement: T): T | AstEmptyStatement;
function asEmbeddedStatement<T extends AstNode>(statement: T | undefined): T | AstEmptyStatement | undefined;
function asEmbeddedStatement<T extends AstNode>(statement: T | undefined): T | AstEmptyStatement | undefined {
return statement && isAstNotEmittedStatement(statement) ? setTextRange(setOriginal(createEmptyStatement(), statement), statement) : statement;
return statement && astIsNotEmittedStatement(statement) ? setTextRange(setOriginal(createEmptyStatement(), statement), statement) : statement;
}
function asVariableDeclaration(variableDeclaration: string | AstBindingName | AstVariableDeclaration | undefined) {
if (typeof variableDeclaration === "string" || variableDeclaration && !isAstVariableDeclaration(variableDeclaration)) {
if (typeof variableDeclaration === "string" || variableDeclaration && !astIsVariableDeclaration(variableDeclaration)) {
return createVariableDeclaration(
variableDeclaration,
/*exclamationToken*/ undefined,
@ -5911,8 +5915,8 @@ function getJSDocTypeAliasName(fullName: AstJSDocNamespaceBody | undefined) {
if (fullName) {
let rightNode = fullName;
while (true) {
if (isAstIdentifier(rightNode) || !rightNode.data.body) {
return isAstIdentifier(rightNode) ? rightNode : rightNode.data.name;
if (astIsIdentifier(rightNode) || !rightNode.data.body) {
return astIsIdentifier(rightNode) ? rightNode : rightNode.data.name;
}
rightNode = rightNode.data.body;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -21,21 +21,20 @@ import {
AstTaggedTemplateExpression,
AstTypeNode,
AstUnaryExpression,
isAstBinaryExpression,
isAstBlock,
isAstCallExpression,
isAstCommaListExpression,
isAstConditionalTypeNode,
isAstConstructorTypeNode,
isAstFunctionTypeNode,
isAstInferTypeNode,
isAstIntersectionTypeNode,
isAstJSDocNullableType,
isAstNamedTupleMember,
isAstOptionalChain,
isAstTypeOperatorNode,
isAstUnionTypeNode,
skipAstOuterExpressions,
astIsBinaryExpression,
astIsBlock,
astIsCallExpression,
astIsCommaListExpression,
astIsConditionalTypeNode,
astIsConstructorTypeNode,
astIsFunctionTypeNode,
astIsInferTypeNode,
astIsIntersectionTypeNode,
astIsJSDocNullableType,
astIsNamedTupleMember,
astIsOptionalChain,
astIsTypeOperatorNode,
astIsUnionTypeNode,
Associativity,
BinaryOperator,
compareValues,
@ -56,6 +55,7 @@ import {
setTextRange,
SyntaxKind,
TextRange,
astSkipOuterExpressions,
} from "../_namespaces/ts.js";
/** @internal */
@ -179,7 +179,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
// the intended order of operations: `(a ** b) ** c`
const binaryOperatorPrecedence = getOperatorPrecedence(SyntaxKind.BinaryExpression, binaryOperator);
const binaryOperatorAssociativity = getOperatorAssociativity(SyntaxKind.BinaryExpression, binaryOperator);
const emittedOperand = skipAstOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const emittedOperand = astSkipOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions);
if (!isLeftSideOfBinary && operand.kind === SyntaxKind.ArrowFunction && binaryOperatorPrecedence > OperatorPrecedence.Assignment) {
// We need to parenthesize arrow functions on the right side to avoid it being
// parsed as parenthesized expression: `a && (() => {})`
@ -218,7 +218,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
}
else {
if (
isAstBinaryExpression(emittedOperand)
astIsBinaryExpression(emittedOperand)
&& emittedOperand.data.operatorToken.kind === binaryOperator
) {
// No need to parenthesize the right operand when the binary operator and
@ -289,13 +289,13 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
* emitted without parentheses.
*/
function getLiteralKindOfBinaryPlusOperand(node: AstExpression): SyntaxKind {
node = skipAstOuterExpressions(node, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
node = astSkipOuterExpressions(node, OuterExpressionKinds.PartiallyEmittedExpressions);
if (isLiteralKind(node.kind)) {
return node.kind;
}
if (isAstBinaryExpression(node) && (node as AstBinaryExpression).data.operatorToken.kind === SyntaxKind.PlusToken) {
if (astIsBinaryExpression(node) && (node as AstBinaryExpression).data.operatorToken.kind === SyntaxKind.PlusToken) {
if (node.data.cachedLiteralKind !== undefined) {
return node.data.cachedLiteralKind;
}
@ -323,7 +323,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
* BinaryExpression.
*/
function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: AstExpression, isLeftSideOfBinary: boolean, leftOperand?: AstExpression) {
const skipped = skipAstOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const skipped = astSkipOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions);
// If the resulting expression is already parenthesized, we do not need to do any further processing.
if (skipped.kind === SyntaxKind.ParenthesizedExpression) {
@ -349,7 +349,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
function parenthesizeConditionOfConditionalExpression(condition: AstExpression): AstExpression {
const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken);
const emittedCondition = skipAstOuterExpressions(condition, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const emittedCondition = astSkipOuterExpressions(condition, OuterExpressionKinds.PartiallyEmittedExpressions);
const conditionPrecedence = getExpressionPrecedence(emittedCondition);
if (compareValues(conditionPrecedence, conditionalPrecedence) !== Comparison.GreaterThan) {
return factory.createParenthesizedExpression(condition);
@ -358,14 +358,14 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
}
function isCommaSequence(expression: AstExpression): boolean {
return isAstCommaListExpression(expression) || isAstBinaryExpression(expression) && expression.node.data.operatorToken.kind === SyntaxKind.CommaToken;
return astIsCommaListExpression(expression) || astIsBinaryExpression(expression) && expression.node.data.operatorToken.kind === SyntaxKind.CommaToken;
}
function parenthesizeBranchOfConditionalExpression(branch: AstExpression): AstExpression {
// per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
// so in case when comma expression is introduced as a part of previous transformations
// if should be wrapped in parens since comma operator has the lowest precedence
const emittedExpression = skipAstOuterExpressions(branch, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const emittedExpression = astSkipOuterExpressions(branch, OuterExpressionKinds.PartiallyEmittedExpressions);
return isCommaSequence(emittedExpression)
? factory.createParenthesizedExpression(branch)
: branch;
@ -383,7 +383,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
* - ClassExpression
*/
function parenthesizeExpressionOfExportDefault(expression: AstExpression): AstExpression {
const check = skipAstOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const check = astSkipOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions);
let needsParens = isCommaSequence(check);
if (!needsParens) {
switch (getLeftmostExpression(check, /*stopAtCallExpressions*/ false).kind) {
@ -425,11 +425,11 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
// NewExpression:
// new C.x -> not the same as (new C).x
//
const emittedExpression = skipAstOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const emittedExpression = astSkipOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions);
if (
isLeftHandSideExpressionKind(skipAstOuterExpressions(emittedExpression, OuterExpressionKinds.PartiallyEmittedExpressions).kind)
isLeftHandSideExpressionKind(astSkipOuterExpressions(emittedExpression, OuterExpressionKinds.PartiallyEmittedExpressions).kind)
&& (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression as AstNewExpression).data.arguments)
&& (optionalChain || !isAstOptionalChain(emittedExpression))
&& (optionalChain || !astIsOptionalChain(emittedExpression))
) {
// TODO(rbuckton): Verify whether this assertion holds.
return expression as AstLeftHandSideExpression;
@ -441,12 +441,12 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
function parenthesizeOperandOfPostfixUnary(operand: AstExpression): AstLeftHandSideExpression {
// TODO(rbuckton): Verifiy whether `setTextRange` is needed.
return isLeftHandSideExpressionKind(skipAstOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions).kind) ? operand as AstLeftHandSideExpression : setTextRange(factory.createParenthesizedExpression(operand), operand);
return isLeftHandSideExpressionKind(astSkipOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions).kind) ? operand as AstLeftHandSideExpression : setTextRange(factory.createParenthesizedExpression(operand), operand);
}
function parenthesizeOperandOfPrefixUnary(operand: AstExpression): AstUnaryExpression {
// TODO(rbuckton): Verifiy whether `setTextRange` is needed.
return isUnaryExpressionKind(skipAstOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions).kind) ? operand as AstUnaryExpression : setTextRange(factory.createParenthesizedExpression(operand), operand);
return isUnaryExpressionKind(astSkipOuterExpressions(operand, OuterExpressionKinds.PartiallyEmittedExpressions).kind) ? operand as AstUnaryExpression : setTextRange(factory.createParenthesizedExpression(operand), operand);
}
function parenthesizeExpressionsOfCommaDelimitedList(elements: AstNodeArrayLike<AstExpression>): AstNodeArray<AstExpression> {
@ -466,7 +466,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
}
function parenthesizeExpressionForDisallowedComma(expression: AstExpression): AstExpression {
const emittedExpression = skipAstOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
const emittedExpression = astSkipOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions);
const expressionPrecedence = getExpressionPrecedence(emittedExpression);
const commaPrecedence = getOperatorPrecedence(SyntaxKind.BinaryExpression, SyntaxKind.CommaToken);
// TODO(rbuckton): Verifiy whether `setTextRange` is needed.
@ -474,10 +474,10 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
}
function parenthesizeExpressionOfExpressionStatement(expression: AstExpression): AstExpression {
const emittedExpression = skipAstOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions) as AstExpression;
if (isAstCallExpression(emittedExpression)) {
const emittedExpression = astSkipOuterExpressions(expression, OuterExpressionKinds.PartiallyEmittedExpressions);
if (astIsCallExpression(emittedExpression)) {
const callee = emittedExpression.data.expression;
const kind = skipAstOuterExpressions(callee, OuterExpressionKinds.PartiallyEmittedExpressions).kind;
const kind = astSkipOuterExpressions(callee, OuterExpressionKinds.PartiallyEmittedExpressions).kind;
if (kind === SyntaxKind.FunctionExpression || kind === SyntaxKind.ArrowFunction) {
// TODO(rbuckton): Verifiy whether `setTextRange` is needed.
const updated = factory.updateCallExpression(
@ -502,7 +502,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
function parenthesizeConciseBodyOfArrowFunction(body: AstExpression): AstExpression;
function parenthesizeConciseBodyOfArrowFunction(body: AstConciseBody): AstConciseBody;
function parenthesizeConciseBodyOfArrowFunction(body: AstConciseBody): AstConciseBody {
if (!isAstBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === SyntaxKind.ObjectLiteralExpression)) {
if (!astIsBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === SyntaxKind.ObjectLiteralExpression)) {
// TODO(rbuckton): Verifiy whether `setTextRange` is needed.
return setTextRange(factory.createParenthesizedExpression(body), body);
}
@ -660,13 +660,13 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
}
function hasJSDocPostfixQuestion(type: AstTypeNode | AstNamedTupleMember): boolean {
if (isAstJSDocNullableType(type)) return type.data.postfix;
if (isAstNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.data.type);
if (isAstFunctionTypeNode(type) || isAstConstructorTypeNode(type) || isAstTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.data.type);
if (isAstConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.data.falseType);
if (isAstUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.data.types.items));
if (isAstIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.data.types.items));
if (isAstInferTypeNode(type)) return !!type.data.typeParameter.data.constraint && hasJSDocPostfixQuestion(type.data.typeParameter.data.constraint);
if (astIsJSDocNullableType(type)) return type.data.postfix;
if (astIsNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.data.type);
if (astIsFunctionTypeNode(type) || astIsConstructorTypeNode(type) || astIsTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.data.type);
if (astIsConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.data.falseType);
if (astIsUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.data.types.items));
if (astIsIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.data.types.items));
if (astIsInferTypeNode(type)) return !!type.data.typeParameter.data.constraint && hasJSDocPostfixQuestion(type.data.typeParameter.data.constraint);
return false;
}
@ -697,7 +697,7 @@ export function createAstParenthesizerRules(factory: AstNodeFactory): AstParenth
// }
function parenthesizeLeadingTypeArgument(node: AstTypeNode) {
return (isAstFunctionTypeNode(node) || isAstConstructorTypeNode(node)) && node.data.typeParameters ? factory.createParenthesizedType(node) : node;
return (astIsFunctionTypeNode(node) || astIsConstructorTypeNode(node)) && node.data.typeParameters ? factory.createParenthesizedType(node) : node;
}
function parenthesizeOrdinalTypeArgument(node: AstTypeNode, i: number) {

Просмотреть файл

@ -289,7 +289,7 @@ export function isMinusToken(node: Node): node is MinusToken {
return node.kind === SyntaxKind.MinusToken;
}
export function isAsteriskToken(node: Node): node is AsteriskToken {
export function astIseriskToken(node: Node): node is AsteriskToken {
return node.kind === SyntaxKind.AsteriskToken;
}

Просмотреть файл

@ -8,6 +8,11 @@ import {
AssignmentExpression,
AssignmentOperatorOrHigher,
AssignmentPattern,
AstExpression,
astIsJSDocTypeAssertion,
AstNode,
AstOuterExpression,
AstWrappedExpression,
BinaryExpression,
BinaryOperator,
BinaryOperatorToken,
@ -628,9 +633,14 @@ export function getJSDocTypeAssertionType(node: JSDocTypeAssertion): TypeNode {
/** @internal */
export function isOuterExpression(node: Node, kinds: OuterExpressionKinds = OuterExpressionKinds.All): node is OuterExpression {
return astIsOuterExpression(node.ast, kinds);
}
/** @internal */
export function astIsOuterExpression(node: AstNode, kinds: OuterExpressionKinds = OuterExpressionKinds.All): node is AstOuterExpression {
switch (node.kind) {
case SyntaxKind.ParenthesizedExpression:
if (kinds & OuterExpressionKinds.ExcludeJSDocTypeAssertion && isJSDocTypeAssertion(node)) {
if (kinds & OuterExpressionKinds.ExcludeJSDocTypeAssertion && astIsJSDocTypeAssertion(node)) {
return false;
}
return (kinds & OuterExpressionKinds.Parentheses) !== 0;
@ -656,8 +666,19 @@ export function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKi
export function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node;
/** @internal */
export function skipOuterExpressions(node: Node, kinds = OuterExpressionKinds.All) {
while (isOuterExpression(node, kinds)) {
node = node.expression;
return astSkipOuterExpressions(node.ast, kinds).node;
}
/** @internal */
export function astSkipOuterExpressions<T extends AstExpression>(node: AstWrappedExpression<T>): T;
/** @internal */
export function astSkipOuterExpressions(node: AstExpression, kinds?: OuterExpressionKinds): AstExpression;
/** @internal */
export function astSkipOuterExpressions(node: AstNode, kinds?: OuterExpressionKinds): AstNode;
/** @internal */
export function astSkipOuterExpressions(node: AstNode, kinds: OuterExpressionKinds = OuterExpressionKinds.All): AstNode {
while (astIsOuterExpression(node, kinds)) {
node = node.data.expression;
}
return node;
}

Просмотреть файл

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {
ArrayBindingPattern,
ArrayLiteralExpression,
@ -52,13 +53,35 @@ import {
FunctionExpression,
FunctionTypeNode,
GetAccessorDeclaration,
HasAsteriskToken,
HasBody,
HasComment,
HasElements,
HasEndFlowNode,
HasExclamationToken,
HasExpression,
HasInitializer,
HasIsTypeOnly,
HasJSDoc,
HasLocals,
HasMembers,
HasName,
HasParameters,
HasQuestionDotToken,
HasQuestionToken,
HasStatement,
HasStatements,
HasSymbol,
HasTagName,
HasText,
HasType,
HasTypeParameters,
HasTypes,
HeritageClause,
Identifier,
IfStatement,
ImportAttribute,
ImportAttributes,
ImportClause,
ImportDeclaration,
ImportEqualsDeclaration,
@ -70,6 +93,7 @@ import {
IndexSignatureDeclaration,
InferTypeNode,
InterfaceDeclaration,
InternalHasTypeArguments,
IntersectionTypeNode,
IsFunctionLike,
JSDoc,
@ -144,6 +168,7 @@ import {
NamespaceExportDeclaration,
NamespaceImport,
NewExpression,
Node,
NonNullExpression,
NoSubstitutionTemplateLiteral,
NotEmittedStatement,
@ -213,7 +238,6 @@ import {
} from "./_namespaces/ts.js";
{
// eslint-disable-next-line @typescript-eslint/naming-convention
type _ = [
__Expect<IsFunctionLike, Extract<Nodes, { _signatureDeclarationBrand: any }>>,
__Expect<Extract<Nodes, { _signatureDeclarationBrand: any }>, IsFunctionLike>,
@ -221,7 +245,6 @@ import {
}
{
// eslint-disable-next-line @typescript-eslint/naming-convention
type _ = [
__Expect<HasLocals, Extract<Nodes, { _localsContainerBrand: any }>>,
__Expect<Extract<Nodes, { _localsContainerBrand: any }>, HasLocals>,
@ -229,7 +252,6 @@ import {
}
{
// eslint-disable-next-line @typescript-eslint/naming-convention
type _ = [
__Expect<HasName, Extract<Nodes, { name: any }>>,
__Expect<Extract<Nodes, { name: any }>, HasName>,
@ -237,13 +259,195 @@ import {
}
{
// eslint-disable-next-line @typescript-eslint/naming-convention
type _ = [
__Expect<HasJSDoc, Extract<Nodes, { jsDoc: any }>>,
__Expect<Extract<Nodes, { jsDoc: any }>, HasJSDoc>,
];
}
{
type _ = [
__Expect<HasExpression, Extract<Nodes, { expression: any }>>,
__Expect<Extract<Nodes, { expression: any }>, HasExpression>,
];
}
{
type _ = [
__Expect<HasInitializer, Extract<Nodes, { initializer: any }>>,
__Expect<Extract<Nodes, { initializer: any }>, HasInitializer>,
];
type __ = Exclude<Extract<Nodes, { initializer: any }>, HasInitializer>;
}
{
type _ = [
__Expect<HasText, Extract<Nodes, { text: any, escapedText?: never }>>,
__Expect<Extract<Nodes, { text: any, escapedText?: never }>, HasText>,
];
type __ = Exclude<Extract<Nodes, { text: any, escapedText?: never }>, HasText>;
}
{
type _ = [
__Expect<HasSymbol, Exclude<Extract<Nodes, { symbol: any }>, { symbol: never }>>,
__Expect<Exclude<Extract<Nodes, { symbol: any }>, { symbol: never }>, HasSymbol>,
];
type __ = Exclude<Exclude<Extract<Nodes, { symbol: any }>, { symbol: never }>, HasSymbol>;
}
{
type _ = [
__Expect<HasType, Extract<Nodes, { type: Node | undefined }>>,
__Expect<Extract<Nodes, { type: Node | undefined }>, HasType>,
];
type __ = Exclude<Extract<Nodes, { type: Node | undefined }>, HasType>;
}
{
type _ = [
__Expect<HasLocals, Extract<Nodes, { locals: any }>>,
__Expect<Extract<Nodes, { locals: any }>, HasLocals>,
];
type __ = Exclude<Extract<Nodes, { locals: any }>, HasLocals>;
}
{
type _ = [
__Expect<HasTypeParameters, Extract<Nodes, { typeParameters: any }>>,
__Expect<Extract<Nodes, { typeParameters: any }>, HasTypeParameters>,
];
type __ = Exclude<Extract<Nodes, { typeParameters: any }>, HasTypeParameters>;
}
{
type _ = [
__Expect<HasParameters, Extract<Nodes, { parameters: any }>>,
__Expect<Extract<Nodes, { parameters: any }>, HasParameters>,
];
type __ = Exclude<Extract<Nodes, { parameters: any }>, HasParameters>;
}
{
type _ = [
__Expect<HasBody, Extract<Nodes, { body: any }>>,
__Expect<Extract<Nodes, { body: any }>, HasBody>,
];
type __ = Exclude<Extract<Nodes, { body: any }>, HasBody>;
}
{
type _ = [
__Expect<HasQuestionToken, Extract<Nodes, { questionToken: any }>>,
__Expect<Extract<Nodes, { questionToken: any }>, HasQuestionToken>,
];
type __ = Exclude<Extract<Nodes, { questionToken: any }>, HasQuestionToken>;
}
{
type _ = [
__Expect<HasEndFlowNode, Extract<Nodes, { endFlowNode: any }>>,
__Expect<Extract<Nodes, { endFlowNode: any }>, HasEndFlowNode>,
];
type __ = Exclude<Extract<Nodes, { endFlowNode: any }>, HasEndFlowNode>;
}
{
type _ = [
__Expect<InternalHasTypeArguments, Extract<Nodes, { typeArguments: any }>>,
__Expect<Extract<Nodes, { typeArguments: any }>, InternalHasTypeArguments>,
];
type __ = Exclude<Extract<Nodes, { typeArguments: any }>, InternalHasTypeArguments>;
}
{
type _ = [
__Expect<HasElements, Extract<Nodes, { elements: any }>>,
__Expect<Extract<Nodes, { elements: any }>, HasElements>,
];
type __ = Exclude<Extract<Nodes, { elements: any }>, HasElements>;
}
{
type _ = [
__Expect<HasMembers, Extract<Nodes, { members: any }>>,
__Expect<Extract<Nodes, { members: any }>, HasMembers>,
];
type __ = Exclude<Extract<Nodes, { members: any }>, HasMembers>;
}
{
type _ = [
__Expect<HasStatement, Extract<Nodes, { statement: any }>>,
__Expect<Extract<Nodes, { statement: any }>, HasStatement>,
];
type __ = Exclude<Extract<Nodes, { statement: any }>, HasStatement>;
}
{
type _ = [
__Expect<HasStatements, Extract<Nodes, { statements: any }>>,
__Expect<Extract<Nodes, { statements: any }>, HasStatements>,
];
type __ = Exclude<Extract<Nodes, { statements: any }>, HasStatements>;
}
{
type _ = [
__Expect<HasExclamationToken, Extract<Nodes, { exclamationToken: any }>>,
__Expect<Extract<Nodes, { exclamationToken: any }>, HasExclamationToken>,
];
type __ = Exclude<Extract<Nodes, { exclamationToken: any }>, HasExclamationToken>;
}
{
type _ = [
__Expect<HasAsteriskToken, Extract<Nodes, { asteriskToken: any }>>,
__Expect<Extract<Nodes, { asteriskToken: any }>, HasAsteriskToken>,
];
type __ = Exclude<Extract<Nodes, { asteriskToken: any }>, HasAsteriskToken>;
}
{
type _ = [
__Expect<HasQuestionDotToken, Extract<Nodes, { questionDotToken: any }>>,
__Expect<Extract<Nodes, { questionDotToken: any }>, HasQuestionDotToken>,
];
type __ = Exclude<Extract<Nodes, { questionDotToken: any }>, HasQuestionDotToken>;
}
{
type _ = [
__Expect<HasComment, Extract<Nodes, { comment: any }>>,
__Expect<Extract<Nodes, { comment: any }>, HasComment>,
];
type __ = Exclude<Extract<Nodes, { comment: any }>, HasComment>;
}
{
type _ = [
__Expect<HasTypes, Extract<Nodes, { types: any }>>,
__Expect<Extract<Nodes, { types: any }>, HasTypes>,
];
type __ = Exclude<Extract<Nodes, { types: any }>, HasTypes>;
}
{
type _ = [
__Expect<HasTagName, Extract<Nodes, { tagName: any }>>,
__Expect<Extract<Nodes, { tagName: any }>, HasTagName>,
];
type __ = Exclude<Extract<Nodes, { tagName: any }>, HasTagName>;
}
{
type _ = [
__Expect<HasIsTypeOnly, Extract<Nodes, { isTypeOnly: any }>>,
__Expect<Extract<Nodes, { isTypeOnly: any }>, HasIsTypeOnly>,
];
type __ = Exclude<Extract<Nodes, { isTypeOnly: any }>, HasIsTypeOnly>;
}
// Registry
/**
@ -619,4 +823,4 @@ export interface NodeMap {
*/
export type Nodes = NodeMap[keyof NodeMap];
type __Expect<T, _ extends T> = never; // eslint-disable-line @typescript-eslint/naming-convention
type __Expect<T, _ extends T> = never;

Просмотреть файл

@ -35,6 +35,7 @@ import {
AstConciseBody,
AstConstructorDeclaration,
AstConstructSignatureDeclaration,
astContainsParseError,
AstDecorator,
AstDefaultClause,
AstDoStatement,
@ -58,6 +59,9 @@ import {
AstFunctionDeclaration,
AstFunctionExpression,
AstFunctionOrConstructorTypeNode,
astGetFullWidth,
astGetModifiers,
astGetTextOfNodeFromSourceText,
AstHasJSDoc,
astHasJSDoc,
astHasJSDocNodes,
@ -75,6 +79,32 @@ import {
AstIndexSignatureDeclaration,
AstInferTypeNode,
AstInterfaceDeclaration,
astIsAsyncModifier,
astIsDeclareKeyword,
astIsExportAssignment,
astIsExportDeclaration,
astIsExportModifier,
astIsExpressionWithTypeArguments,
astIsExternalModuleReference,
astIsFunctionTypeNode,
astIsIdentifier,
astIsImportDeclaration,
astIsImportEqualsDeclaration,
astIsJSDocFunctionType,
astIsJSDocNullableType,
astIsJSDocReturnTag,
astIsJSDocTypeTag,
astIsJsxNamespacedName,
astIsJsxOpeningElement,
astIsJsxOpeningFragment,
astIsLeftHandSideExpression,
astIsMetaProperty,
astIsNonNullExpression,
astIsPrivateIdentifier,
astIsSetAccessorDeclaration,
astIsStringOrNumericLiteralLike,
astIsTaggedTemplateExpression,
astIsTypeReferenceNode,
AstIterationStatement,
AstJSDoc,
AstJSDocAllType,
@ -145,6 +175,7 @@ import {
AstMissingDeclaration,
AstModifier,
AstModifierLike,
astModifiersToFlags,
AstModuleBlock,
AstModuleDeclaration,
AstModuleExportName,
@ -159,6 +190,8 @@ import {
AstNode,
AstNodeArray,
AstNodeArrayLike,
astNodeIsMissing,
astNodeIsPresent,
AstNoSubstitutionTemplateLiteral,
AstNullLiteral,
AstNumericLiteral,
@ -230,7 +263,6 @@ import {
commentPragmas,
CommentRange,
concatenate,
containsParseError,
convertToJson,
createAstNodeFactory,
createDetachedDiagnostic,
@ -256,42 +288,14 @@ import {
getAnyExtensionFromPath,
getBaseFileName,
getBinaryOperatorPrecedence,
getFullWidth,
getJSDocCommentRanges,
getLanguageVariant,
getLastChild,
getLeadingCommentRanges,
getSpellingSuggestion,
getTextOfNodeFromSourceText,
identity,
isArray,
isAssignmentOperator,
isAstAsyncModifier,
isAstDeclareKeyword,
isAstExportAssignment,
isAstExportDeclaration,
isAstExportModifier,
isAstExpressionWithTypeArguments,
isAstExternalModuleReference,
isAstFunctionTypeNode,
isAstIdentifier,
isAstImportDeclaration,
isAstImportEqualsDeclaration,
isAstJSDocFunctionType,
isAstJSDocNullableType,
isAstJSDocReturnTag,
isAstJSDocTypeTag,
isAstJsxNamespacedName,
isAstJsxOpeningElement,
isAstJsxOpeningFragment,
isAstLeftHandSideExpression,
isAstMetaProperty,
isAstNonNullExpression,
isAstPrivateIdentifier,
isAstSetAccessorDeclaration,
isAstStringOrNumericLiteralLike,
isAstTaggedTemplateExpression,
isAstTypeReferenceNode,
isClassMemberModifier,
isIdentifierText,
isKeyword,
@ -311,15 +315,12 @@ import {
map,
mapDefined,
ModifierFlags,
modifiersToFlags,
ModuleKind,
Mutable,
Node,
NodeFactory,
NodeFactoryFlags,
NodeFlags,
nodeIsMissing,
nodeIsPresent,
noop,
normalizePath,
OperatorPrecedence,
@ -406,10 +407,10 @@ export function isFileProbablyExternalModule(sourceFile: SourceFile): Node | und
function isAnExternalModuleIndicatorNode(node: AstNode) {
return astCanHaveModifiers(node) && hasModifierOfKind(node, SyntaxKind.ExportKeyword)
|| isAstImportEqualsDeclaration(node) && isAstExternalModuleReference(node.data.moduleReference)
|| isAstImportDeclaration(node)
|| isAstExportAssignment(node)
|| isAstExportDeclaration(node) ? node : undefined;
|| astIsImportEqualsDeclaration(node) && astIsExternalModuleReference(node.data.moduleReference)
|| astIsImportDeclaration(node)
|| astIsExportAssignment(node)
|| astIsExportDeclaration(node) ? node : undefined;
}
function getImportMetaIfNecessary(sourceFile: SourceFile) {
@ -424,11 +425,11 @@ function walkTreeForImportMeta(node: AstNode): AstNode | undefined {
/** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
function hasModifierOfKind(node: AstHasModifiers, kind: SyntaxKind) {
return some(node.data.modifiers?.items, m => m.kind === kind);
return some(astGetModifiers(node)?.items, m => m.kind === kind);
}
function isImportMeta(node: AstNode): boolean {
return isAstMetaProperty(node) && node.data.keywordToken === SyntaxKind.ImportKeyword && node.data.name.data.escapedText === "meta";
return astIsMetaProperty(node) && node.data.keywordToken === SyntaxKind.ImportKeyword && node.data.name.data.escapedText === "meta";
}
export interface CreateSourceFileOptions {
@ -497,7 +498,13 @@ export function parseJsonText(fileName: string, sourceText: string): JsonSourceF
// See also `isExternalOrCommonJsModule` in utilities.ts
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
return astIsExternalModule(file.ast);
}
// See also `isExternalOrCommonJsModule` in utilities.ts
/** @internal */
export function astIsExternalModule(file: AstSourceFile): boolean {
return file.data.externalModuleIndicator !== undefined;
}
// Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
@ -1456,13 +1463,13 @@ namespace Parser {
// Tagged template literals are sometimes used in places where only simple strings are allowed, i.e.:
// module `M1` {
// ^^^^^^^^^^^ This block is parsed as a template literal like module`M1`.
if (isAstTaggedTemplateExpression(node)) {
if (astIsTaggedTemplateExpression(node)) {
parseErrorAt(skipTrivia(sourceText, node.data.template.pos), node.data.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings);
return;
}
// Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
const expressionText = isAstIdentifier(node) ? unescapeLeadingUnderscores(node.data.escapedText) : undefined;
const expressionText = astIsIdentifier(node) ? unescapeLeadingUnderscores(node.data.escapedText) : undefined;
if (!expressionText || !isIdentifierText(expressionText, languageVersion)) {
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken));
return;
@ -2226,7 +2233,7 @@ namespace Parser {
// Can't reuse a node that intersected the change range.
// Can't reuse a node that contains a parse error. This is necessary so that we
// produce the same set of errors again.
if (nodeIsMissing(node) || intersectsIncrementalChange(node) || containsParseError(node)) {
if (astNodeIsMissing(node) || intersectsIncrementalChange(node) || astContainsParseError(node)) {
return undefined;
}
@ -2898,7 +2905,7 @@ namespace Parser {
function typeHasArrowFunctionBlockingParseError(node: AstTypeNode): boolean {
switch (node.kind) {
case SyntaxKind.TypeReference:
return nodeIsMissing((node as AstTypeReferenceNode).data.typeName);
return astNodeIsMissing((node as AstTypeReferenceNode).data.typeName);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType: {
const { data: { parameters, type } } = node as AstFunctionOrConstructorTypeNode;
@ -3091,7 +3098,7 @@ namespace Parser {
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
if (getFullWidth(name) === 0 && !some(modifiers?.items) && isModifierKind(token())) {
if (astGetFullWidth(name) === 0 && !some(modifiers?.items) && isModifierKind(token())) {
// in cases like
// 'use strict'
// function foo(static)
@ -3532,7 +3539,7 @@ namespace Parser {
return finishNode(factory.createRestTypeNode(parseType()), pos);
}
const type = parseType();
if (isAstJSDocNullableType(type) && type.pos === type.data.type.pos) {
if (astIsJSDocNullableType(type) && type.pos === type.data.type.pos) {
const node = factory.createOptionalTypeNode(type.data.type);
setTextRange(node, type);
node.flags = type.flags;
@ -3890,7 +3897,7 @@ namespace Parser {
if (isStartOfFunctionTypeOrConstructorType()) {
const type = parseFunctionOrConstructorType();
let diagnostic: DiagnosticMessage;
if (isAstFunctionTypeNode(type)) {
if (astIsFunctionTypeNode(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;
@ -4215,7 +4222,7 @@ namespace Parser {
//
// Note: we call reScanGreaterToken so that we get an appropriately merged token
// for cases like `> > =` becoming `>>=`
if (isAstLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) {
if (astIsLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) {
return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos);
}
@ -4521,7 +4528,7 @@ namespace Parser {
const pos = getNodePos();
const hasJSDoc = hasPrecedingJSDocComment();
const modifiers = parseModifiersForArrowFunction();
const isAsync = some(modifiers?.items, isAstAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
const isAsync = some(modifiers?.items, astIsAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
// Arrow functions are never generators.
//
// If we're speculatively parsing a signature for a parenthesized arrow function, then
@ -4576,7 +4583,7 @@ namespace Parser {
unwrappedType = (unwrappedType as AstParenthesizedTypeNode).data.type; // Skip parens if need be
}
const hasJSDocFunctionType = unwrappedType && isAstJSDocFunctionType(unwrappedType);
const hasJSDocFunctionType = unwrappedType && astIsJSDocFunctionType(unwrappedType);
if (!allowAmbiguity && token() !== SyntaxKind.EqualsGreaterThanToken && (hasJSDocFunctionType || token() !== SyntaxKind.OpenBraceToken)) {
// Returning undefined here will cause our caller to rewind to where we started from.
return undefined;
@ -4587,7 +4594,7 @@ namespace Parser {
const lastToken = token();
const equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken);
const body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken)
? parseArrowFunctionExpressionBody(some(modifiers?.items, isAstAsyncModifier), allowReturnTypeInArrowFunction)
? parseArrowFunctionExpressionBody(some(modifiers?.items, astIsAsyncModifier), allowReturnTypeInArrowFunction)
: parseIdentifier();
// Given:
@ -4674,7 +4681,7 @@ namespace Parser {
questionToken,
doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false)),
colonToken = parseExpectedToken(SyntaxKind.ColonToken),
nodeIsPresent(colonToken)
astNodeIsPresent(colonToken)
? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)
: createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)),
),
@ -4971,7 +4978,7 @@ namespace Parser {
const expression = parseLeftHandSideExpressionOrHigher();
Debug.assert(isAstLeftHandSideExpression(expression));
Debug.assert(astIsLeftHandSideExpression(expression));
if ((token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) {
const operator = token() as PostfixUnaryOperator;
nextToken();
@ -5158,13 +5165,13 @@ namespace Parser {
else {
closingElement = parseJsxClosingElement(opening, inExpressionContext);
if (!tagNamesAreEquivalent(opening.data.tagName, closingElement.data.tagName)) {
if (openingTag && isAstJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.data.tagName, openingTag.data.tagName)) {
if (openingTag && astIsJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.data.tagName, openingTag.data.tagName)) {
// opening incorrectly matched with its parent's closing -- put error on opening
parseErrorAtRange(opening.data.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, opening.data.tagName));
parseErrorAtRange(opening.data.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, astGetTextOfNodeFromSourceText(sourceText, opening.data.tagName));
}
else {
// other opening/closing mismatches -- put error on closing
parseErrorAtRange(closingElement.data.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.data.tagName));
parseErrorAtRange(closingElement.data.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, astGetTextOfNodeFromSourceText(sourceText, opening.data.tagName));
}
}
}
@ -5215,7 +5222,7 @@ namespace Parser {
case SyntaxKind.EndOfFileToken:
// If we hit EOF, issue the error at the tag that lacks the closing element
// rather than at the end of the file (which is useless)
if (isAstJsxOpeningFragment(openingTag)) {
if (astIsJsxOpeningFragment(openingTag)) {
parseErrorAtRange(openingTag, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
}
else {
@ -5223,7 +5230,7 @@ namespace Parser {
// or to cover only 'Foo' in < Foo >
const tag = openingTag.data.tagName;
const start = Math.min(skipTrivia(sourceText, tag.pos), tag.end);
parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTag.data.tagName));
parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, astGetTextOfNodeFromSourceText(sourceText, openingTag.data.tagName));
}
return undefined;
case SyntaxKind.LessThanSlashToken:
@ -5252,7 +5259,7 @@ namespace Parser {
if (!child) break;
list.push(child);
if (
isAstJsxOpeningElement(openingTag)
astIsJsxOpeningElement(openingTag)
&& child?.kind === SyntaxKind.JsxElement
&& !tagNamesAreEquivalent(child.data.openingElement.data.tagName, child.data.closingElement.data.tagName)
&& tagNamesAreEquivalent(openingTag.data.tagName, child.data.closingElement.data.tagName)
@ -5319,7 +5326,7 @@ namespace Parser {
// We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
// We only want to consider "this" as a primaryExpression
const initialExpression = parseJsxTagName();
if (isAstJsxNamespacedName(initialExpression)) {
if (astIsJsxNamespacedName(initialExpression)) {
return initialExpression; // `a:b.c` is invalid syntax, don't even look for the `.` if we parse `a:b`, and let `parseAttribute` report "unexpected :" instead.
}
let expression: AstPropertyAccessExpression | AstIdentifier | AstThisExpression = initialExpression;
@ -5475,14 +5482,14 @@ namespace Parser {
return true;
}
// check for an optional chain in a non-null expression
if (isAstNonNullExpression(node)) {
if (astIsNonNullExpression(node)) {
let expr = node.data.expression;
while (isAstNonNullExpression(expr) && !(expr.flags & NodeFlags.OptionalChain)) {
while (astIsNonNullExpression(expr) && !(expr.flags & NodeFlags.OptionalChain)) {
expr = expr.data.expression;
}
if (expr.flags & NodeFlags.OptionalChain) {
// this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
while (isAstNonNullExpression(node)) {
while (astIsNonNullExpression(node)) {
node.flags |= NodeFlags.OptionalChain;
node = node.data.expression;
}
@ -5498,10 +5505,10 @@ namespace Parser {
const propertyAccess = isOptionalChain ?
factoryCreatePropertyAccessChain(expression, questionDotToken, name) :
factoryCreatePropertyAccessExpression(expression, name);
if (isOptionalChain && isAstPrivateIdentifier(propertyAccess.data.name)) {
if (isOptionalChain && astIsPrivateIdentifier(propertyAccess.data.name)) {
parseErrorAtRange(propertyAccess.data.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
}
if (isAstExpressionWithTypeArguments(expression) && expression.data.typeArguments) {
if (astIsExpressionWithTypeArguments(expression) && expression.data.typeArguments) {
const pos = expression.data.typeArguments.pos - 1;
const end = skipTrivia(sourceText, expression.data.typeArguments.end) + 1;
parseErrorAt(pos, end, Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access);
@ -5516,7 +5523,7 @@ namespace Parser {
}
else {
const argument = allowInAnd(parseExpression);
if (isAstStringOrNumericLiteralLike(argument)) {
if (astIsStringOrNumericLiteralLike(argument)) {
argument.data.text = internIdentifier(argument.data.text);
}
argumentExpression = argument;
@ -5555,7 +5562,7 @@ namespace Parser {
if (isTemplateStartOfTaggedTemplate()) {
// Absorb type arguments into TemplateExpression when preceding expression is ExpressionWithTypeArguments
expression = !questionDotToken && isAstExpressionWithTypeArguments(expression) ?
expression = !questionDotToken && astIsExpressionWithTypeArguments(expression) ?
parseTaggedTemplateRest(pos, expression.data.expression, questionDotToken, expression.data.typeArguments) :
parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
continue;
@ -5611,7 +5618,7 @@ namespace Parser {
}
if (typeArguments || token() === SyntaxKind.OpenParenToken) {
// Absorb type arguments into CallExpression when preceding expression is ExpressionWithTypeArguments
if (!questionDotToken && isAstExpressionWithTypeArguments(expression)) {
if (!questionDotToken && astIsExpressionWithTypeArguments(expression)) {
typeArguments = expression.data.typeArguments;
expression = expression.data.expression;
}
@ -5857,7 +5864,7 @@ namespace Parser {
parseExpected(SyntaxKind.FunctionKeyword);
const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None;
const isAsync = some(modifiers?.items, isAstAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
const isAsync = some(modifiers?.items, astIsAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
@ -5889,12 +5896,12 @@ namespace Parser {
let expression: AstLeftHandSideExpression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false);
let typeArguments: AstNodeArray<AstTypeNode> | undefined;
// Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments
if (isAstExpressionWithTypeArguments(expression)) {
if (astIsExpressionWithTypeArguments(expression)) {
typeArguments = expression.data.typeArguments;
expression = expression.data.expression;
}
if (token() === SyntaxKind.QuestionDotToken) {
parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression));
parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, astGetTextOfNodeFromSourceText(sourceText, expression));
}
const argumentList = token() === SyntaxKind.OpenParenToken ? parseArgumentList() : undefined;
return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos);
@ -6209,7 +6216,7 @@ namespace Parser {
let node: AstExpressionStatement | AstLabeledStatement;
const hasParen = token() === SyntaxKind.OpenParenToken;
const expression = allowInAnd(parseExpression);
if (isAstIdentifier(expression) && parseOptional(SyntaxKind.ColonToken)) {
if (astIsIdentifier(expression) && parseOptional(SyntaxKind.ColonToken)) {
node = factory.createLabeledStatement(expression, parseStatement());
}
else {
@ -6538,7 +6545,7 @@ namespace Parser {
const pos = getNodePos();
const hasJSDoc = hasPrecedingJSDocComment();
const modifiers = parseModifiers(/*allowDecorators*/ true);
const isAmbient = some(modifiers?.items, isAstDeclareKeyword);
const isAmbient = some(modifiers?.items, astIsDeclareKeyword);
if (isAmbient) {
const node = tryReuseAmbientDeclaration(pos);
if (node) {
@ -6795,7 +6802,7 @@ namespace Parser {
function parseFunctionDeclaration(pos: number, hasJSDoc: boolean, modifiers: AstNodeArray<AstModifierLike> | undefined): AstFunctionDeclaration {
const savedAwaitContext = inAwaitContext();
const modifierFlags = modifiersToFlags(modifiers?.items);
const modifierFlags = astModifiersToFlags(modifiers?.items);
parseExpected(SyntaxKind.FunctionKeyword);
const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
// We don't parse the name here in await context, instead we will report a grammar error in the checker.
@ -6852,7 +6859,7 @@ namespace Parser {
diagnosticMessage?: DiagnosticMessage,
): AstMethodDeclaration {
const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None;
const isAsync = some(modifiers?.items, isAstAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
const isAsync = some(modifiers?.items, astIsAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None;
const typeParameters = parseTypeParameters();
const parameters = parseParameters(isGenerator | isAsync);
const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false);
@ -6921,7 +6928,7 @@ namespace Parser {
: factory.createSetAccessorDeclaration(modifiers, name, parameters, body);
// Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
node.data.typeParameters = typeParameters;
if (isAstSetAccessorDeclaration(node)) {
if (astIsSetAccessorDeclaration(node)) {
node.data.type = type;
}
return withJSDoc(finishNode(node, pos), hasJSDoc);
@ -7171,7 +7178,7 @@ namespace Parser {
token() === SyntaxKind.AsteriskToken ||
token() === SyntaxKind.OpenBracketToken
) {
const isAmbient = some(modifiers?.items, isAstDeclareKeyword);
const isAmbient = some(modifiers?.items, astIsDeclareKeyword);
if (isAmbient) {
for (const m of modifiers!.items) {
m.flags |= NodeFlags.Ambient;
@ -7222,7 +7229,7 @@ namespace Parser {
// We don't parse the name here in await context, instead we will report a grammar error in the checker.
const name = parseNameOfClassDeclarationOrExpression();
const typeParameters = parseTypeParameters();
if (some(modifiers?.items, isAstExportModifier)) setAwaitContext(/*value*/ true);
if (some(modifiers?.items, astIsExportModifier)) setAwaitContext(/*value*/ true);
const heritageClauses = parseHeritageClauses();
let members;
@ -8466,7 +8473,7 @@ namespace Parser {
case SyntaxKind.ArrayType:
return isObjectOrObjectArrayTypeReference((node as AstArrayTypeNode).data.elementType);
default:
return isAstTypeReferenceNode(node) && isAstIdentifier(node.data.typeName) && node.data.typeName.data.escapedText === "Object" && !node.data.typeArguments;
return astIsTypeReferenceNode(node) && astIsIdentifier(node.data.typeName) && node.data.typeName.data.escapedText === "Object" && !node.data.typeArguments;
}
}
@ -8516,7 +8523,7 @@ namespace Parser {
}
function parseReturnTag(start: number, tagName: AstIdentifier, indent: number, indentText: string): AstJSDocReturnTag {
if (some(tags, isAstJSDocReturnTag)) {
if (some(tags, astIsJSDocReturnTag)) {
parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.data.escapedText));
}
@ -8525,7 +8532,7 @@ namespace Parser {
}
function parseTypeTag(start: number, tagName: AstIdentifier, indent?: number, indentText?: string): AstJSDocTypeTag {
if (some(tags, isAstJSDocTypeTag)) {
if (some(tags, astIsJSDocTypeTag)) {
parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.data.escapedText));
}
@ -8790,8 +8797,8 @@ namespace Parser {
}
function escapedTextsEqual(a: AstEntityName, b: AstEntityName): boolean {
while (!isAstIdentifier(a) || !isAstIdentifier(b)) {
if (!isAstIdentifier(a) && !isAstIdentifier(b) && a.data.right.data.escapedText === b.data.right.data.escapedText) {
while (!astIsIdentifier(a) || !astIsIdentifier(b)) {
if (!astIsIdentifier(a) && !astIsIdentifier(b) && a.data.right.data.escapedText === b.data.right.data.escapedText) {
a = a.data.left;
b = b.data.left;
}
@ -8816,7 +8823,7 @@ namespace Parser {
const child = tryParseChildTag(target, indent);
if (
child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) &&
name && (isAstIdentifier(child.data.name) || !escapedTextsEqual(name, child.data.name.data.left))
name && (astIsIdentifier(child.data.name) || !escapedTextsEqual(name, child.data.name.data.left))
) {
return false;
}
@ -8893,7 +8900,7 @@ namespace Parser {
parseExpected(SyntaxKind.CloseBracketToken);
}
if (nodeIsMissing(name)) {
if (astNodeIsMissing(name)) {
return undefined;
}
return finishNode(factory.createTypeParameterDeclaration(modifiers, name, /*constraint*/ undefined, defaultType), typeParameterPos);
@ -9415,7 +9422,7 @@ namespace IncrementalParser {
}
function visit(child: AstNode) {
if (nodeIsMissing(child)) {
if (astNodeIsMissing(child)) {
// Missing nodes are effectively invisible to us. We never even consider them
// When trying to find the nearest node before us.
return;

Просмотреть файл

@ -0,0 +1,116 @@
function canonicalNumericIndexString(argument: string) {
if (argument === "-0") {
return -0;
}
const n = Number(argument);
if (String(n) === argument) {
return n;
}
return undefined;
}
function isValidIntegerIndex(argument: string | symbol) {
if (typeof argument === "string") {
const index = canonicalNumericIndexString(argument);
if (index !== undefined && Number.isInteger(index)) {
return true;
}
}
return false;
}
const readonlyArrayViewBrand = new WeakSet<object>();
const readonlyArrayViewData = new WeakMap<readonly unknown[], { source: readonly unknown[], mapper: (value: any) => any}>();
const readonlyArrayViewHandler: ProxyHandler<readonly unknown[]> = {
defineProperty(o, p, desc) {
if (p === "length" || isValidIntegerIndex(p)) {
const { source, mapper } = readonlyArrayViewData.get(o)!;
const existing = Reflect.getOwnPropertyDescriptor(source, p);
if (!existing) {
return false;
}
if (p !== "length") {
existing.value = mapper(existing.value);
}
return existing.get === desc.get &&
existing.set === desc.set &&
existing.configurable === desc.configurable &&
existing.enumerable === desc.enumerable &&
existing.writable === desc.writable &&
existing.value === desc.value;
}
return Reflect.defineProperty(o, p, desc);
},
getOwnPropertyDescriptor(o, p) {
const { source, mapper } = readonlyArrayViewData.get(o)!;
if (p === "length") {
return Reflect.getOwnPropertyDescriptor(source, p);
}
if (isValidIntegerIndex(p)) {
const existing = Reflect.getOwnPropertyDescriptor(source, p);
if (existing?.value !== undefined) {
existing.value = mapper(existing.value);
}
return existing;
}
return Reflect.getOwnPropertyDescriptor(o, p);
},
has(o, p) {
const { source } = readonlyArrayViewData.get(o)!;
if (p === "length" || isValidIntegerIndex(p)) {
return Reflect.has(source, p);
}
return Reflect.has(o, p);
},
get(o, p, receiver) {
const { source, mapper } = readonlyArrayViewData.get(o)!;
if (p === "length") {
return Reflect.get(source, p, receiver);
}
if (isValidIntegerIndex(p)) {
const value = Reflect.get(source, p, receiver);
return value !== undefined ? mapper(value) : value;
}
return Reflect.get(o, p, receiver);
},
set(o, p, v, receiver) {
if (p === "length" || isValidIntegerIndex(p)) {
return false;
}
return Reflect.set(o, p, v, receiver);
},
deleteProperty(o, p) {
if (p === "length" || isValidIntegerIndex(p)) {
return false;
}
return Reflect.deleteProperty(o, p);
},
preventExtensions(_o) {
return false;
},
};
/** @internal */
export interface ReadonlyArrayView<U> extends ReadonlyArray<U> {
_readonlyArrayViewBrand: any;
}
/** @internal */
export interface ReadonlyArrayViewConstructor {
new <T, U>(source: readonly T[], mapper: (value: T) => U): ReadonlyArrayView<U>;
isReadonlyArrayView(obj: unknown): obj is ReadonlyArrayView<unknown>;
}
/** @internal */
// eslint-disable-next-line local/only-arrow-functions
export const ReadonlyArrayView = function <T, U>(source: readonly T[], mapper: (value: T) => U) {
const array: readonly U[] = [];
const proxy = new Proxy<readonly any[]>(array, readonlyArrayViewHandler);
readonlyArrayViewData.set(array, { source, mapper });
readonlyArrayViewBrand.add(proxy);
return proxy;
} as unknown as ReadonlyArrayViewConstructor;
ReadonlyArrayView.isReadonlyArrayView = (obj): obj is ReadonlyArrayView<unknown> => {
return typeof obj === "object" && !!obj && readonlyArrayViewBrand.has(obj);
};

Просмотреть файл

@ -1,7 +1,8 @@
{
"extends": "../tsconfig-base",
"compilerOptions": {
"types": ["node"]
"types": ["node"],
"experimentalDecorators": true
},
"references": [],

Просмотреть файл

@ -209,7 +209,7 @@ import {
AstTryStatementData,
AstTupleTypeNodeData,
AstTypeAliasDeclarationData,
AstTypeAssertionData,
AstTypeAssertionExpressionData,
AstTypeLiteralNodeData,
AstTypeOfExpressionData,
AstTypeOperatorNodeData,
@ -315,6 +315,24 @@ import {
AstEntityNameExpression,
AstQuestionDotToken,
AstMemberName,
AstStringLiteralLike,
AstNumericLiteral,
AstObjectLiteralExpression,
AstBindableStaticNameExpression,
AstWrappedExpression,
AstNodeOneOf,
AstLeftHandSideExpression,
AstBindableStaticAccessExpression,
AstEntityName,
AstJSDocTypeExpression,
AstComputedPropertyName,
AstElementAccessExpression,
AstDeclaration,
AstModuleBlock,
AstStringLiteral,
astGetComment,
astSetComment,
AstJSDocUnknownTag,
} from "./_namespaces/ts.js";
// branded string type used to store absolute, normalized and canonicalized paths
@ -1254,12 +1272,12 @@ export class Node<
get pos(): number { return this.ast.pos; }
get end(): number { return this.ast.end; }
get flags(): NodeFlags { return this.ast.flags; }
get parent(): Node { return this.ast.parent?.node!; }
get parent(): Node { return this.ast.parent?.node; }
/** @internal */ set pos(value) { this.ast.pos = value; }
/** @internal */ set end(value) { this.ast.end = value; }
/** @internal */ set flags(value) { this.ast.flags = value; }
/** @internal */ set parent(value) { this.ast.parent = value?.ast; }
/** @internal */ set parent(value) { this.ast.parent = value?.ast as typeof this.ast.parent; }
/** @internal */ get modifierFlagsCache(): ModifierFlags { return this.ast.modifierFlagsCache; }
/** @internal */ set modifierFlagsCache(value) { this.ast.modifierFlagsCache = value; }
/** @internal */ get transformFlags(): TransformFlags { return this.ast.transformFlags; }
@ -1520,11 +1538,22 @@ export type HasFlowNode =
| TryStatement
| DebuggerStatement;
/** @internal */
export type HasEndFlowNode =
| MethodDeclaration
| ClassStaticBlockDeclaration
| ConstructorDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| FunctionExpression
| ArrowFunction
| FunctionDeclaration
| SourceFile;
// Ideally, `ForEachChildNodes` and `VisitEachChildNodes` would not differ.
// However, `forEachChild` currently processes JSDoc comment syntax and missing declarations more thoroughly.
// On the other hand, `visitEachChild` actually processes `Identifier`s (which really *shouldn't* have children,
// but are constructed as if they could for faked-up `QualifiedName`s in the language service.)
/** @internal */
export type ForEachChildNodes =
| HasChildren
@ -1794,7 +1823,20 @@ export type HasType =
| JSDocNonNullableType
| JSDocNullableType
| JSDocOptionalType
| JSDocVariadicType;
| JSDocVariadicType
| OptionalTypeNode
| RestTypeNode
| NamedTupleMember
| TemplateLiteralTypeSpan
| SatisfiesExpression
| JSDocNamepathType
| JSDocSignature;
/** @internal */
export type HasTypes =
| UnionTypeNode
| IntersectionTypeNode
| HeritageClause;
// NOTE: Changing the following list requires changes to:
// - `canHaveIllegalType` in factory/utilities.ts
@ -1803,6 +1845,29 @@ export type HasIllegalType =
| ConstructorDeclaration
| SetAccessorDeclaration;
/** @internal */
export type HasTypeParameters =
| ConstructorDeclaration
| SetAccessorDeclaration
| GetAccessorDeclaration
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| MethodSignature
| IndexSignatureDeclaration
| MethodDeclaration
| FunctionDeclaration
| JSDocSignature
| JSDocFunctionType
| FunctionTypeNode
| ConstructorTypeNode
| FunctionExpression
| ArrowFunction
| ClassExpression
| ClassDeclaration
| InterfaceDeclaration
| TypeAliasDeclaration
| JSDocTemplateTag;
// NOTE: Changing the following list requires changes to:
// - `canHaveIllegalTypeParameters` in factory/utilities.ts
/** @internal */
@ -1811,13 +1876,186 @@ export type HasIllegalTypeParameters =
| SetAccessorDeclaration
| GetAccessorDeclaration;
/** @internal */
export type HasParameters =
| ConstructorDeclaration
| SetAccessorDeclaration
| GetAccessorDeclaration
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| MethodSignature
| IndexSignatureDeclaration
| MethodDeclaration
| FunctionDeclaration
| JSDocSignature
| JSDocFunctionType
| FunctionTypeNode
| ConstructorTypeNode
| FunctionExpression
| ArrowFunction;
/** @internal */
export type HasBody =
| MethodDeclaration
| ClassStaticBlockDeclaration
| ConstructorDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| FunctionDeclaration
| FunctionExpression
| ArrowFunction
| ModuleDeclaration;
export type HasTypeArguments =
| CallExpression
| NewExpression
| TaggedTemplateExpression
| ExpressionWithTypeArguments
| TypeQueryNode
| ImportTypeNode
| TypeReferenceNode
| JsxOpeningElement
| JsxSelfClosingElement;
/** @internal */
export type InternalHasTypeArguments =
| HasTypeArguments
| MethodSignature
| MethodDeclaration
| ConstructorDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| IndexSignatureDeclaration
| FunctionTypeNode
| ConstructorTypeNode
| FunctionExpression
| ArrowFunction
| FunctionDeclaration
| JSDocFunctionType;
/** @internal */
export type HasElements =
| TupleTypeNode
| ObjectBindingPattern
| ArrayBindingPattern
| ArrayLiteralExpression
| ImportAttributes
| NamedImports
| NamedExports
| CommaListExpression;
/** @internal */
export type HasMembers =
| TypeLiteralNode
| MappedTypeNode
| ClassExpression
| ClassDeclaration
| InterfaceDeclaration
| EnumDeclaration;
/** @internal */
export type HasStatement =
| DoStatement
| WhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| WithStatement
| LabeledStatement;
/** @internal */
export type HasStatements =
| Block
| ModuleBlock
| CaseClause
| DefaultClause
| SourceFile;
/** @internal */
export type HasExclamationToken =
| MethodDeclaration
| PropertyAssignment
| PropertyDeclaration
| ShorthandPropertyAssignment
| VariableDeclaration;
/** @internal */
export type HasQuestionDotToken =
| PropertyAccessExpression
| ElementAccessExpression
| CallExpression
| TaggedTemplateExpression;
/** @internal */
export type HasTagName =
| JsxSelfClosingElement
| JsxOpeningElement
| JsxClosingElement
| JSDocUnknownTag
| JSDocAugmentsTag
| JSDocImplementsTag
| JSDocAuthorTag
| JSDocDeprecatedTag
| JSDocClassTag
| JSDocPublicTag
| JSDocPrivateTag
| JSDocProtectedTag
| JSDocReadonlyTag
| JSDocOverrideTag
| JSDocCallbackTag
| JSDocOverloadTag
| JSDocEnumTag
| JSDocParameterTag
| JSDocReturnTag
| JSDocThisTag
| JSDocTypedefTag
| JSDocSeeTag
| JSDocPropertyTag
| JSDocTemplateTag
| JSDocTypeTag
| JSDocThrowsTag
| JSDocSatisfiesTag
| JSDocImportTag;
/** @internal */
export type HasIsTypeOnly =
| ImportEqualsDeclaration
| ExportDeclaration
| ExportSpecifier
| ImportClause
| ImportSpecifier;
/** @internal */
export type HasComment =
| JSDoc
| JSDocUnknownTag
| JSDocAugmentsTag
| JSDocImplementsTag
| JSDocAuthorTag
| JSDocDeprecatedTag
| JSDocClassTag
| JSDocPublicTag
| JSDocPrivateTag
| JSDocProtectedTag
| JSDocReadonlyTag
| JSDocOverrideTag
| JSDocCallbackTag
| JSDocOverloadTag
| JSDocEnumTag
| JSDocParameterTag
| JSDocReturnTag
| JSDocThisTag
| JSDocTypeTag
| JSDocTemplateTag
| JSDocTypedefTag
| JSDocSeeTag
| JSDocPropertyTag
| JSDocThrowsTag
| JSDocSatisfiesTag
| JSDocImportTag;
export type HasInitializer =
| HasExpressionInitializer
| ForStatement
@ -1831,6 +2069,7 @@ export type HasExpressionInitializer =
| BindingElement
| PropertyDeclaration
| PropertyAssignment
| PropertySignature
| EnumMember;
/** @internal @knipignore */
@ -1910,6 +2149,80 @@ export type HasIllegalModifiers =
| MissingDeclaration
| NamespaceExportDeclaration;
/** @internal */
export type InternalHasModifiers =
| HasModifiers
| HasIllegalModifiers;
/** @internal */
export type HasSymbol =
| NumericLiteral
| StringLiteral
| NoSubstitutionTemplateLiteral
| Identifier
| TypeParameterDeclaration
| ParameterDeclaration
| PropertySignature
| PropertyDeclaration
| MethodSignature
| MethodDeclaration
| ClassStaticBlockDeclaration
| ConstructorDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| IndexSignatureDeclaration
| FunctionTypeNode
| ConstructorTypeNode
| TypeLiteralNode
| MappedTypeNode
| NamedTupleMember
| BindingElement
| ObjectLiteralExpression
| PropertyAccessExpression
| ElementAccessExpression
| CallExpression
| NewExpression
| FunctionExpression
| ArrowFunction
| BinaryExpression
| ClassExpression
| VariableDeclaration
| FunctionDeclaration
| ClassDeclaration
| InterfaceDeclaration
| TypeAliasDeclaration
| EnumDeclaration
| ModuleDeclaration
| NamespaceExportDeclaration
| ImportEqualsDeclaration
| ImportDeclaration
| ImportClause
| NamespaceImport
| ImportSpecifier
| ExportAssignment
| ExportDeclaration
| NamespaceExport
| ExportSpecifier
| MissingDeclaration
| JsxAttribute
| JsxAttributes
| SourceFile
| JSDocCallbackTag
| JSDocEnumTag
| JSDocFunctionType
| JSDocSignature
| JSDocTypedefTag
| PropertyAssignment
| ShorthandPropertyAssignment
| SpreadAssignment
| EnumMember
| JSDocParameterTag
| JSDocPropertyTag
| JSDocTypeLiteral
| NotEmittedTypeElement;
/** @internal */
export type PrimitiveLiteral =
| BooleanLiteral
@ -1920,6 +2233,21 @@ export type PrimitiveLiteral =
| PrefixUnaryExpression & { operator: SyntaxKind.PlusToken; operand: NumericLiteral; }
| PrefixUnaryExpression & { operator: SyntaxKind.MinusToken; operand: NumericLiteral | BigIntLiteral; };
/** @internal */
export type HasText =
| NumericLiteral
| BigIntLiteral
| StringLiteral
| RegularExpressionLiteral
| TemplateLiteralToken
| JsxText
| JSDocText
| JSDocLink
| JSDocLinkCode
| JSDocLinkPlain
| SourceFile
;
/**
* Declarations that can contain other declarations. Corresponds with `ContainerFlags.IsContainer` in binder.ts.
*
@ -2432,15 +2760,65 @@ export type HasName =
| JSDocPropertyTag
| MissingDeclaration;
// NOTE: Changing the following list requires changes to:
// - `astCanHaveExpression` in ast.ts
// - `astGetExpression` in ast.ts
/** @internal */
export interface DynamicNamedDeclaration extends NamedDeclaration {
readonly name: ComputedPropertyName;
}
export type HasExpression =
| ComputedPropertyName
| TypeParameterDeclaration
| Decorator
| PropertyAccessExpression
| ElementAccessExpression
| CallExpression
| NewExpression
| TypeAssertionExpression
| ParenthesizedExpression
| DeleteExpression
| TypeOfExpression
| VoidExpression
| AwaitExpression
| ForInStatement
| ForOfStatement
| ExpressionStatement
| IfStatement
| DoStatement
| WhileStatement
| YieldExpression
| SpreadElement
| ExpressionWithTypeArguments
| AsExpression
| NonNullExpression
| SatisfiesExpression
| TemplateSpan
| ReturnStatement
| WithStatement
| SwitchStatement
| ThrowStatement
| ExportAssignment
| ExternalModuleReference
| JsxSpreadAttribute
| JsxExpression
| CaseClause
| SpreadAssignment
| PartiallyEmittedExpression
| SyntheticReferenceExpression;
/** @internal */
export interface DynamicNamedBinaryExpression extends BinaryExpression {
export type DynamicNamedDeclaration = NamedDeclaration & {
readonly name: ComputedPropertyName;
readonly data: {
readonly name: AstComputedPropertyName;
};
};
/** @internal */
export type DynamicNamedBinaryExpression = BinaryExpression & {
readonly left: ElementAccessExpression;
}
readonly data: {
readonly left: AstElementAccessExpression;
};
};
/** @internal */
// A declaration that supports late-binding (used in checker)
@ -4304,10 +4682,14 @@ export class BinaryExpression extends Node<SyntaxKind.BinaryExpression, AstBinar
export type AssignmentOperatorToken = Token<AssignmentOperator>;
export interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
export type AssignmentExpression<TOperator extends AssignmentOperatorToken> = BinaryExpression & {
readonly left: LeftHandSideExpression;
readonly operatorToken: TOperator;
}
readonly data: {
readonly left: AstLeftHandSideExpression;
readonly operatorToken: TOperator;
};
};
export interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
readonly left: ObjectLiteralExpression;
@ -5050,7 +5432,7 @@ export class CallExpression extends Node<SyntaxKind.CallExpression, AstCallExpre
get questionDotToken(): QuestionDotToken | undefined { return this.ast.data.questionDotToken?.node; }
get typeArguments(): NodeArray<TypeNode> | undefined { return this.ast.data.typeArguments?.nodes; }
get arguments(): NodeArray<Expression> { return this.ast.data.arguments.nodes; }
/** @internal */ set expression(value) { this.ast.data.expression = value.ast; }
/** @internal */ set questionDotToken(value) { this.ast.data.questionDotToken = value?.ast; }
/** @internal */ set typeArguments(value) { this.ast.data.typeArguments = value?.ast; }
@ -5086,6 +5468,9 @@ export type OptionalChainRoot =
/** @internal */
export type BindableObjectDefinePropertyCall = CallExpression & {
readonly arguments: readonly [BindableStaticNameExpression, StringLiteralLike | NumericLiteral, ObjectLiteralExpression] & Readonly<TextRange>;
readonly data: {
readonly arguments: { readonly items: readonly [AstBindableStaticNameExpression, AstStringLiteralLike | AstNumericLiteral, AstObjectLiteralExpression]; } & Readonly<TextRange>
};
};
/** @internal */
@ -5096,16 +5481,25 @@ export type BindableStaticNameExpression =
/** @internal */
export type LiteralLikeElementAccessExpression = ElementAccessExpression & Declaration & {
readonly argumentExpression: StringLiteralLike | NumericLiteral;
readonly data: {
readonly argumentExpression: AstStringLiteralLike | AstNumericLiteral;
};
};
/** @internal */
export type BindableStaticElementAccessExpression = LiteralLikeElementAccessExpression & {
readonly expression: BindableStaticNameExpression;
readonly data: {
readonly expression: AstBindableStaticNameExpression;
};
};
/** @internal */
export type BindableElementAccessExpression = ElementAccessExpression & {
readonly expression: BindableStaticNameExpression;
readonly data: {
readonly expression: AstBindableStaticNameExpression;
};
};
/** @internal */
@ -5119,14 +5513,20 @@ export type BindableAccessExpression =
| BindableElementAccessExpression;
/** @internal */
export interface BindableStaticPropertyAssignmentExpression extends BinaryExpression {
export type BindableStaticPropertyAssignmentExpression = BinaryExpression & {
readonly left: BindableStaticAccessExpression;
}
readonly data: {
readonly left: AstBindableStaticAccessExpression;
};
};
/** @internal */
export interface BindablePropertyAssignmentExpression extends BinaryExpression {
export type BindablePropertyAssignmentExpression = BinaryExpression & {
readonly left: BindableAccessExpression;
}
readonly data: {
readonly left: AstBindableStaticAccessExpression;
};
};
// see: https://tc39.github.io/ecma262/#prod-SuperCall
export interface SuperCall extends CallExpression {
@ -5219,7 +5619,7 @@ export class AsExpression extends Node<SyntaxKind.AsExpression, AstAsExpressionD
}
// dprint-ignore
export class TypeAssertionExpression extends Node<SyntaxKind.TypeAssertionExpression, AstTypeAssertionData> implements UnaryExpression {
export class TypeAssertionExpression extends Node<SyntaxKind.TypeAssertionExpression, AstTypeAssertionExpressionData> implements UnaryExpression {
declare _unaryExpressionBrand: any;
declare _expressionBrand: any;
// declare readonly ast: AstTypeAssertion;
@ -6320,9 +6720,23 @@ export type ModuleBody =
// TODO(rbuckton): Move after ModuleDeclaration
/** @internal */
export interface AmbientModuleDeclaration extends ModuleDeclaration {
export type AmbientModuleDeclaration = ModuleDeclaration & {
readonly name: StringLiteral;
readonly body: ModuleBlock | undefined;
}
readonly data: {
readonly name: AstStringLiteral;
readonly body: AstModuleBlock | undefined;
};
};
// TODO(rbuckton): Move after ModuleDeclaration
/** @internal */
export type NonGlobalAmbientModuleDeclaration = AmbientModuleDeclaration & {
readonly name: StringLiteral;
readonly data: {
readonly name: AstStringLiteral;
};
};
// dprint-ignore
export class ModuleDeclaration extends Node<SyntaxKind.ModuleDeclaration, AstModuleDeclarationData> implements DeclarationStatement, JSDocContainer, LocalsContainer {
@ -6960,13 +7374,13 @@ export class JSDoc extends Node<SyntaxKind.JSDoc, AstJSDocData> {
get tags(): NodeArray<JSDocTag> | undefined { return this.ast.data.tags?.nodes; }
get comment(): string | NodeArray<JSDocComment> | undefined {
const comment = this.ast.data.comment;
const comment = astGetComment(this.ast);
return typeof comment === "string" ? comment : comment?.nodes;
}
/** @internal */ override set parent(value) { super.parent = value; }
/** @internal */ set tags(value) { this.ast.data.tags = value?.ast; }
/** @internal */ set comment(value) { this.ast.data.comment = typeof value === "string" ? value : value?.ast; }
/** @internal */ set comment(value) { astSetComment(this.ast, typeof value === "string" ? value : value?.ast); }
}
// TODO(rbuckton): Move after JSDocText
@ -6978,13 +7392,13 @@ export class JSDocTag<TKind extends SyntaxKind = SyntaxKind, T extends AstJSDocT
get tagName(): Identifier { return this.ast.data.tagName.node; }
get comment(): string | NodeArray<JSDocLink | JSDocLinkCode | JSDocLinkPlain | JSDocText> | undefined {
const comment = this.ast.data.comment;
const comment = astGetComment(this.ast);
return typeof comment === "string" ? comment : comment?.nodes;
}
/** @internal */ override set parent(value) { super.parent = value; }
/** @internal */ set tagName(value) { this.ast.data.tagName = value.ast; }
/** @internal */ set comment(value) { this.ast.data.comment = typeof value === "string" ? value : value?.ast; }
/** @internal */ set comment(value) { astSetComment(this.ast as AstJSDocUnknownTag, typeof value === "string" ? value : value?.ast); }
}
// dprint-ignore
@ -7277,13 +7691,18 @@ export class JSDocSignature extends Node<SyntaxKind.JSDocSignature, AstJSDocSign
export interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
// readonly ast: AstJSDocPropertyLikeTag;
readonly data: AstJSDocTagData & AstDeclarationData;
readonly parent: JSDoc;
readonly name: EntityName;
readonly typeExpression?: JSDocTypeExpression | undefined;
/** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
readonly isNameFirst: boolean;
readonly isBracketed: boolean;
readonly data: AstJSDocTagData & AstDeclarationData & {
readonly name: AstEntityName;
readonly typeExpression?: AstJSDocTypeExpression | undefined;
readonly isNameFirst: boolean;
readonly isBracketed: boolean;
};
}
// dprint-ignore
@ -7913,7 +8332,7 @@ export class SourceFile extends Node<SyntaxKind.SourceFile, AstSourceFileData> i
}
/** @internal */
export type PartialSourceFile<OptionalKeys extends keyof SourceFile = never> =
export type PartialSourceFile<OptionalKeys extends keyof SourceFile = never> =
& Pick<SourceFile, "fileName">
& Partial<Pick<SourceFile, OptionalKeys>>;
@ -9482,21 +9901,23 @@ export type SymbolId = number;
// dprint-ignore
export interface Symbol {
flags: SymbolFlags; // Symbol flags
escapedName: __String; // Name of symbol
declarations?: Declaration[]; // Declarations associated with this symbol
valueDeclaration?: Declaration; // First value declaration of the symbol
members?: SymbolTable; // Class, interface or object literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/** @internal */ id: SymbolId; // Unique id (used to look up SymbolLinks)
/** @internal */ mergeId: number; // Merge id (used to look up merged symbol)
/** @internal */ parent?: Symbol; // Parent symbol
/** @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
flags: SymbolFlags; // Symbol flags
escapedName: __String; // Name of symbol
readonly declarations?: readonly Declaration[]; // Declarations associated with this symbol
readonly valueDeclaration?: Declaration; // First value declaration of the symbol
members?: SymbolTable; // Class, interface or object literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/** @internal */ astValueDeclaration?: AstDeclaration; // Declarations associated with this symbol
/** @internal */ astDeclarations?: AstDeclaration[]; // First value declaration of the symbol
/** @internal */ id: SymbolId; // Unique id (used to look up SymbolLinks)
/** @internal */ mergeId: number; // Merge id (used to look up merged symbol)
/** @internal */ parent?: Symbol; // Parent symbol
/** @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
/** @internal */ constEnumOnlyModule: boolean | undefined; // True if module contains only const enums or other modules with only const enums
/** @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter.
/** @internal */ lastAssignmentPos?: number; // Source position of last node that assigns value to symbol. Negative if it is assigned anywhere definitely
/** @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
/** @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter.
/** @internal */ lastAssignmentPos?: number; // Source position of last node that assigns value to symbol. Negative if it is assigned anywhere definitely
/** @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
/** @internal */ assignmentDeclarationMembers?: Map<number, Declaration>; // detected late-bound assignment declarations associated with the symbol
}
@ -12082,7 +12503,7 @@ export type OuterExpression =
/** @internal */
export type WrappedExpression<T extends Expression> =
| OuterExpression & { readonly expression: WrappedExpression<T>; }
| OuterExpression & { readonly expression: WrappedExpression<T>; readonly data: { readonly expression: AstWrappedExpression<AstNodeOneOf<T>>; }; }
| T;
/** @internal */

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,6 +1,5 @@
import {
__String,
AccessExpression,
AccessorDeclaration,
ArrayBindingElement,
ArrayBindingOrAssignmentElement,
@ -11,7 +10,6 @@ import {
AssignmentPattern,
AutoAccessorPropertyDeclaration,
BinaryExpression,
BindableObjectDefinePropertyCall,
BindingElement,
BindingName,
BindingOrAssignmentElement,
@ -51,13 +49,11 @@ import {
Diagnostics,
diagnosticsEqualityComparer,
ElementAccessChain,
ElementAccessExpression,
emptyArray,
EntityName,
entityNameToString,
EnumDeclaration,
every,
ExportAssignment,
ExportDeclaration,
ExportSpecifier,
Expression,
@ -76,11 +72,9 @@ import {
GeneratedIdentifierFlags,
GeneratedPrivateIdentifier,
GetAccessorDeclaration,
getAssignmentDeclarationKind,
getDirectoryPath,
getEffectiveModifierFlags,
getEffectiveModifierFlagsAlwaysIncludeJSDoc,
getElementOrPropertyAccessArgumentExpressionOrName,
getEmitScriptTarget,
getJSDocCommentsAndTags,
getJSDocRoot,
@ -106,21 +100,17 @@ import {
ImportEqualsDeclaration,
ImportSpecifier,
ImportTypeNode,
isAccessExpression,
isAmbientModule,
isAnyImportOrReExport,
isArrowFunction,
isAssignmentExpression,
isBinaryExpression,
isBindableStaticAccessExpression,
isBindableStaticElementAccessExpression,
isBindableStaticNameExpression,
isBindingElement,
isBlock,
isCallExpression,
isCallSignatureDeclaration,
isClassExpression,
isClassStaticBlockDeclaration,
isDecorator,
isElementAccessExpression,
isExpandoPropertyDeclaration,
@ -163,7 +153,6 @@ import {
isParameter,
isPrivateIdentifier,
isPropertyAccessExpression,
isPropertyAssignment,
isPropertyDeclaration,
isPrototypeAccess,
isRootedDiskPath,
@ -296,6 +285,56 @@ import {
HasAsteriskToken,
AsteriskToken,
AstNode,
AstIdentifier,
AstPrivateIdentifier,
AstClassLikeDeclaration,
AstClassElement,
AstDeclaration,
AstExpression,
AstDeclarationName,
astIsFunctionExpression,
astIsArrowFunction,
astIsClassExpression,
AstJSDocPropertyLikeTag,
AstCallExpression,
AstBinaryExpression,
astGetAssignmentDeclarationKind,
astGetElementOrPropertyAccessArgumentExpressionOrName,
AstAccessExpression,
AstBindableObjectDefinePropertyCall,
AstJSDocTypedefTag,
AstJSDocEnumTag,
AstExportAssignment,
astIsIdentifier,
AstElementAccessExpression,
astIsBindableStaticElementAccessExpression,
astGetName,
AstNamedDeclaration,
astIsInJSFile,
astIsExpression,
AstPropertyAccessExpression,
astCanHaveJSDoc,
astGetJSDocCommentsAndTags,
AstParameterDeclaration,
AstTypeParameterDeclaration,
astIsPropertyAssignment,
astIsBindingElement,
astIsBinaryExpression,
astIsAccessExpression,
astIsVariableDeclaration,
AstAutoAccessorPropertyDeclaration,
astIsPropertyDeclaration,
astHasAccessorModifier,
AstModifierLike,
AstModifier,
astIsDecorator,
AstBindingElement,
AstVariableDeclaration,
AstSignatureDeclaration,
AstClassStaticBlockDeclaration,
astIsClassStaticBlockDeclaration,
isDeclarationName,
AstBindingPattern,
} from "./_namespaces/ts.js";
export function isExternalModuleNameRelative(moduleName: string): boolean {
@ -638,6 +677,15 @@ export function walkUpBindingElementsAndPatterns(binding: BindingElement): Varia
return node.parent;
}
/** @internal */
export function astWalkUpBindingElementsAndPatterns(binding: AstBindingElement): AstVariableDeclaration | AstParameterDeclaration {
let node = binding.parent;
while (astIsBindingElement(node.parent)) {
node = node.parent.parent;
}
return node.parent;
}
function getCombinedFlags(node: Node, getFlags: (n: Node) => number): number {
if (isBindingElement(node)) {
node = walkUpBindingElementsAndPatterns(node);
@ -656,6 +704,24 @@ function getCombinedFlags(node: Node, getFlags: (n: Node) => number): number {
return flags;
}
function astGetCombinedFlags(node: AstNode, getFlags: (n: AstNode) => number): number {
if (astIsBindingElement(node)) {
node = astWalkUpBindingElementsAndPatterns(node);
}
let flags = getFlags(node);
if (node.kind === SyntaxKind.VariableDeclaration) {
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableDeclarationList) {
flags |= getFlags(node);
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableStatement) {
flags |= getFlags(node);
}
return flags;
}
export function getCombinedModifierFlags(node: Declaration): ModifierFlags {
return getCombinedFlags(node, getEffectiveModifierFlags);
}
@ -673,10 +739,22 @@ export function getCombinedNodeFlagsAlwaysIncludeJSDoc(node: Declaration): Modif
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
export function getCombinedNodeFlags(node: Node): NodeFlags {
return getCombinedFlags(node, getNodeFlags);
return astGetCombinedNodeFlags(node.ast);
}
function getNodeFlags(node: Node) {
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
// (if it has one). Similarly, flags for let/const are stored on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
/** @internal */
export function astGetCombinedNodeFlags(node: AstNode): NodeFlags {
return astGetCombinedFlags(node, astGetNodeFlags);
}
function astGetNodeFlags(node: AstNode) {
return node.flags;
}
@ -872,12 +950,28 @@ export function idText(identifierOrPrivateName: Identifier | PrivateIdentifier):
return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
}
export function astIdText(identifierOrPrivateName: AstIdentifier | AstPrivateIdentifier): string {
// NOTE: each branch is duplicated to remain monomorphic
switch (identifierOrPrivateName.kind) {
case SyntaxKind.Identifier: return unescapeLeadingUnderscores(identifierOrPrivateName.data.escapedText);
case SyntaxKind.PrivateIdentifier: return unescapeLeadingUnderscores(identifierOrPrivateName.data.escapedText);
}
}
/**
* If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the
* SyntaxKind for the matching keyword.
*/
export function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined {
const token = stringToToken(node.escapedText as string);
return astIdentifierToKeywordKind(node.ast);
}
/**
* If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the
* SyntaxKind for the matching keyword.
*/
export function astIdentifierToKeywordKind(node: AstIdentifier): KeywordSyntaxKind | undefined {
const token = stringToToken(node.data.escapedText as string);
return token ? tryCast(token, isKeyword) : undefined;
}
@ -894,51 +988,60 @@ export function symbolName(symbol: Symbol): string {
* will be merged with)
*/
function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag): Identifier | PrivateIdentifier | undefined {
return astNameForNamelessJSDocTypedef(declaration.ast)?.node;
}
/**
* A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
* attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
* will be merged with)
*/
function astNameForNamelessJSDocTypedef(declaration: AstJSDocTypedefTag | AstJSDocEnumTag): AstIdentifier | AstPrivateIdentifier | undefined {
const hostNode = declaration.parent.parent;
if (!hostNode) {
return undefined;
}
// Covers classes, functions - any named declaration host node
if (isDeclaration(hostNode)) {
return getDeclarationIdentifier(hostNode);
if (astIsDeclaration(hostNode)) {
return astGetDeclarationIdentifier(hostNode);
}
// Covers remaining cases (returning undefined if none match).
switch (hostNode.kind) {
case SyntaxKind.VariableStatement:
if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
if (hostNode.data.declarationList?.data.declarations.items[0]) {
return astGetDeclarationIdentifier(hostNode.data.declarationList.data.declarations.items[0]);
}
break;
case SyntaxKind.ExpressionStatement:
let expr = hostNode.expression;
if (expr.kind === SyntaxKind.BinaryExpression && (expr as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
expr = (expr as BinaryExpression).left;
let expr = hostNode.data.expression;
if (expr.kind === SyntaxKind.BinaryExpression && (expr as AstBinaryExpression).data.operatorToken.kind === SyntaxKind.EqualsToken) {
expr = (expr as AstBinaryExpression).data.left;
}
switch (expr.kind) {
case SyntaxKind.PropertyAccessExpression:
return (expr as PropertyAccessExpression).name;
return (expr as AstPropertyAccessExpression).data.name;
case SyntaxKind.ElementAccessExpression:
const arg = (expr as ElementAccessExpression).argumentExpression;
if (isIdentifier(arg)) {
const arg = (expr as AstElementAccessExpression).data.argumentExpression;
if (astIsIdentifier(arg)) {
return arg;
}
}
break;
case SyntaxKind.ParenthesizedExpression: {
return getDeclarationIdentifier(hostNode.expression);
return astGetDeclarationIdentifier(hostNode.data.expression);
}
case SyntaxKind.LabeledStatement: {
if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
return getDeclarationIdentifier(hostNode.statement);
if (astIsDeclaration(hostNode.data.statement) || astIsExpression(hostNode.data.statement)) {
return astGetDeclarationIdentifier(hostNode.data.statement);
}
break;
}
}
}
function getDeclarationIdentifier(node: Declaration | Expression): Identifier | undefined {
const name = getNameOfDeclaration(node);
return name && isIdentifier(name) ? name : undefined;
function astGetDeclarationIdentifier(node: AstDeclaration | AstExpression): AstIdentifier | undefined {
const name = astGetNameOfDeclaration(node);
return name && astIsIdentifier(name) ? name : undefined;
}
/** @internal */
@ -956,6 +1059,10 @@ export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier
return declaration.name || nameForNamelessJSDocTypedef(declaration);
}
export function astGetNameOfJSDocTypedef(declaration: AstJSDocTypedefTag): AstIdentifier | AstPrivateIdentifier | undefined {
return declaration.data.name || astNameForNamelessJSDocTypedef(declaration);
}
/** @internal */
export function isNamedDeclaration(node: Node): node is NamedDeclaration & { name: DeclarationName; } {
return !!(node as NamedDeclaration).name; // A 'name' property should always be a DeclarationName.
@ -1055,49 +1162,73 @@ export function hasAsteriskToken(node: Node): node is HasAsteriskToken & { aster
/** @internal */
export function getNonAssignedNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined {
return astGetNonAssignedNameOfDeclaration(declaration.ast)?.node;
}
/** @internal */
export function astGetNonAssignedNameOfDeclaration(declaration: AstDeclaration | AstExpression): AstDeclarationName | undefined {
switch (declaration.kind) {
case SyntaxKind.Identifier:
return declaration as Identifier;
return declaration as AstIdentifier;
case SyntaxKind.JSDocPropertyTag:
case SyntaxKind.JSDocParameterTag: {
const { name } = declaration as JSDocPropertyLikeTag;
const { data: { name } } = declaration as AstJSDocPropertyLikeTag;
if (name.kind === SyntaxKind.QualifiedName) {
return name.right;
return name.data.right;
}
break;
}
case SyntaxKind.CallExpression:
case SyntaxKind.BinaryExpression: {
const expr = declaration as BinaryExpression | CallExpression;
switch (getAssignmentDeclarationKind(expr)) {
const expr = declaration as AstBinaryExpression | AstCallExpression;
switch (astGetAssignmentDeclarationKind(expr)) {
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ThisProperty:
case AssignmentDeclarationKind.Property:
case AssignmentDeclarationKind.PrototypeProperty:
return getElementOrPropertyAccessArgumentExpressionOrName((expr as BinaryExpression).left as AccessExpression);
return astGetElementOrPropertyAccessArgumentExpressionOrName((expr as AstBinaryExpression).data.left as AstAccessExpression);
case AssignmentDeclarationKind.ObjectDefinePropertyValue:
case AssignmentDeclarationKind.ObjectDefinePropertyExports:
case AssignmentDeclarationKind.ObjectDefinePrototypeProperty:
return (expr as BindableObjectDefinePropertyCall).arguments[1];
return (expr as AstBindableObjectDefinePropertyCall).data.arguments.items[1];
default:
return undefined;
}
}
case SyntaxKind.JSDocTypedefTag:
return getNameOfJSDocTypedef(declaration as JSDocTypedefTag);
return astGetNameOfJSDocTypedef(declaration as AstJSDocTypedefTag);
case SyntaxKind.JSDocEnumTag:
return nameForNamelessJSDocTypedef(declaration as JSDocEnumTag);
return astNameForNamelessJSDocTypedef(declaration as AstJSDocEnumTag);
case SyntaxKind.ExportAssignment: {
const { expression } = declaration as ExportAssignment;
return isIdentifier(expression) ? expression : undefined;
const { data: { expression } } = declaration as AstExportAssignment;
return astIsIdentifier(expression) ? expression : undefined;
}
case SyntaxKind.ElementAccessExpression:
const expr = declaration as ElementAccessExpression;
if (isBindableStaticElementAccessExpression(expr)) {
return expr.argumentExpression;
const expr = declaration as AstElementAccessExpression;
if (astIsBindableStaticElementAccessExpression(expr)) {
return expr.data.argumentExpression;
}
}
return (declaration as NamedDeclaration).name;
const name = astGetName(declaration);
if (name) {
Debug.type<AstDeclarationName>(name);
switch (name.kind) {
case SyntaxKind.NumericLiteral:
case SyntaxKind.BigIntLiteral:
case SyntaxKind.StringLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.Identifier:
case SyntaxKind.PrivateIdentifier:
case SyntaxKind.ComputedPropertyName:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.JsxNamespacedName:
return name;
default:
Debug.assertNeverTypeOnly(name);
}
}
return undefined;
}
export function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined {
@ -1106,24 +1237,39 @@ export function getNameOfDeclaration(declaration: Declaration | Expression | und
(isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
}
export function astGetNameOfDeclaration(declaration: AstDeclaration | AstExpression | undefined): AstDeclarationName | undefined {
if (declaration === undefined) return undefined;
return astGetNonAssignedNameOfDeclaration(declaration) ||
(astIsFunctionExpression(declaration) || astIsArrowFunction(declaration) || astIsClassExpression(declaration) ? astGetAssignedName(declaration) : undefined);
}
/** @internal */
export function getAssignedName(node: Node): DeclarationName | undefined {
return astGetAssignedName(node.ast)?.node;
}
/** @internal */
export function astGetAssignedName(node: AstNode): AstDeclarationName | undefined {
// NOTE: branches may be repeated to remain monomorphic
if (!node.parent) {
return undefined;
}
else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
return node.parent.name;
else if (astIsPropertyAssignment(node.parent)) {
return node.parent.data.name;
}
else if (isBinaryExpression(node.parent) && node === node.parent.right) {
if (isIdentifier(node.parent.left)) {
return node.parent.left;
else if (astIsBindingElement(node.parent)) {
return node.parent.data.name;
}
else if (astIsBinaryExpression(node.parent) && node === node.parent.data.right) {
if (astIsIdentifier(node.parent.data.left)) {
return node.parent.data.left;
}
else if (isAccessExpression(node.parent.left)) {
return getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
else if (astIsAccessExpression(node.parent.data.left)) {
return astGetElementOrPropertyAccessArgumentExpressionOrName(node.parent.data.left);
}
}
else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
return node.parent.name;
else if (astIsVariableDeclaration(node.parent) && astIsIdentifier(node.parent.data.name)) {
return node.parent.data.name;
}
}
@ -1139,16 +1285,16 @@ export function getModifiers(node: HasModifiers): readonly Modifier[] | undefine
}
}
function getJSDocParameterTagsWorker(param: ParameterDeclaration, noCache?: boolean): readonly JSDocParameterTag[] {
if (param.name) {
if (isIdentifier(param.name)) {
const name = param.name.escapedText;
return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name);
function astGetJSDocParameterTagsWorker(param: AstParameterDeclaration, noCache?: boolean): readonly JSDocParameterTag[] {
if (param.data.name) {
if (astIsIdentifier(param.data.name)) {
const name = param.data.name.data.escapedText;
return astGetJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name);
}
else {
const i = param.parent.parameters.indexOf(param);
const i = param.parent.data.parameters.items.indexOf(param);
Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
const paramTags = getJSDocTagsWorker(param.parent, noCache).filter(isJSDocParameterTag);
const paramTags = astGetJSDocTagsWorker(param.parent, noCache).filter(isJSDocParameterTag);
if (i < paramTags.length) {
return [paramTags[i]];
}
@ -1171,17 +1317,38 @@ function getJSDocParameterTagsWorker(param: ParameterDeclaration, noCache?: bool
* For binding patterns, parameter tags are matched by position.
*/
export function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[] {
return getJSDocParameterTagsWorker(param, /*noCache*/ false);
return astGetJSDocParameterTags(param.ast);
}
/**
* Gets the JSDoc parameter tags for the node if present.
*
* @remarks Returns any JSDoc param tag whose name matches the provided
* parameter, whether a param tag on a containing function
* expression, or a param tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the param
* tag on the containing function expression would be first.
*
* For binding patterns, parameter tags are matched by position.
*/
export function astGetJSDocParameterTags(param: AstParameterDeclaration): readonly JSDocParameterTag[] {
return astGetJSDocParameterTagsWorker(param, /*noCache*/ false);
}
/** @internal */
export function getJSDocParameterTagsNoCache(param: ParameterDeclaration): readonly JSDocParameterTag[] {
return getJSDocParameterTagsWorker(param, /*noCache*/ true);
return astGetJSDocParameterTagsNoCache(param.ast);
}
function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCache?: boolean): readonly JSDocTemplateTag[] {
const name = param.name.escapedText;
return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocTemplateTag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name));
/** @internal */
export function astGetJSDocParameterTagsNoCache(param: AstParameterDeclaration): readonly JSDocParameterTag[] {
return astGetJSDocParameterTagsWorker(param, /*noCache*/ true);
}
function astGetJSDocTypeParameterTagsWorker(param: AstTypeParameterDeclaration, noCache?: boolean): readonly JSDocTemplateTag[] {
const name = param.data.name.data.escapedText;
return astGetJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocTemplateTag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name));
}
/**
@ -1195,12 +1362,31 @@ function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCach
* tag on the containing function expression would be first.
*/
export function getJSDocTypeParameterTags(param: TypeParameterDeclaration): readonly JSDocTemplateTag[] {
return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
return astGetJSDocTypeParameterTags(param.ast);
}
/**
* Gets the JSDoc type parameter tags for the node if present.
*
* @remarks Returns any JSDoc template tag whose names match the provided
* parameter, whether a template tag on a containing function
* expression, or a template tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the template
* tag on the containing function expression would be first.
*/
export function astGetJSDocTypeParameterTags(param: AstTypeParameterDeclaration): readonly JSDocTemplateTag[] {
return astGetJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
}
/** @internal */
export function getJSDocTypeParameterTagsNoCache(param: TypeParameterDeclaration): readonly JSDocTemplateTag[] {
return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
return astGetJSDocTypeParameterTagsNoCache(param.ast);
}
/** @internal */
export function astGetJSDocTypeParameterTagsNoCache(param: AstTypeParameterDeclaration): readonly JSDocTemplateTag[] {
return astGetJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
}
/**
@ -1235,7 +1421,12 @@ export function getJSDocPublicTag(node: Node): JSDocPublicTag | undefined {
/** @internal */
export function getJSDocPublicTagNoCache(node: Node): JSDocPublicTag | undefined {
return getFirstJSDocTag(node, isJSDocPublicTag, /*noCache*/ true);
return astGetJSDocPublicTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocPublicTagNoCache(node: AstNode): JSDocPublicTag | undefined {
return astGetFirstJSDocTag(node, isJSDocPublicTag, /*noCache*/ true);
}
/** Gets the JSDoc private tag for the node if present */
@ -1245,7 +1436,12 @@ export function getJSDocPrivateTag(node: Node): JSDocPrivateTag | undefined {
/** @internal */
export function getJSDocPrivateTagNoCache(node: Node): JSDocPrivateTag | undefined {
return getFirstJSDocTag(node, isJSDocPrivateTag, /*noCache*/ true);
return astGetJSDocPrivateTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocPrivateTagNoCache(node: AstNode): JSDocPrivateTag | undefined {
return astGetFirstJSDocTag(node, isJSDocPrivateTag, /*noCache*/ true);
}
/** Gets the JSDoc protected tag for the node if present */
@ -1255,7 +1451,12 @@ export function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined
/** @internal */
export function getJSDocProtectedTagNoCache(node: Node): JSDocProtectedTag | undefined {
return getFirstJSDocTag(node, isJSDocProtectedTag, /*noCache*/ true);
return astGetJSDocProtectedTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocProtectedTagNoCache(node: AstNode): JSDocProtectedTag | undefined {
return astGetFirstJSDocTag(node, isJSDocProtectedTag, /*noCache*/ true);
}
/** Gets the JSDoc protected tag for the node if present */
@ -1265,11 +1466,26 @@ export function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined {
/** @internal */
export function getJSDocReadonlyTagNoCache(node: Node): JSDocReadonlyTag | undefined {
return getFirstJSDocTag(node, isJSDocReadonlyTag, /*noCache*/ true);
return astGetJSDocReadonlyTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocReadonlyTagNoCache(node: AstNode): JSDocReadonlyTag | undefined {
return astGetFirstJSDocTag(node, isJSDocReadonlyTag, /*noCache*/ true);
}
export function getJSDocOverrideTag(node: Node): JSDocOverrideTag | undefined {
return getFirstJSDocTag(node, isJSDocOverrideTag);
}
/** @internal */
export function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined {
return getFirstJSDocTag(node, isJSDocOverrideTag, /*noCache*/ true);
return astGetJSDocOverrideTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocOverrideTagNoCache(node: AstNode): JSDocOverrideTag | undefined {
return astGetFirstJSDocTag(node, isJSDocOverrideTag, /*noCache*/ true);
}
/** Gets the JSDoc deprecated tag for the node if present */
@ -1279,7 +1495,12 @@ export function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefine
/** @internal */
export function getJSDocDeprecatedTagNoCache(node: Node): JSDocDeprecatedTag | undefined {
return getFirstJSDocTag(node, isJSDocDeprecatedTag, /*noCache*/ true);
return astGetJSDocDeprecatedTagNoCache(node.ast);
}
/** @internal */
export function astGetJSDocDeprecatedTagNoCache(node: AstNode): JSDocDeprecatedTag | undefined {
return astGetFirstJSDocTag(node, isJSDocDeprecatedTag, /*noCache*/ true);
}
/** Gets the JSDoc enum tag for the node if present */
@ -1376,6 +1597,22 @@ function getJSDocTagsWorker(node: Node, noCache?: boolean): readonly JSDocTag[]
return tags;
}
function astGetJSDocTagsWorker(node: AstNode, noCache?: boolean): readonly JSDocTag[] {
if (!astCanHaveJSDoc(node)) return emptyArray;
let tags = node.data.jsDoc?.jsDocCache;
// If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
if (tags === undefined || noCache) {
const comments = astGetJSDocCommentsAndTags(node, noCache);
Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
tags = flatMap(comments, j => isJSDoc(j) ? j.tags : j);
if (!noCache) {
node.data.jsDoc ??= [];
node.data.jsDoc.jsDocCache = tags;
}
}
return tags;
}
/** Get all JSDoc tags related to a node, including those on parent nodes. */
export function getJSDocTags(node: Node): readonly JSDocTag[] {
return getJSDocTagsWorker(node, /*noCache*/ false);
@ -1383,7 +1620,12 @@ export function getJSDocTags(node: Node): readonly JSDocTag[] {
/** Get the first JSDoc tag of a specified kind, or undefined if not present. */
function getFirstJSDocTag<T extends JSDocTag>(node: Node, predicate: (tag: JSDocTag) => tag is T, noCache?: boolean): T | undefined {
return find(getJSDocTagsWorker(node, noCache), predicate);
return astGetFirstJSDocTag(node.ast, predicate, noCache);
}
/** Get the first JSDoc tag of a specified kind, or undefined if not present. */
function astGetFirstJSDocTag<T extends JSDocTag>(node: AstNode, predicate: (tag: JSDocTag) => tag is T, noCache?: boolean): T | undefined {
return find(astGetJSDocTagsWorker(node, noCache), predicate);
}
/** Gets all JSDoc tags that match a specified predicate */
@ -1750,6 +1992,11 @@ export function isClassMemberModifier(idToken: SyntaxKind): boolean {
}
export function isModifier(node: Node): node is Modifier {
return astIsModifier(node.ast);
}
/** @internal */
export function astIsModifier(node: AstNode): node is AstModifier {
return isModifierKind(node.kind);
}
@ -1781,9 +2028,17 @@ export function isFunctionLike(node: Node | undefined): node is SignatureDeclara
return !!node && isFunctionLikeKind(node.kind);
}
/** @internal */
/**
* @deprecated Use {@link astIsFunctionLikeOrClassStaticBlockDeclaration}
* @internal
*/
export function isFunctionLikeOrClassStaticBlockDeclaration(node: Node | undefined): node is SignatureDeclaration | ClassStaticBlockDeclaration {
return !!node && (isFunctionLikeKind(node.kind) || isClassStaticBlockDeclaration(node));
return astIsFunctionLikeOrClassStaticBlockDeclaration(node?.ast);
}
/** @internal */
export function astIsFunctionLikeOrClassStaticBlockDeclaration(node: AstNode | undefined): node is AstSignatureDeclaration | AstClassStaticBlockDeclaration {
return !!node && (isFunctionLikeKind(node.kind) || astIsClassStaticBlockDeclaration(node));
}
/** @internal */
@ -1835,6 +2090,11 @@ export function isFunctionOrModuleBlock(node: Node): boolean {
// Classes
export function isClassElement(node: Node): node is ClassElement {
return astIsClassElement(node.ast);
}
// Classes
export function astIsClassElement(node: AstNode): node is AstClassElement {
const kind = node.kind;
return kind === SyntaxKind.Constructor
|| kind === SyntaxKind.PropertyDeclaration
@ -1847,6 +2107,10 @@ export function isClassElement(node: Node): node is ClassElement {
}
export function isClassLike(node: Node): node is ClassLikeDeclaration {
return node && astIsClassLike(node.ast);
}
export function astIsClassLike(node: AstNode): node is AstClassLikeDeclaration {
return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression);
}
@ -1858,6 +2122,11 @@ export function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAcces
return isPropertyDeclaration(node) && hasAccessorModifier(node);
}
/** @internal */
export function astIsAutoAccessorPropertyDeclaration(node: AstNode): node is AstAutoAccessorPropertyDeclaration {
return astIsPropertyDeclaration(node) && astHasAccessorModifier(node);
}
/** @internal */
export function isClassInstanceProperty(node: Declaration): boolean {
if (isInJSFile(node) && isExpandoPropertyDeclaration(node)) {
@ -1881,7 +2150,12 @@ export function isMethodOrAccessor(node: Node): node is MethodDeclaration | Acce
// Type members
export function isModifierLike(node: Node): node is ModifierLike {
return isModifier(node) || isDecorator(node);
return astIsModifierLike(node.ast);
}
/** @intenral */
export function astIsModifierLike(node: AstNode): node is AstModifierLike {
return astIsModifier(node) || astIsDecorator(node);
}
export function isTypeElement(node: Node): node is TypeElement {
@ -1933,8 +2207,13 @@ export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTyp
// Binding patterns
/** @internal */
/** @deprecated @internal */
export function isBindingPattern(node: Node | undefined): node is BindingPattern {
return astIsBindingPattern(node?.ast);
}
/** @internal */
export function astIsBindingPattern(node: AstNode | undefined): node is AstBindingPattern {
if (node) {
const kind = node.kind;
return kind === SyntaxKind.ArrayBindingPattern
@ -2194,7 +2473,8 @@ export function isExpression(node: Node): node is Expression {
return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
}
function isExpressionKind(kind: SyntaxKind): boolean {
/** @internal */
export function isExpressionKind(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.ConditionalExpression:
case SyntaxKind.YieldExpression:
@ -2503,8 +2783,13 @@ function isStatementKindButNotDeclarationKind(kind: SyntaxKind) {
/** @internal */
export function isDeclaration(node: Node): node is NamedDeclaration {
return astIsDeclaration(node.ast);
}
/** @internal */
export function astIsDeclaration(node: AstNode): node is AstNamedDeclaration {
if (node.kind === SyntaxKind.TypeParameter) {
return (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || isInJSFile(node);
return (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || astIsInJSFile(node);
}
return isDeclarationKind(node.kind);
@ -2625,6 +2910,15 @@ export function isJSDocNode(node: Node): boolean {
return node.kind >= SyntaxKind.FirstJSDocNode && node.kind <= SyntaxKind.LastJSDocNode;
}
/**
* True if node is of some JSDoc syntax kind.
*
* @internal
*/
export function astIsJSDocNode(node: AstNode): boolean {
return node.kind >= SyntaxKind.FirstJSDocNode && node.kind <= SyntaxKind.LastJSDocNode;
}
/** True if node is of a kind that may contain comment text. */
export function isJSDocCommentContainingNode(node: Node): boolean {
return node.kind === SyntaxKind.JSDoc

Просмотреть файл

@ -13,7 +13,7 @@ import {
isArrayBindingElement,
isAssertClause,
isAssertsKeyword,
isAsteriskToken,
astIseriskToken,
isAwaitKeyword,
isBinaryOperatorToken,
isBindingElement,
@ -705,7 +705,7 @@ const visitEachChildTable: VisitEachChildTable = {
return context.factory.updateMethodDeclaration(
node,
nodesVisitor(node.modifiers, visitor, isModifierLike),
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, astIseriskToken) : node.asteriskToken,
Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
@ -1102,7 +1102,7 @@ const visitEachChildTable: VisitEachChildTable = {
return context.factory.updateFunctionExpression(
node,
nodesVisitor(node.modifiers, visitor, isModifier),
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, astIseriskToken) : node.asteriskToken,
nodeVisitor(node.name, visitor, isIdentifier),
nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList(node.parameters, visitor, context, nodesVisitor),
@ -1196,7 +1196,7 @@ const visitEachChildTable: VisitEachChildTable = {
[SyntaxKind.YieldExpression]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
return context.factory.updateYieldExpression(
node,
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, astIseriskToken) : node.asteriskToken,
nodeVisitor(node.expression, visitor, isExpression),
);
},
@ -1430,7 +1430,7 @@ const visitEachChildTable: VisitEachChildTable = {
return context.factory.updateFunctionDeclaration(
node,
nodesVisitor(node.modifiers, visitor, isModifier),
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, astIseriskToken) : node.asteriskToken,
nodeVisitor(node.name, visitor, isIdentifier),
nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList(node.parameters, visitor, context, nodesVisitor),

Просмотреть файл

@ -244,7 +244,7 @@ function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDo
}
/** @internal */
export function getJsDocTagsFromDeclarations(declarations?: Declaration[], checker?: TypeChecker): JSDocTagInfo[] {
export function getJsDocTagsFromDeclarations(declarations?: readonly Declaration[], checker?: TypeChecker): JSDocTagInfo[] {
// Only collect doc comments from duplicate declarations once.
const infos: JSDocTagInfo[] = [];
forEachUnique(declarations, declaration => {

Просмотреть файл

@ -299,6 +299,8 @@ import {
UnionType,
updateSourceFile,
UserPreferences,
AstDeclaration,
createReadOnlyArrayView,
} from "./_namespaces/ts.js";
import * as NavigateTo from "./_namespaces/ts.NavigateTo.js";
import * as NavigationBar from "./_namespaces/ts.NavigationBar.js";
@ -316,8 +318,9 @@ export const servicesVersion = "0.8";
class SymbolObject implements Symbol {
flags: SymbolFlags;
escapedName: __String;
declarations?: Declaration[];
valueDeclaration?: Declaration;
private _declarations: readonly Declaration[] | undefined = undefined;
astValueDeclaration: AstDeclaration | undefined = undefined;
astDeclarations: AstDeclaration[] | undefined = undefined;
members?: SymbolTable;
exports?: SymbolTable;
id: number;
@ -344,8 +347,6 @@ class SymbolObject implements Symbol {
// Note: if modifying this, be sure to update Symbol in src/compiler/types.ts
this.flags = flags;
this.escapedName = name;
this.declarations = undefined;
this.valueDeclaration = undefined;
this.id = 0;
this.mergeId = 0;
this.parent = undefined;
@ -358,6 +359,10 @@ class SymbolObject implements Symbol {
this.links = undefined; // used by TransientSymbol
}
get valueDeclaration() { return this.astValueDeclaration?.node; }
set valueDeclaration(value) { this.astValueDeclaration = value?.ast; }
get declarations() { return this._declarations ??= this.astDeclarations && createReadOnlyArrayView(this.astDeclarations, ast => ast.node); }
getFlags(): SymbolFlags {
return this.flags;
}
@ -374,7 +379,7 @@ class SymbolObject implements Symbol {
return this.name;
}
getDeclarations(): Declaration[] | undefined {
getDeclarations(): readonly Declaration[] | undefined {
return this.declarations;
}
@ -617,7 +622,7 @@ function hasJSDocInheritDocTag(node: Node) {
return getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc");
}
function getJsDocTagsOfDeclarations(declarations: Declaration[] | undefined, checker: TypeChecker | undefined): JSDocTagInfo[] {
function getJsDocTagsOfDeclarations(declarations: readonly Declaration[] | undefined, checker: TypeChecker | undefined): JSDocTagInfo[] {
if (!declarations) return emptyArray;
let tags = JsDoc.getJsDocTagsFromDeclarations(declarations, checker);

Просмотреть файл

@ -51,7 +51,7 @@ declare module "../compiler/types.js" {
getFlags(): SymbolFlags;
getEscapedName(): __String;
getName(): string;
getDeclarations(): Declaration[] | undefined;
getDeclarations(): readonly Declaration[] | undefined;
getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[];
/** @internal */
getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[];

Просмотреть файл

@ -5,7 +5,7 @@
"flags": "JSDoc",
"modifierFlagsCache": 0,
"transformFlags": 0,
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 0,
@ -89,7 +89,7 @@
"transformFlags": 0,
"escapedText": "param"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 70,
@ -164,7 +164,7 @@
"transformFlags": 0,
"escapedText": "param"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 113,
@ -404,7 +404,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 597,

Просмотреть файл

@ -21,7 +21,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 15,
@ -87,7 +87,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 178,
@ -119,7 +119,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 235,
@ -168,7 +168,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 346,
@ -200,7 +200,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 389,
@ -232,7 +232,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 406,
@ -264,7 +264,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 437,
@ -296,7 +296,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 453,
@ -328,7 +328,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 461,
@ -360,7 +360,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 469,
@ -392,7 +392,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 497,
@ -424,7 +424,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 510,
@ -456,7 +456,7 @@
"transformFlags": 0,
"escapedText": "author"
},
"comment": {
"commentArray": {
"0": {
"kind": "JSDocText",
"pos": 530,

184
tests/baselines/reference/api/typescript.d.ts поставляемый
Просмотреть файл

@ -4444,10 +4444,10 @@ declare namespace ts {
| ModuleBlock
| MissingDeclaration
| NotEmittedStatement;
export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType;
export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement;
export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType | OptionalTypeNode | RestTypeNode | NamedTupleMember | TemplateLiteralTypeSpan | SatisfiesExpression | JSDocNamepathType | JSDocSignature;
export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | ExpressionWithTypeArguments | TypeQueryNode | ImportTypeNode | TypeReferenceNode | JsxOpeningElement | JsxSelfClosingElement;
export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute;
export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | EnumMember;
export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | EnumMember;
export type HasDecorators = ParameterDeclaration | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression | ClassDeclaration;
export type HasModifiers = TypeParameterDeclaration | ParameterDeclaration | ConstructorTypeNode | PropertySignature | PropertyDeclaration | MethodSignature | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | IndexSignatureDeclaration | FunctionExpression | ArrowFunction | ClassExpression | VariableStatement | FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment | ExportDeclaration;
export class NodeArray<N extends Node> extends ReadonlyArray<N> {
@ -5239,10 +5239,14 @@ declare namespace ts {
get right(): Expression;
}
export type AssignmentOperatorToken = Token<AssignmentOperator>;
export interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
export type AssignmentExpression<TOperator extends AssignmentOperatorToken> = BinaryExpression & {
readonly left: LeftHandSideExpression;
readonly operatorToken: TOperator;
}
readonly data: {
readonly left: AstLeftHandSideExpression;
readonly operatorToken: TOperator;
};
};
export interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
readonly left: ObjectLiteralExpression;
}
@ -5586,7 +5590,7 @@ declare namespace ts {
get expression(): Expression;
get type(): TypeNode;
}
export class TypeAssertionExpression extends Node<SyntaxKind.TypeAssertionExpression, AstTypeAssertionData> implements UnaryExpression {
export class TypeAssertionExpression extends Node<SyntaxKind.TypeAssertionExpression, AstTypeAssertionExpressionData> implements UnaryExpression {
_unaryExpressionBrand: any;
_expressionBrand: any;
get type(): TypeNode;
@ -6417,13 +6421,18 @@ declare namespace ts {
get type(): JSDocReturnTag | undefined;
}
export interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
readonly data: AstJSDocTagData & AstDeclarationData;
readonly parent: JSDoc;
readonly name: EntityName;
readonly typeExpression?: JSDocTypeExpression | undefined;
/** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
readonly isNameFirst: boolean;
readonly isBracketed: boolean;
readonly data: AstJSDocTagData & AstDeclarationData & {
readonly name: AstEntityName;
readonly typeExpression?: AstJSDocTypeExpression | undefined;
readonly isNameFirst: boolean;
readonly isBracketed: boolean;
};
}
export class JSDocPropertyTag extends JSDocTag<SyntaxKind.JSDocPropertyTag, AstJSDocPropertyTagData> implements JSDocPropertyLikeTag, Declaration {
_declarationBrand: any;
@ -7126,8 +7135,8 @@ declare namespace ts {
export interface Symbol {
flags: SymbolFlags;
escapedName: __String;
declarations?: Declaration[];
valueDeclaration?: Declaration;
readonly declarations?: readonly Declaration[];
readonly valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
@ -7137,7 +7146,7 @@ declare namespace ts {
getFlags(): SymbolFlags;
getEscapedName(): __String;
getName(): string;
getDeclarations(): Declaration[] | undefined;
getDeclarations(): readonly Declaration[] | undefined;
getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[];
getJsDocTags(checker?: TypeChecker): JSDocTagInfo[];
}
@ -9024,7 +9033,7 @@ declare namespace ts {
private _extra;
readonly kind: N["kind"];
readonly data: N["data"];
parent: AstNode<NonNullable<N["parent"]>> | undefined;
parent: AstNodeOneOf<N["parent"]>;
flags: NodeFlags;
pos: number;
end: number;
@ -9405,6 +9414,7 @@ declare namespace ts {
type: AstTypeNode | undefined;
initializer: AstExpression | undefined;
}
export type AstVariableLikeDeclaration = AstNodeOneOf<VariableLikeDeclaration>;
export type AstVariableDeclarationList = AstNode<VariableDeclarationList>;
export class AstVariableDeclarationListData extends AstData {
declarations: AstNodeArray<AstVariableDeclaration>;
@ -9417,6 +9427,7 @@ declare namespace ts {
initializer: AstExpression | undefined;
}
export type AstPropertyDeclaration = AstNode<PropertyDeclaration>;
export type AstAutoAccessorPropertyDeclaration = AstNode<AutoAccessorPropertyDeclaration>;
export class AstPropertyDeclarationData extends AstData {
modifiers: AstNodeArray<AstModifierLike> | undefined;
name: AstPropertyName;
@ -9669,6 +9680,7 @@ declare namespace ts {
operatorToken: AstBinaryOperatorToken;
right: AstExpression;
}
export type AstAssignmentExpression<TOperator extends AssignmentOperatorToken> = AstNodeOneOf<AssignmentExpression<TOperator>>;
export type AstDestructuringAssignment = AstNodeOneOf<DestructuringAssignment>;
export class AstConditionalExpressionData extends AstData {
condition: AstExpression;
@ -9771,6 +9783,7 @@ declare namespace ts {
name: AstMemberName;
}
export type AstPropertyAccessEntityNameExpression = AstNode<PropertyAccessEntityNameExpression>;
export type AstAccessExpression = AstNodeOneOf<AccessExpression>;
export type AstEntityNameExpression = AstNodeOneOf<EntityNameExpression>;
export type AstPropertyAccessChain = AstNode<PropertyAccessChain>;
export class AstElementAccessExpressionData extends AstData {
@ -9806,7 +9819,7 @@ declare namespace ts {
expression: AstExpression;
type: AstTypeNode;
}
export class AstTypeAssertionData extends AstData {
export class AstTypeAssertionExpressionData extends AstData {
type: AstTypeNode;
expression: AstUnaryExpression;
}
@ -10164,7 +10177,8 @@ declare namespace ts {
type: AstTypeNode;
}
export class AstJSDocData extends AstData {
comment: string | AstNodeArray<AstJSDocComment> | undefined;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
tags: AstNodeArray<AstBaseJSDocTag> | undefined;
}
export type AstHasJSDoc = AstNodeOneOf<HasJSDoc>;
@ -10186,71 +10200,135 @@ declare namespace ts {
text: string;
}
export type AstBaseJSDocTag<TKind extends SyntaxKind = SyntaxKind, T extends AstJSDocTagData = AstJSDocTagData> = AstNode<JSDocTag<TKind, T>>;
export class AstJSDocTagData extends AstData {
tagName: AstIdentifier;
comment: string | AstNodeArray<AstJSDocComment> | undefined;
export abstract class AstJSDocTagData extends AstData {
abstract tagName: AstIdentifier;
abstract comment: string | undefined;
abstract commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocUnknownTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export type AstJSDocClassReference = AstNode<JSDocClassReference>;
export interface AstJSDocClassReferenceData extends AstExpressionWithTypeArgumentsData {
expression: AstIdentifier | AstPropertyAccessEntityNameExpression;
}
export class AstJSDocAugmentsTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
class: AstJSDocClassReference;
}
export class AstJSDocImplementsTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
class: AstJSDocClassReference;
}
export class AstJSDocAuthorTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocDeprecatedTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocClassTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocPublicTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocPrivateTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocProtectedTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocReadonlyTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocOverrideTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
}
export class AstJSDocEnumTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression;
}
export class AstJSDocThisTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression;
}
export class AstJSDocTemplateTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
constraint: AstJSDocTypeExpression | undefined;
typeParameters: AstNodeArray<AstTypeParameterDeclaration>;
}
export class AstJSDocSeeTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
name: AstJSDocNameReference | undefined;
}
export class AstJSDocReturnTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression | undefined;
}
export class AstJSDocTypeTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression;
}
export class AstJSDocTypedefTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression | AstJSDocTypeLiteral | undefined;
fullName: AstJSDocNamespaceDeclaration | AstIdentifier | undefined;
name: AstIdentifier | undefined;
}
export class AstJSDocCallbackTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
fullName: AstJSDocNamespaceDeclaration | AstIdentifier | undefined;
name: AstIdentifier | undefined;
typeExpression: AstJSDocSignature;
}
export class AstJSDocOverloadTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocSignature;
}
export class AstJSDocThrowsTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression | undefined;
}
export class AstJSDocSignatureData extends AstData {
@ -10259,6 +10337,9 @@ declare namespace ts {
type: AstJSDocReturnTag | undefined;
}
export class AstJSDocPropertyTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression | undefined;
name: AstEntityName;
/** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
@ -10266,6 +10347,9 @@ declare namespace ts {
isBracketed: boolean;
}
export class AstJSDocParameterTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression | undefined;
name: AstEntityName;
/** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
@ -10279,9 +10363,15 @@ declare namespace ts {
isArrayType: boolean;
}
export class AstJSDocSatisfiesTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
typeExpression: AstJSDocTypeExpression;
}
export class AstJSDocImportTagData extends AstJSDocTagData {
tagName: AstIdentifier;
comment: string | undefined;
commentArray: AstNodeArray<AstJSDocComment> | undefined;
importClause: AstImportClause | undefined;
moduleSpecifier: AstExpression;
attributes: AstImportAttributes | undefined;
@ -10350,7 +10440,6 @@ declare namespace ts {
impliedNodeFormat: ResolutionMode | undefined;
moduleName: string | undefined;
namedDeclarations: Map<string, Declaration[]> | undefined;
cloneNode(node: AstNode): AstNode;
}
export type AstMethodSignature = AstNode<MethodSignature>;
export type AstMethodDeclaration = AstNode<MethodDeclaration>;
@ -10587,6 +10676,7 @@ declare namespace ts {
>
>
: never;
export type AstNamedDeclaration = AstNodeOneOf<NamedDeclaration>;
export enum FileWatcherEventKind {
Created = 0,
Changed = 1,
@ -10801,14 +10891,22 @@ declare namespace ts {
*/
export function unescapeLeadingUnderscores(identifier: __String): string;
export function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string;
export function astIdText(identifierOrPrivateName: AstIdentifier | AstPrivateIdentifier): string;
/**
* If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the
* SyntaxKind for the matching keyword.
*/
export function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined;
/**
* If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the
* SyntaxKind for the matching keyword.
*/
export function astIdentifierToKeywordKind(node: AstIdentifier): KeywordSyntaxKind | undefined;
export function symbolName(symbol: Symbol): string;
export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined;
export function astGetNameOfJSDocTypedef(declaration: AstJSDocTypedefTag): AstIdentifier | AstPrivateIdentifier | undefined;
export function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined;
export function astGetNameOfDeclaration(declaration: AstDeclaration | AstExpression | undefined): AstDeclarationName | undefined;
export function getDecorators(node: HasDecorators): readonly Decorator[] | undefined;
export function getModifiers(node: HasModifiers): readonly Modifier[] | undefined;
/**
@ -10824,6 +10922,19 @@ declare namespace ts {
* For binding patterns, parameter tags are matched by position.
*/
export function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[];
/**
* Gets the JSDoc parameter tags for the node if present.
*
* @remarks Returns any JSDoc param tag whose name matches the provided
* parameter, whether a param tag on a containing function
* expression, or a param tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the param
* tag on the containing function expression would be first.
*
* For binding patterns, parameter tags are matched by position.
*/
export function astGetJSDocParameterTags(param: AstParameterDeclaration): readonly JSDocParameterTag[];
/**
* Gets the JSDoc type parameter tags for the node if present.
*
@ -10835,6 +10946,17 @@ declare namespace ts {
* tag on the containing function expression would be first.
*/
export function getJSDocTypeParameterTags(param: TypeParameterDeclaration): readonly JSDocTemplateTag[];
/**
* Gets the JSDoc type parameter tags for the node if present.
*
* @remarks Returns any JSDoc template tag whose names match the provided
* parameter, whether a template tag on a containing function
* expression, or a template tag on a variable declaration whose
* initializer is the containing function. The tags closest to the
* node are returned first, so in the previous example, the template
* tag on the containing function expression would be first.
*/
export function astGetJSDocTypeParameterTags(param: AstTypeParameterDeclaration): readonly JSDocTemplateTag[];
/**
* Return true if the node has JSDoc parameter tags.
*
@ -10856,7 +10978,7 @@ declare namespace ts {
export function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined;
/** Gets the JSDoc protected tag for the node if present */
export function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined;
export function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined;
export function getJSDocOverrideTag(node: Node): JSDocOverrideTag | undefined;
/** Gets the JSDoc deprecated tag for the node if present */
export function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined;
/** Gets the JSDoc enum tag for the node if present */
@ -10950,10 +11072,14 @@ declare namespace ts {
export function isBindingName(node: Node): node is BindingName;
export function isFunctionLike(node: Node | undefined): node is SignatureDeclaration;
export function isClassElement(node: Node): node is ClassElement;
export function astIsClassElement(node: AstNode): node is AstClassElement;
export function isClassLike(node: Node): node is ClassLikeDeclaration;
export function astIsClassLike(node: AstNode): node is AstClassLikeDeclaration;
export function isAccessor(node: Node): node is AccessorDeclaration;
export function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAccessorPropertyDeclaration;
export function isModifierLike(node: Node): node is ModifierLike;
/** @intenral */
export function astIsModifierLike(node: AstNode): node is AstModifierLike;
export function isTypeElement(node: Node): node is TypeElement;
export function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement;
export function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike;
@ -11030,6 +11156,26 @@ declare namespace ts {
* ```
*/
export function getJSDocCommentsAndTags(hostNode: Node): readonly (JSDoc | JSDocTag)[];
/**
* This function checks multiple locations for JSDoc comments that apply to a host node.
* At each location, the whole comment may apply to the node, or only a specific tag in
* the comment. In the first case, location adds the entire {@link JSDoc} object. In the
* second case, it adds the applicable {@link JSDocTag}.
*
* For example, a JSDoc comment before a parameter adds the entire {@link JSDoc}. But a
* `@param` tag on the parent function only adds the {@link JSDocTag} for the `@param`.
*
* ```ts
* /** JSDoc will be returned for `a` *\/
* const a = 0
* /**
* * Entire JSDoc will be returned for `b`
* * @param c JSDocTag will be returned for `c`
* *\/
* function b(/** JSDoc will be returned for `c` *\/ c) {}
* ```
*/
export function astGetJSDocCommentsAndTags(hostNode: AstNode): readonly (JSDoc | JSDocTag)[];
/**
* Create an external source map source file reference
*/
@ -11116,7 +11262,7 @@ declare namespace ts {
export function isDotDotDotToken(node: Node): node is DotDotDotToken;
export function isPlusToken(node: Node): node is PlusToken;
export function isMinusToken(node: Node): node is MinusToken;
export function isAsteriskToken(node: Node): node is AsteriskToken;
export function astIseriskToken(node: Node): node is AsteriskToken;
export function isExclamationToken(node: Node): node is ExclamationToken;
export function isQuestionToken(node: Node): node is QuestionToken;
export function isColonToken(node: Node): node is ColonToken;

Просмотреть файл

@ -15,7 +15,7 @@
- "flags": "JSDoc",
- "modifierFlagsCache": 0,
- "transformFlags": 0,
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 32,

Просмотреть файл

@ -15,7 +15,7 @@
- "flags": "JSDoc",
- "modifierFlagsCache": 0,
- "transformFlags": 0,
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 32,

Просмотреть файл

@ -15,7 +15,7 @@
- "flags": "JSDoc",
- "modifierFlagsCache": 0,
- "transformFlags": 0,
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 32,

Просмотреть файл

@ -93,7 +93,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 42,
@ -142,7 +142,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 60,
@ -191,7 +191,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 82,

Просмотреть файл

@ -93,7 +93,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 42,
@ -142,7 +142,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 60,
@ -191,7 +191,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 82,

Просмотреть файл

@ -93,7 +93,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 42,
@ -142,7 +142,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 60,
@ -191,7 +191,7 @@
- "transformFlags": 0,
- "escapedText": "see"
- },
- "comment": {
- "commentArray": {
- "0": {
- "kind": "JSDocText",
- "pos": 82,