diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 8838362c3c279..583e079cf0a47 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -62,6 +62,7 @@ import { readSourceFileLease, RemoteNode, RemoteSourceFile, + sourceFileDescriptor, } from "../node/node.ts"; import { Wtf8Decoder } from "../node/wtf8.ts"; import type { @@ -125,7 +126,6 @@ import type { ResolveTypeReferenceDirectiveResult, SignaturePropertyMethod, SignatureResponse, - SourceFileDescriptor, SourceFileMetadata, StaticModuleResolution, SymbolPropertyMethod, @@ -946,17 +946,6 @@ export class API implements FormatDiagnosticsHo type EnsureInitialized = () => Promise; // @sync: type EnsureInitialized = (() => void) & { gen(): Generator; }; -function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor { - return { - fileName: sourceFile.fileName, - path: sourceFile.path, - contentHash: sourceFile.contentHash, - parseOptionsKey: sourceFile.parseOptionsKey, - scriptKind: sourceFile.scriptKind, - nodeId: sourceFile.nodeId, - }; -} - /** Returns whether a node is backed by a remote compiler response. */ export function isRemoteNode(node: Node): boolean { return node instanceof RemoteNode; diff --git a/packages/typescript/src/api/node/node.ts b/packages/typescript/src/api/node/node.ts index c54b728cf3550..4429ff0f7dbe1 100644 --- a/packages/typescript/src/api/node/node.ts +++ b/packages/typescript/src/api/node/node.ts @@ -14,6 +14,7 @@ import { } from "../../ast/index.ts"; import type { API as AsyncAPI } from "../async/api.ts"; import { tryPathKeyFromCanonical } from "../path.ts"; +import type { SourceFileDescriptor } from "../proto.generated.ts"; import type { CachedSourceFile } from "../sourceFileCache.ts"; import type { API as SyncAPI } from "../sync/api.ts"; import type { TimingCollector } from "../timing.ts"; @@ -148,6 +149,11 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { return readSourceFileNodeId(this.view); } + /** @internal */ + get hasServerIdentity(): boolean { + return this.view.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, /*littleEndian*/ true) !== 0n; + } + /** * The file component of node handles sent to the server: `#` followed by the * server's identity for this exact source file. @@ -555,6 +561,30 @@ export function decodeNode(data: Uint8Array): Node { return sf; } +/** @internal */ +export function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor { + return { + fileName: sourceFile.fileName, + path: sourceFile.path, + contentHash: sourceFile.contentHash, + parseOptionsKey: sourceFile.parseOptionsKey, + scriptKind: sourceFile.scriptKind, + nodeId: sourceFile.nodeId, + }; +} + +/** + * Returns the server source file containing `node` and the node's index within it, + * or `undefined` if `node` was not decoded from a server source file. + * @internal + */ +export function getRemoteNodeLocation(node: Node): { sourceFile: RemoteSourceFile; index: number; } | undefined { + if (!(node instanceof RemoteNode)) return undefined; + const sourceFile = node["_sourceFile"]; + if (!(sourceFile instanceof RemoteSourceFile) || !sourceFile.hasServerIdentity) return undefined; + return { sourceFile, index: node["index"] }; +} + /** * Get the unique ID string for a remote node. * Throws if the node is not a RemoteNode (i.e. not decoded from binary data). diff --git a/packages/typescript/src/api/printer.ts b/packages/typescript/src/api/printer.ts index c5e2ccc986cc8..1bf5ba66a8876 100644 --- a/packages/typescript/src/api/printer.ts +++ b/packages/typescript/src/api/printer.ts @@ -1,12 +1,22 @@ import { EmitFlags } from "../../enums/emitFlags.js"; -import type { - Node, - SyntaxKind, +import { SyntaxKind } from "../../enums/syntaxKind.js"; +import { + getOriginalNode, + type Node, } from "../ast/index.ts"; import { encodeNode, uint8ArrayToBase64, } from "./node/encoder.ts"; +import { + getRemoteNodeLocation, + type RemoteSourceFile, + sourceFileDescriptor, +} from "./node/node.ts"; +import type { + PrintOriginalNode, + SourceFileDescriptor, +} from "./proto.generated.ts"; export interface PrintNodeOptions { preserveSourceNewlines?: boolean | undefined; @@ -43,12 +53,38 @@ export interface EmitContext { addSyntheticTrailingComment(node: Node, kind: CommentKind, text: string, hasTrailingNewLine: boolean, hasLeadingNewLine: boolean): Node; setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; getSyntheticTrailingComments(node: Node): readonly SynthesizedComment[] | undefined; + + /** + * Suppresses emission of the source comments before and after `node`. Comments inside the + * node are still emitted. `NoLeadingComments` and `NoTrailingComments` hide comments at a + * node's start and end, including those of descendants sharing that position, so the flags + * are also added to first and last descendants until one with a source position is reached. + */ + suppressLeadingAndTrailingComments(node: T): T; } /** @internal */ -export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): { data: string; emitNodes: Record | undefined; } { +export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): { + data: string; + emitNodes: Record | undefined; + originalFiles: SourceFileDescriptor[] | undefined; + originalNodes: Record | undefined; +} { let emitNodes: Record | undefined; + let originalFiles: SourceFileDescriptor[] | undefined; + let originalNodes: Record | undefined; + const fileIndices = new Map(); const encoded = encodeNode(node, (node, index) => { + const original = getOriginalNode(node); + const location = original !== node ? getRemoteNodeLocation(original) : undefined; + if (location) { + let file = fileIndices.get(location.sourceFile); + if (file === undefined) { + file = (originalFiles ??= []).push(sourceFileDescriptor(location.sourceFile)) - 1; + fileIndices.set(location.sourceFile, file); + } + (originalNodes ??= {})[index] = { file, index: location.index }; + } const emitNode = emitContext?.getEmitNode(node); if (emitNode === undefined) return; (emitNodes ??= {})[index] = { @@ -57,7 +93,7 @@ export function encodePrintNode(node: Node, emitContext: EmitContext | undefined trailingComments: emitNode.trailingComments?.map(c => ({ ...c })), }; }); - return { data: uint8ArrayToBase64(encoded), emitNodes }; + return { data: uint8ArrayToBase64(encoded), emitNodes, originalFiles, originalNodes }; } /** @internal */ @@ -108,5 +144,41 @@ export function createEmitContext(): EmitContext { getSyntheticTrailingComments(node) { return emitNodes.get(node)?.trailingComments; }, + + suppressLeadingAndTrailingComments(node) { + for (let n: Node | undefined = node; n; n = n.pos < 0 ? getFirstChild(n) : undefined) { + getOrCreateEmitNode(n).emitFlags |= EmitFlags.NoLeadingComments; + } + for (let n: Node | undefined = node; n; n = n.end < 0 ? getLastChild(n) : undefined) { + getOrCreateEmitNode(n).emitFlags |= EmitFlags.NoTrailingComments; + } + return node; + }, }; } + +function getFirstChild(node: Node): Node | undefined { + return node.forEachChild(child => child); +} + +function getLastChild(node: Node): Node | undefined { + let lastChild: Node | undefined; + node.forEachChild( + child => { + if (nodeIsPresent(child)) lastChild = child; + }, + children => { + for (let i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }, + ); + return lastChild; +} + +function nodeIsPresent(node: Node): boolean { + return node.pos !== node.end || node.pos < 0 || node.kind === SyntaxKind.EndOfFile; +} diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index fa535065ac824..c64307ae3d4a4 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -1238,6 +1238,10 @@ export interface PrintNodeParams { neverAsciiEscape?: boolean | undefined; terminateUnterminatedLiterals?: boolean | undefined; emitNodes?: Record | undefined; + /** OriginalFiles are the source files containing the nodes referenced by OriginalNodes. */ + originalFiles?: readonly SourceFileDescriptor[] | undefined; + /** OriginalNodes maps encoded node indices to the parsed nodes they were created from. */ + originalNodes?: Record | undefined; } export interface EmitParams { @@ -1957,6 +1961,15 @@ export interface PrintEmitNode { trailingComments?: PrintSynthesizedComment[] | undefined; } +/** + * PrintOriginalNode identifies a parsed node by the index of its source file in + * PrintNodeParams.OriginalFiles and its index within that file. + */ +export interface PrintOriginalNode { + file: number; + index: number; +} + export interface EmitOutputFile { fileName: RootedFilePath; text: string; diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5ff945800baac..e8ee246f8a652 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -81,6 +81,7 @@ import { readSourceFileLease, RemoteNode, RemoteSourceFile, + sourceFileDescriptor, } from "../node/node.ts"; import { Wtf8Decoder } from "../node/wtf8.ts"; import type { @@ -144,7 +145,6 @@ import type { ResolveTypeReferenceDirectiveResult, SignaturePropertyMethod, SignatureResponse, - SourceFileDescriptor, SourceFileMetadata, StaticModuleResolution, SymbolPropertyMethod, @@ -1555,17 +1555,6 @@ export class API implements FormatDiagnosticsHo type EnsureInitialized = (() => void) & { gen(): Generator; }; -function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor { - return { - fileName: sourceFile.fileName, - path: sourceFile.path, - contentHash: sourceFile.contentHash, - parseOptionsKey: sourceFile.parseOptionsKey, - scriptKind: sourceFile.scriptKind, - nodeId: sourceFile.nodeId, - }; -} - /** Returns whether a node is backed by a remote compiler response. */ export function isRemoteNode(node: Node): boolean { return node instanceof RemoteNode; diff --git a/packages/typescript/src/ast/clone.ts b/packages/typescript/src/ast/clone.ts index e224e39889186..4cf0c34911055 100644 --- a/packages/typescript/src/ast/clone.ts +++ b/packages/typescript/src/ast/clone.ts @@ -12,6 +12,7 @@ import { createNumericLiteral, createStringLiteral, } from "./factory.generated.ts"; +import { setOriginalNode } from "./utils.ts"; import { visitEachChild } from "./visitor.ts"; function isArray(value: any): value is readonly unknown[] { @@ -87,35 +88,23 @@ function setTextRange(node: T, range: ReadonlyTextRange | undefi /** * Creates a deep clone of a node and its subtree, synthesizing new nodes for every child. - * The resulting tree has fully set parent pointers. - * - * @param node The node to clone. - * @param includeTrivia Whether to preserve the text range (pos/end) on the clone. + * Every cloned node keeps the text range of the node it was cloned from, and the resulting + * tree has fully set parent pointers. */ -export function getSynthesizedDeepClone(node: T, includeTrivia?: boolean): T; -export function getSynthesizedDeepClone(node: T | undefined, includeTrivia?: boolean): T | undefined; -export function getSynthesizedDeepClone(node: T | undefined, includeTrivia = true): T | undefined { - const clone = node && getSynthesizedDeepCloneWorker(node); - if (clone && !includeTrivia) { - (clone as any).pos = -1; - (clone as any).end = -1; - } - return setParentRecursive(clone); +export function getSynthesizedDeepClone(node: T): T; +export function getSynthesizedDeepClone(node: T | undefined): T | undefined; +export function getSynthesizedDeepClone(node: T | undefined): T | undefined { + return setParentRecursive(node && getSynthesizedDeepCloneWorker(node)); } /** * Creates deep clones of a NodeArray and all its elements. */ -export function getSynthesizedDeepClones(nodes: NodeArray, includeTrivia?: boolean): NodeArray; -export function getSynthesizedDeepClones(nodes: NodeArray | undefined, includeTrivia?: boolean): NodeArray | undefined; -export function getSynthesizedDeepClones(nodes: NodeArray | undefined, includeTrivia = true): NodeArray | undefined { +export function getSynthesizedDeepClones(nodes: NodeArray): NodeArray; +export function getSynthesizedDeepClones(nodes: NodeArray | undefined): NodeArray | undefined; +export function getSynthesizedDeepClones(nodes: NodeArray | undefined): NodeArray | undefined { if (nodes) { - const cloned = createNodeArray( - nodes.map(n => getSynthesizedDeepClone(n, includeTrivia)), - nodes.pos, - nodes.end, - ); - return cloned; + return createNodeArray(nodes.map(n => getSynthesizedDeepClone(n)), nodes.pos, nodes.end); } return nodes; } @@ -131,7 +120,7 @@ function getSynthesizedDeepCloneWorker(node: T): T { : node.kind === SyntaxKind.NumericLiteral ? createNumericLiteral((node as Node as NumericLiteral).text, (node as Node as NumericLiteral).tokenFlags) as Node as T : cloneNode(node); - return setTextRange(clone, node); + return setOriginalNode(setTextRange(clone, node), node); } // visitEachChild already created a new node with visited children. diff --git a/packages/typescript/src/ast/factory.generated.ts b/packages/typescript/src/ast/factory.generated.ts index 85c3ea3029f74..916b01702f691 100644 --- a/packages/typescript/src/ast/factory.generated.ts +++ b/packages/typescript/src/ast/factory.generated.ts @@ -271,7 +271,10 @@ import { getModifiers, modifierToFlag, } from "./modifiers.ts"; -import { cloneSourceFileData } from "./utils.ts"; +import { + cloneSourceFileData, + setOriginalNode, +} from "./utils.ts"; import { forEachChildOfJSDocParameterTag, forEachChildOfJSDocPropertyTag, @@ -282,7 +285,7 @@ import { /** @internal */ export class NodeObject { readonly kind: SyntaxKind; - flags: NodeFlags = 0 as NodeFlags; + flags: NodeFlags = NodeFlags.Synthesized; readonly pos: number = -1; readonly end: number = -1; parent: Node = undefined!; @@ -791,13 +794,19 @@ export function createNodeArray(elements: readonly T[], pos: num return arr; } +function update(updated: T, original: T): T { + (updated as any).pos = original.pos; + (updated as any).end = original.end; + return setOriginalNode(updated, original); +} + export function cloneNode(node: T): T { const data = cloneNodeData(node); const clone = new NodeObject(node.kind, data); - (clone as any).flags = node.flags; + (clone as any).flags = node.flags | NodeFlags.Synthesized; (clone as any).pos = node.pos; (clone as any).end = node.end; - return clone as unknown as T; + return setOriginalNode(clone as unknown as T, node); } function cloneNodeData(node: Node): any { @@ -4137,7 +4146,7 @@ export function createVariableDeclarationList(declarations: readonly VariableDec const node = new NodeObject(SyntaxKind.VariableDeclarationList, { declarations: createNodeArray(declarations), }) as unknown as VariableDeclarationList; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -4555,7 +4564,7 @@ export function createPropertyAccessExpression(expression: Expression, questionD questionDotToken, name, }) as unknown as PropertyAccessExpression; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -4565,7 +4574,7 @@ export function createElementAccessExpression(expression: Expression, questionDo questionDotToken, argumentExpression, }) as unknown as ElementAccessExpression; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -4576,7 +4585,7 @@ export function createCallExpression(expression: Expression, questionDotToken: Q typeArguments: typeArguments ? createNodeArray(typeArguments) : undefined, arguments: createNodeArray(arguments_), }) as unknown as CallExpression; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -4599,7 +4608,7 @@ export function createNonNullExpression(expression: Expression, flags: NodeFlags const node = new NodeObject(SyntaxKind.NonNullExpression, { expression, }) as unknown as NonNullExpression; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -4630,7 +4639,7 @@ export function createTaggedTemplateExpression(tag: Expression, questionDotToken typeArguments: typeArguments ? createNodeArray(typeArguments) : undefined, template, }) as unknown as TaggedTemplateExpression; - (node as any).flags = flags; + (node as any).flags = flags | NodeFlags.Synthesized; return node; } @@ -5400,683 +5409,683 @@ export function createJSDocPropertyTag(tagName: Identifier, name: EntityName, is } export function updateQualifiedName(node: QualifiedName, left: EntityName, right: MemberName): QualifiedName { - return node.left !== left || node.right !== right ? createQualifiedName(left, right) : node; + return node.left !== left || node.right !== right ? update(createQualifiedName(left, right), node) : node; } export function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName { - return node.expression !== expression ? createComputedPropertyName(expression) : node; + return node.expression !== expression ? update(createComputedPropertyName(expression), node) : node; } export function updateDecorator(node: Decorator, expression: LeftHandSideExpression): Decorator { - return node.expression !== expression ? createDecorator(expression) : node; + return node.expression !== expression ? update(createDecorator(expression), node) : node; } export function updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement { - return node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement ? createIfStatement(expression, thenStatement, elseStatement) : node; + return node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement ? update(createIfStatement(expression, thenStatement, elseStatement), node) : node; } export function updateDoStatement(node: DoStatement, statement: Statement, expression: Expression): DoStatement { - return node.statement !== statement || node.expression !== expression ? createDoStatement(statement, expression) : node; + return node.statement !== statement || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node; } export function updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement { - return node.expression !== expression || node.statement !== statement ? createWhileStatement(expression, statement) : node; + return node.expression !== expression || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node; } export function updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement { - return node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement ? createForStatement(initializer, condition, incrementor, statement) : node; + return node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement ? update(createForStatement(initializer, condition, incrementor, statement), node) : node; } export function updateBreakStatement(node: BreakStatement, label?: Identifier): BreakStatement { - return node.label !== label ? createBreakStatement(label) : node; + return node.label !== label ? update(createBreakStatement(label), node) : node; } export function updateContinueStatement(node: ContinueStatement, label?: Identifier): ContinueStatement { - return node.label !== label ? createContinueStatement(label) : node; + return node.label !== label ? update(createContinueStatement(label), node) : node; } export function updateReturnStatement(node: ReturnStatement, expression?: Expression): ReturnStatement { - return node.expression !== expression ? createReturnStatement(expression) : node; + return node.expression !== expression ? update(createReturnStatement(expression), node) : node; } export function updateWithStatement(node: WithStatement, expression: Expression, statement: Statement): WithStatement { - return node.expression !== expression || node.statement !== statement ? createWithStatement(expression, statement) : node; + return node.expression !== expression || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node; } export function updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement { - return node.expression !== expression || node.caseBlock !== caseBlock ? createSwitchStatement(expression, caseBlock) : node; + return node.expression !== expression || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node; } export function updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock { - return node.clauses !== clauses ? createCaseBlock(clauses) : node; + return node.clauses !== clauses ? update(createCaseBlock(clauses), node) : node; } export function updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]): CaseClause { - return node.expression !== expression || node.statements !== statements ? createCaseClause(expression, statements) : node; + return node.expression !== expression || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node; } export function updateDefaultClause(node: DefaultClause, statements: readonly Statement[]): DefaultClause { - return node.statements !== statements ? createDefaultClause(statements) : node; + return node.statements !== statements ? update(createDefaultClause(statements), node) : node; } export function updateThrowStatement(node: ThrowStatement, expression: Expression): ThrowStatement { - return node.expression !== expression ? createThrowStatement(expression) : node; + return node.expression !== expression ? update(createThrowStatement(expression), node) : node; } export function updateTryStatement(node: TryStatement, tryBlock: Block, catchClause?: CatchClause, finallyBlock?: Block): TryStatement { - return node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock ? createTryStatement(tryBlock, catchClause, finallyBlock) : node; + return node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) : node; } export function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause { - return node.variableDeclaration !== variableDeclaration || node.block !== block ? createCatchClause(variableDeclaration, block) : node; + return node.variableDeclaration !== variableDeclaration || node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node; } export function updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement { - return node.label !== label || node.statement !== statement ? createLabeledStatement(label, statement) : node; + return node.label !== label || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node; } export function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement { - return node.expression !== expression ? createExpressionStatement(expression) : node; + return node.expression !== expression ? update(createExpressionStatement(expression), node) : node; } export function updateBlock(node: Block, statements: readonly Statement[]): Block { - return node.statements !== statements ? createBlock(statements, node.multiLine) : node; + return node.statements !== statements ? update(createBlock(statements, node.multiLine), node) : node; } export function updateVariableStatement(node: VariableStatement, modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList): VariableStatement { - return node.modifiers !== modifiers || node.declarationList !== declarationList ? createVariableStatement(modifiers, declarationList) : node; + return node.modifiers !== modifiers || node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node; } export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken?: ExclamationToken, type?: TypeNode, initializer?: Expression): VariableDeclaration { - return node.name !== name || node.exclamationToken !== exclamationToken || node.type !== type || node.initializer !== initializer ? createVariableDeclaration(name, exclamationToken, type, initializer) : node; + return node.name !== name || node.exclamationToken !== exclamationToken || node.type !== type || node.initializer !== initializer ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) : node; } export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList { - return node.declarations !== declarations ? createVariableDeclarationList(declarations, node.flags) : node; + return node.declarations !== declarations ? update(createVariableDeclarationList(declarations, node.flags), node) : node; } export function updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration { - return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer ? createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) : node; + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } export function updateBindingElement(node: BindingElement, dotDotDotToken?: DotDotDotToken, propertyName?: PropertyName, name?: BindingName, initializer?: Expression): BindingElement { - return node.dotDotDotToken !== dotDotDotToken || node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer ? createBindingElement(dotDotDotToken, propertyName, name, initializer) : node; + return node.dotDotDotToken !== dotDotDotToken || node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) : node; } export function updateMissingDeclaration(node: MissingDeclaration, modifiers?: readonly ModifierLike[]): MissingDeclaration { - return node.modifiers !== modifiers ? createMissingDeclaration(modifiers) : node; + return node.modifiers !== modifiers ? update(createMissingDeclaration(modifiers), node) : node; } export function updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode, body?: FunctionBody): FunctionDeclaration { - return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } export function updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } export function updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? createClassExpression(modifiers, name, typeParameters, heritageClauses, members) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } export function updateHeritageClause(node: HeritageClause, types: readonly HeritageClauseElement[]): HeritageClause { - return node.types !== types ? createHeritageClause(node.token, types) : node; + return node.types !== types ? update(createHeritageClause(node.token, types), node) : node; } export function updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type ? createTypeAliasDeclaration(modifiers, name, typeParameters, type) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } export function updateEnumMember(node: EnumMember, name: PropertyName, initializer?: Expression): EnumMember { - return node.name !== name || node.initializer !== initializer ? createEnumMember(name, initializer) : node; + return node.name !== name || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node; } export function updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.members !== members ? createEnumDeclaration(modifiers, name, members) : node; + return node.modifiers !== modifiers || node.name !== name || node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node; } export function updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock { - return node.statements !== statements ? createModuleBlock(statements) : node; + return node.statements !== statements ? update(createModuleBlock(statements), node) : node; } export function updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes): ImportDeclaration { - return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes) : node; + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node) : node; } export function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference { - return node.expression !== expression ? createExternalModuleReference(expression) : node; + return node.expression !== expression ? update(createExternalModuleReference(expression), node) : node; } export function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport { - return node.name !== name ? createNamespaceImport(name) : node; + return node.name !== name ? update(createNamespaceImport(name), node) : node; } export function updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports { - return node.elements !== elements ? createNamedImports(elements) : node; + return node.elements !== elements ? update(createNamedImports(elements), node) : node; } export function updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, type: TypeNode | undefined, expression: Expression): ExportAssignment { - return node.modifiers !== modifiers || node.type !== type || node.expression !== expression ? createExportAssignment(modifiers, node.isExportEquals, type, expression) : node; + return node.modifiers !== modifiers || node.type !== type || node.expression !== expression ? update(createExportAssignment(modifiers, node.isExportEquals, type, expression), node) : node; } export function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier): NamespaceExportDeclaration { - return node.modifiers !== modifiers || node.name !== name ? createNamespaceExportDeclaration(modifiers, name) : node; + return node.modifiers !== modifiers || node.name !== name ? update(createNamespaceExportDeclaration(modifiers, name), node) : node; } export function updateNamespaceExport(node: NamespaceExport, name: ModuleExportName): NamespaceExport { - return node.name !== name ? createNamespaceExport(name) : node; + return node.name !== name ? update(createNamespaceExport(name), node) : node; } export function updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports { - return node.elements !== elements ? createNamedExports(elements) : node; + return node.elements !== elements ? update(createNamedExports(elements), node) : node; } export function updateExportSpecifier(node: ExportSpecifier, propertyName: ModuleExportName | undefined, name: ModuleExportName): ExportSpecifier { - return node.propertyName !== propertyName || node.name !== name ? createExportSpecifier(node.isTypeOnly, propertyName, name) : node; + return node.propertyName !== propertyName || node.name !== name ? update(createExportSpecifier(node.isTypeOnly, propertyName, name), node) : node; } export function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode): CallSignatureDeclaration { - return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createCallSignatureDeclaration(typeParameters, parameters, type) : node; + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createCallSignatureDeclaration(typeParameters, parameters, type), node) : node; } export function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode): ConstructSignatureDeclaration { - return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createConstructSignatureDeclaration(typeParameters, parameters, type) : node; + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createConstructSignatureDeclaration(typeParameters, parameters, type), node) : node; } export function updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly ModifierLike[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode, body?: FunctionBody): ConstructorDeclaration { - return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createConstructorDeclaration(modifiers, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createConstructorDeclaration(modifiers, typeParameters, parameters, type, body), node) : node; } export function updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode, body?: FunctionBody): GetAccessorDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createGetAccessorDeclaration(modifiers, name, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createGetAccessorDeclaration(modifiers, name, typeParameters, parameters, type, body), node) : node; } export function updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode, body?: FunctionBody): SetAccessorDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createSetAccessorDeclaration(modifiers, name, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createSetAccessorDeclaration(modifiers, name, typeParameters, parameters, type, body), node) : node; } export function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode): IndexSignatureDeclaration { - return node.modifiers !== modifiers || node.parameters !== parameters || node.type !== type ? createIndexSignatureDeclaration(modifiers, parameters, type) : node; + return node.modifiers !== modifiers || node.parameters !== parameters || node.type !== type ? update(createIndexSignatureDeclaration(modifiers, parameters, type), node) : node; } export function updateMethodSignatureDeclaration(node: MethodSignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, postfixToken: QuestionToken | ExclamationToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode): MethodSignatureDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createMethodSignatureDeclaration(modifiers, name, postfixToken, typeParameters, parameters, type) : node; + return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createMethodSignatureDeclaration(modifiers, name, postfixToken, typeParameters, parameters, type), node) : node; } export function updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, postfixToken: QuestionToken | ExclamationToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type?: TypeNode, body?: FunctionBody): MethodDeclaration { - return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.postfixToken !== postfixToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createMethodDeclaration(modifiers, asteriskToken, name, postfixToken, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.postfixToken !== postfixToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createMethodDeclaration(modifiers, asteriskToken, name, postfixToken, typeParameters, parameters, type, body), node) : node; } export function updatePropertySignatureDeclaration(node: PropertySignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, postfixToken?: QuestionToken | ExclamationToken, type?: TypeNode, initializer?: Expression): PropertySignatureDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? createPropertySignatureDeclaration(modifiers, name, postfixToken, type, initializer) : node; + return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? update(createPropertySignatureDeclaration(modifiers, name, postfixToken, type, initializer), node) : node; } export function updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, postfixToken?: QuestionToken | ExclamationToken, type?: TypeNode, initializer?: Expression): PropertyDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? createPropertyDeclaration(modifiers, name, postfixToken, type, initializer) : node; + return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? update(createPropertyDeclaration(modifiers, name, postfixToken, type, initializer), node) : node; } export function updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, modifiers: readonly ModifierLike[] | undefined, body: Block): ClassStaticBlockDeclaration { - return node.modifiers !== modifiers || node.body !== body ? createClassStaticBlockDeclaration(modifiers, body) : node; + return node.modifiers !== modifiers || node.body !== body ? update(createClassStaticBlockDeclaration(modifiers, body), node) : node; } export function updateBinaryExpression(node: BinaryExpression, modifiers: readonly ModifierLike[] | undefined, left: Expression, type: TypeNode | undefined, operatorToken: BinaryOperatorToken, right: Expression): BinaryExpression { - return node.modifiers !== modifiers || node.left !== left || node.type !== type || node.operatorToken !== operatorToken || node.right !== right ? createBinaryExpression(modifiers, left, type, operatorToken, right) : node; + return node.modifiers !== modifiers || node.left !== left || node.type !== type || node.operatorToken !== operatorToken || node.right !== right ? update(createBinaryExpression(modifiers, left, type, operatorToken, right), node) : node; } export function updatePrefixUnaryExpression(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression { - return node.operand !== operand ? createPrefixUnaryExpression(node.operator, operand) : node; + return node.operand !== operand ? update(createPrefixUnaryExpression(node.operator, operand), node) : node; } export function updatePostfixUnaryExpression(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression { - return node.operand !== operand ? createPostfixUnaryExpression(operand, node.operator) : node; + return node.operand !== operand ? update(createPostfixUnaryExpression(operand, node.operator), node) : node; } export function updateYieldExpression(node: YieldExpression, asteriskToken?: AsteriskToken, expression?: Expression): YieldExpression { - return node.asteriskToken !== asteriskToken || node.expression !== expression ? createYieldExpression(asteriskToken, expression) : node; + return node.asteriskToken !== asteriskToken || node.expression !== expression ? update(createYieldExpression(asteriskToken, expression), node) : node; } export function updateArrowFunction(node: ArrowFunction, modifiers: readonly ModifierLike[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody): ArrowFunction { - return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body ? createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) : node; + return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body ? update(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } export function updateFunctionExpression(node: FunctionExpression, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: FunctionBody): FunctionExpression { - return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) : node; + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? update(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } export function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression { - return node.expression !== expression || node.type !== type ? createAsExpression(expression, type) : node; + return node.expression !== expression || node.type !== type ? update(createAsExpression(expression, type), node) : node; } export function updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression { - return node.expression !== expression || node.type !== type ? createSatisfiesExpression(expression, type) : node; + return node.expression !== expression || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node; } export function updateConditionalExpression(node: ConditionalExpression, condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression { - return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue || node.colonToken !== colonToken || node.whenFalse !== whenFalse ? createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) : node; + return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue || node.colonToken !== colonToken || node.whenFalse !== whenFalse ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } export function updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessExpression { - return node.expression !== expression || node.questionDotToken !== questionDotToken || node.name !== name ? createPropertyAccessExpression(expression, questionDotToken, name, node.flags) : node; + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.name !== name ? update(createPropertyAccessExpression(expression, questionDotToken, name, node.flags), node) : node; } export function updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression): ElementAccessExpression { - return node.expression !== expression || node.questionDotToken !== questionDotToken || node.argumentExpression !== argumentExpression ? createElementAccessExpression(expression, questionDotToken, argumentExpression, node.flags) : node; + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.argumentExpression !== argumentExpression ? update(createElementAccessExpression(expression, questionDotToken, argumentExpression, node.flags), node) : node; } export function updateCallExpression(node: CallExpression, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, arguments_: readonly Expression[]): CallExpression { - return node.expression !== expression || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.arguments !== arguments_ ? createCallExpression(expression, questionDotToken, typeArguments, arguments_, node.flags) : node; + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.arguments !== arguments_ ? update(createCallExpression(expression, questionDotToken, typeArguments, arguments_, node.flags), node) : node; } export function updateNewExpression(node: NewExpression, expression: Expression, typeArguments?: readonly TypeNode[], arguments_?: readonly Expression[]): NewExpression { - return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== arguments_ ? createNewExpression(expression, typeArguments, arguments_) : node; + return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== arguments_ ? update(createNewExpression(expression, typeArguments, arguments_), node) : node; } export function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty { - return node.name !== name ? createMetaProperty(node.keywordToken, name) : node; + return node.name !== name ? update(createMetaProperty(node.keywordToken, name), node) : node; } export function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression { - return node.expression !== expression ? createNonNullExpression(expression, node.flags) : node; + return node.expression !== expression ? update(createNonNullExpression(expression, node.flags), node) : node; } export function updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement { - return node.expression !== expression ? createSpreadElement(expression) : node; + return node.expression !== expression ? update(createSpreadElement(expression), node) : node; } export function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression { - return node.head !== head || node.templateSpans !== templateSpans ? createTemplateExpression(head, templateSpans) : node; + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node; } export function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddleOrTail): TemplateSpan { - return node.expression !== expression || node.literal !== literal ? createTemplateSpan(expression, literal) : node; + return node.expression !== expression || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node; } export function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression { - return node.tag !== tag || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.template !== template ? createTaggedTemplateExpression(tag, questionDotToken, typeArguments, template, node.flags) : node; + return node.tag !== tag || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.template !== template ? update(createTaggedTemplateExpression(tag, questionDotToken, typeArguments, template, node.flags), node) : node; } export function updateParenthesizedExpression(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression { - return node.expression !== expression ? createParenthesizedExpression(expression) : node; + return node.expression !== expression ? update(createParenthesizedExpression(expression), node) : node; } export function updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression { - return node.elements !== elements ? createArrayLiteralExpression(elements, node.multiLine) : node; + return node.elements !== elements ? update(createArrayLiteralExpression(elements, node.multiLine), node) : node; } export function updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression { - return node.properties !== properties ? createObjectLiteralExpression(properties, node.multiLine) : node; + return node.properties !== properties ? update(createObjectLiteralExpression(properties, node.multiLine), node) : node; } export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment { - return node.expression !== expression ? createSpreadAssignment(expression) : node; + return node.expression !== expression ? update(createSpreadAssignment(expression), node) : node; } export function updatePropertyAssignment(node: PropertyAssignment, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, postfixToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyAssignment { - return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? createPropertyAssignment(modifiers, name, postfixToken, type, initializer) : node; + return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.initializer !== initializer ? update(createPropertyAssignment(modifiers, name, postfixToken, type, initializer), node) : node; } export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, postfixToken?: QuestionToken | ExclamationToken, type?: TypeNode, equalsToken?: EqualsToken, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment { - return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.equalsToken !== equalsToken || node.objectAssignmentInitializer !== objectAssignmentInitializer ? createShorthandPropertyAssignment(modifiers, name, postfixToken, type, equalsToken, objectAssignmentInitializer) : node; + return node.modifiers !== modifiers || node.name !== name || node.postfixToken !== postfixToken || node.type !== type || node.equalsToken !== equalsToken || node.objectAssignmentInitializer !== objectAssignmentInitializer ? update(createShorthandPropertyAssignment(modifiers, name, postfixToken, type, equalsToken, objectAssignmentInitializer), node) : node; } export function updateDeleteExpression(node: DeleteExpression, expression: Expression): DeleteExpression { - return node.expression !== expression ? createDeleteExpression(expression) : node; + return node.expression !== expression ? update(createDeleteExpression(expression), node) : node; } export function updateTypeOfExpression(node: TypeOfExpression, expression: Expression): TypeOfExpression { - return node.expression !== expression ? createTypeOfExpression(expression) : node; + return node.expression !== expression ? update(createTypeOfExpression(expression), node) : node; } export function updateVoidExpression(node: VoidExpression, expression: Expression): VoidExpression { - return node.expression !== expression ? createVoidExpression(expression) : node; + return node.expression !== expression ? update(createVoidExpression(expression), node) : node; } export function updateAwaitExpression(node: AwaitExpression, expression: Expression): AwaitExpression { - return node.expression !== expression ? createAwaitExpression(expression) : node; + return node.expression !== expression ? update(createAwaitExpression(expression), node) : node; } export function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion { - return node.type !== type || node.expression !== expression ? createTypeAssertion(type, expression) : node; + return node.type !== type || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node; } export function updateUnionTypeNode(node: UnionTypeNode, types: readonly TypeNode[]): UnionTypeNode { - return node.types !== types ? createUnionTypeNode(types) : node; + return node.types !== types ? update(createUnionTypeNode(types), node) : node; } export function updateIntersectionTypeNode(node: IntersectionTypeNode, types: readonly TypeNode[]): IntersectionTypeNode { - return node.types !== types ? createIntersectionTypeNode(types) : node; + return node.types !== types ? update(createIntersectionTypeNode(types), node) : node; } export function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode { - return node.checkType !== checkType || node.extendsType !== extendsType || node.trueType !== trueType || node.falseType !== falseType ? createConditionalTypeNode(checkType, extendsType, trueType, falseType) : node; + return node.checkType !== checkType || node.extendsType !== extendsType || node.trueType !== trueType || node.falseType !== falseType ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) : node; } export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode { - return node.type !== type ? createTypeOperatorNode(node.operator, type) : node; + return node.type !== type ? update(createTypeOperatorNode(node.operator, type), node) : node; } export function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode { - return node.typeParameter !== typeParameter ? createInferTypeNode(typeParameter) : node; + return node.typeParameter !== typeParameter ? update(createInferTypeNode(typeParameter), node) : node; } export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { - return node.elementType !== elementType ? createArrayTypeNode(elementType) : node; + return node.elementType !== elementType ? update(createArrayTypeNode(elementType), node) : node; } export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode { - return node.objectType !== objectType || node.indexType !== indexType ? createIndexedAccessTypeNode(objectType, indexType) : node; + return node.objectType !== objectType || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; } export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments?: readonly TypeNode[]): TypeReferenceNode { - return node.typeName !== typeName || node.typeArguments !== typeArguments ? createTypeReferenceNode(typeName, typeArguments) : node; + return node.typeName !== typeName || node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node; } export function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments?: readonly TypeNode[]): ExpressionWithTypeArguments { - return node.expression !== expression || node.typeArguments !== typeArguments ? createExpressionWithTypeArguments(expression, typeArguments) : node; + return node.expression !== expression || node.typeArguments !== typeArguments ? update(createExpressionWithTypeArguments(expression, typeArguments), node) : node; } export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Node): LiteralTypeNode { - return node.literal !== literal ? createLiteralTypeNode(literal) : node; + return node.literal !== literal ? update(createLiteralTypeNode(literal), node) : node; } export function updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: TypePredicateParameterName, type?: TypeNode): TypePredicateNode { - return node.assertsModifier !== assertsModifier || node.parameterName !== parameterName || node.type !== type ? createTypePredicateNode(assertsModifier, parameterName, type) : node; + return node.assertsModifier !== assertsModifier || node.parameterName !== parameterName || node.type !== type ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) : node; } export function updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute { - return node.name !== name || node.value !== value ? createImportAttribute(name, value) : node; + return node.name !== name || node.value !== value ? update(createImportAttribute(name, value), node) : node; } export function updateImportAttributes(node: ImportAttributes, attributes: readonly ImportAttribute[]): ImportAttributes { - return node.attributes !== attributes ? createImportAttributes(node.token, attributes, node.multiLine) : node; + return node.attributes !== attributes ? update(createImportAttributes(node.token, attributes, node.multiLine), node) : node; } export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode { - return node.exprName !== exprName || node.typeArguments !== typeArguments ? createTypeQueryNode(exprName, typeArguments) : node; + return node.exprName !== exprName || node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node; } export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType?: TypeNode, questionToken?: QuestionToken | PlusToken | MinusToken, type?: TypeNode, members?: readonly TypeElement[]): MappedTypeNode { - return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type || node.members !== members ? createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) : node; + return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type || node.members !== members ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } export function updateTypeLiteralNode(node: TypeLiteralNode, members: readonly TypeElement[]): TypeLiteralNode { - return node.members !== members ? createTypeLiteralNode(members) : node; + return node.members !== members ? update(createTypeLiteralNode(members), node) : node; } export function updateTupleTypeNode(node: TupleTypeNode, elements: readonly TypeNode[]): TupleTypeNode { - return node.elements !== elements ? createTupleTypeNode(elements) : node; + return node.elements !== elements ? update(createTupleTypeNode(elements), node) : node; } export function updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember { - return node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type ? createNamedTupleMember(dotDotDotToken, name, questionToken, type) : node; + return node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) : node; } export function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode { - return node.type !== type ? createOptionalTypeNode(type) : node; + return node.type !== type ? update(createOptionalTypeNode(type), node) : node; } export function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode { - return node.type !== type ? createRestTypeNode(type) : node; + return node.type !== type ? update(createRestTypeNode(type), node) : node; } export function updateParenthesizedTypeNode(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode { - return node.type !== type ? createParenthesizedTypeNode(type) : node; + return node.type !== type ? update(createParenthesizedTypeNode(type), node) : node; } export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode { - return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createFunctionTypeNode(typeParameters, parameters, type) : node; + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } export function updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly ModifierLike[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode { - return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createConstructorTypeNode(modifiers, typeParameters, parameters, type) : node; + return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } export function updateTemplateLiteralTypeNode(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode { - return node.head !== head || node.templateSpans !== templateSpans ? createTemplateLiteralTypeNode(head, templateSpans) : node; + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralTypeNode(head, templateSpans), node) : node; } export function updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddleOrTail): TemplateLiteralTypeSpan { - return node.type !== type || node.literal !== literal ? createTemplateLiteralTypeSpan(type, literal) : node; + return node.type !== type || node.literal !== literal ? update(createTemplateLiteralTypeSpan(type, literal), node) : node; } export function updateSyntheticExpression(node: SyntheticExpression, tupleNameSource?: Node): SyntheticExpression { - return node.tupleNameSource !== tupleNameSource ? createSyntheticExpression(node.type, node.isSpread, tupleNameSource) : node; + return node.tupleNameSource !== tupleNameSource ? update(createSyntheticExpression(node.type, node.isSpread, tupleNameSource), node) : node; } export function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression { - return node.expression !== expression ? createPartiallyEmittedExpression(expression) : node; + return node.expression !== expression ? update(createPartiallyEmittedExpression(expression), node) : node; } export function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement { - return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement ? createJsxElement(openingElement, children, closingElement) : node; + return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement ? update(createJsxElement(openingElement, children, closingElement), node) : node; } export function updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes { - return node.properties !== properties ? createJsxAttributes(properties) : node; + return node.properties !== properties ? update(createJsxAttributes(properties), node) : node; } export function updateJsxNamespacedName(node: JsxNamespacedName, namespace: Identifier, name: Identifier): JsxNamespacedName { - return node.namespace !== namespace || node.name !== name ? createJsxNamespacedName(namespace, name) : node; + return node.namespace !== namespace || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node; } export function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement { - return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? createJsxOpeningElement(tagName, typeArguments, attributes) : node; + return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } export function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement { - return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? createJsxSelfClosingElement(tagName, typeArguments, attributes) : node; + return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } export function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment { - return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment ? createJsxFragment(openingFragment, children, closingFragment) : node; + return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment ? update(createJsxFragment(openingFragment, children, closingFragment), node) : node; } export function updateJsxAttribute(node: JsxAttribute, name: JsxAttributeName, initializer?: JsxAttributeValue): JsxAttribute { - return node.name !== name || node.initializer !== initializer ? createJsxAttribute(name, initializer) : node; + return node.name !== name || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node; } export function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute { - return node.expression !== expression ? createJsxSpreadAttribute(expression) : node; + return node.expression !== expression ? update(createJsxSpreadAttribute(expression), node) : node; } export function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement { - return node.tagName !== tagName ? createJsxClosingElement(tagName) : node; + return node.tagName !== tagName ? update(createJsxClosingElement(tagName), node) : node; } export function updateJsxExpression(node: JsxExpression, dotDotDotToken?: DotDotDotToken, expression?: Expression): JsxExpression { - return node.dotDotDotToken !== dotDotDotToken || node.expression !== expression ? createJsxExpression(dotDotDotToken, expression) : node; + return node.dotDotDotToken !== dotDotDotToken || node.expression !== expression ? update(createJsxExpression(dotDotDotToken, expression), node) : node; } export function updateSyntaxList(node: SyntaxList, children: readonly Node[]): SyntaxList { - return node.children !== children ? createSyntaxList(children) : node; + return node.children !== children ? update(createSyntaxList(children), node) : node; } export function updateJSDoc(node: JSDoc, comment: readonly JSDocComment[], tags?: readonly JSDocTag[]): JSDoc { - return node.comment !== comment || node.tags !== tags ? createJSDoc(comment, tags) : node; + return node.comment !== comment || node.tags !== tags ? update(createJSDoc(comment, tags), node) : node; } export function updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression { - return node.type !== type ? createJSDocTypeExpression(type) : node; + return node.type !== type ? update(createJSDocTypeExpression(type), node) : node; } export function updateJSDocNonNullableType(node: JSDocNonNullableType, type: TypeNode): JSDocNonNullableType { - return node.type !== type ? createJSDocNonNullableType(type) : node; + return node.type !== type ? update(createJSDocNonNullableType(type), node) : node; } export function updateJSDocNullableType(node: JSDocNullableType, type: TypeNode): JSDocNullableType { - return node.type !== type ? createJSDocNullableType(type) : node; + return node.type !== type ? update(createJSDocNullableType(type), node) : node; } export function updateJSDocVariadicType(node: JSDocVariadicType, type: TypeNode): JSDocVariadicType { - return node.type !== type ? createJSDocVariadicType(type) : node; + return node.type !== type ? update(createJSDocVariadicType(type), node) : node; } export function updateJSDocOptionalType(node: JSDocOptionalType, type: TypeNode): JSDocOptionalType { - return node.type !== type ? createJSDocOptionalType(type) : node; + return node.type !== type ? update(createJSDocOptionalType(type), node) : node; } export function updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier, typeExpression: Node, comment?: readonly JSDocComment[]): JSDocTypeTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocTypeTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocTypeTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocUnknownTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocUnknownTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; } export function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier, constraint: Node | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: readonly JSDocComment[]): JSDocTemplateTag { - return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? createJSDocTemplateTag(tagName, constraint, typeParameters, comment) : node; + return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node; } export function updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier, typeExpression?: TypeNode, comment?: readonly JSDocComment[]): JSDocReturnTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocReturnTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocReturnTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocPublicTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocPublicTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocPublicTag(tagName, comment), node) : node; } export function updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocPrivateTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocPrivateTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocPrivateTag(tagName, comment), node) : node; } export function updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocProtectedTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocProtectedTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocProtectedTag(tagName, comment), node) : node; } export function updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocReadonlyTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocReadonlyTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocReadonlyTag(tagName, comment), node) : node; } export function updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocOverrideTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocOverrideTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocOverrideTag(tagName, comment), node) : node; } export function updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: readonly JSDocComment[]): JSDocDeprecatedTag { - return node.tagName !== tagName || node.comment !== comment ? createJSDocDeprecatedTag(tagName, comment) : node; + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocDeprecatedTag(tagName, comment), node) : node; } export function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier, nameExpression?: TypeNode, comment?: readonly JSDocComment[]): JSDocSeeTag { - return node.tagName !== tagName || node.nameExpression !== nameExpression || node.comment !== comment ? createJSDocSeeTag(tagName, nameExpression, comment) : node; + return node.tagName !== tagName || node.nameExpression !== nameExpression || node.comment !== comment ? update(createJSDocSeeTag(tagName, nameExpression, comment), node) : node; } export function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier, className: TypeReferenceNode, comment?: readonly JSDocComment[]): JSDocImplementsTag { - return node.tagName !== tagName || node.className !== className || node.comment !== comment ? createJSDocImplementsTag(tagName, className, comment) : node; + return node.tagName !== tagName || node.className !== className || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node; } export function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier, className: TypeReferenceNode, comment?: readonly JSDocComment[]): JSDocAugmentsTag { - return node.tagName !== tagName || node.className !== className || node.comment !== comment ? createJSDocAugmentsTag(tagName, className, comment) : node; + return node.tagName !== tagName || node.className !== className || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; } export function updateJSDocSatisfiesTag(node: JSDocSatisfiesTag, tagName: Identifier, typeExpression: TypeNode, comment?: readonly JSDocComment[]): JSDocSatisfiesTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocSatisfiesTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocSatisfiesTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocThrowsTag(node: JSDocThrowsTag, tagName: Identifier, typeExpression?: TypeNode, comment?: readonly JSDocComment[]): JSDocThrowsTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocThrowsTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocThrowsTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier, typeExpression: TypeNode, comment?: readonly JSDocComment[]): JSDocThisTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocThisTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocThisTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocImportTag(node: JSDocImportTag, tagName: Identifier, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes, comment?: readonly JSDocComment[]): JSDocImportTag { - return node.tagName !== tagName || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes || node.comment !== comment ? createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment) : node; + return node.tagName !== tagName || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes || node.comment !== comment ? update(createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment), node) : node; } export function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier, typeExpression: TypeNode, name?: JSDocFullName, comment?: readonly JSDocComment[]): JSDocCallbackTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.name !== name || node.comment !== comment ? createJSDocCallbackTag(tagName, typeExpression, name, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.name !== name || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, name, comment), node) : node; } export function updateJSDocOverloadTag(node: JSDocOverloadTag, tagName: Identifier, typeExpression: TypeNode, comment?: readonly JSDocComment[]): JSDocOverloadTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocOverloadTag(tagName, typeExpression, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node; } export function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, name?: JSDocFullName, comment?: readonly JSDocComment[]): JSDocTypedefTag { - return node.tagName !== tagName || node.typeExpression !== typeExpression || node.name !== name || node.comment !== comment ? createJSDocTypedefTag(tagName, typeExpression, name, comment) : node; + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.name !== name || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, name, comment), node) : node; } export function updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly (JSDocParameterTag | JSDocThisTag)[], type?: JSDocReturnTag): JSDocSignature { - return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? createJSDocSignature(typeParameters, parameters, type) : node; + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createJSDocSignature(typeParameters, parameters, type), node) : node; } export function updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference { - return node.name !== name ? createJSDocNameReference(name) : node; + return node.name !== name ? update(createJSDocNameReference(name), node) : node; } export function updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly ModifierLike[] | undefined, name: ModuleName, attributes?: TypeLiteralNode, body?: ModuleBody): ModuleDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.attributes !== attributes || node.body !== body ? createModuleDeclaration(modifiers, node.keyword, name, attributes, body) : node; + return node.modifiers !== modifiers || node.name !== name || node.attributes !== attributes || node.body !== body ? update(createModuleDeclaration(modifiers, node.keyword, name, attributes, body), node) : node; } export function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.moduleReference !== moduleReference ? createImportEqualsDeclaration(modifiers, node.isTypeOnly, name, moduleReference) : node; + return node.modifiers !== modifiers || node.name !== name || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, node.isTypeOnly, name, moduleReference), node) : node; } export function updateExportDeclaration(node: ExportDeclaration, modifiers?: readonly ModifierLike[], exportClause?: NamedExportBindings, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration { - return node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? createExportDeclaration(modifiers, node.isTypeOnly, exportClause, moduleSpecifier, attributes) : node; + return node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createExportDeclaration(modifiers, node.isTypeOnly, exportClause, moduleSpecifier, attributes), node) : node; } export function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, attributes?: ImportAttributes, qualifier?: EntityName, typeArguments?: readonly TypeNode[]): ImportTypeNode { - return node.argument !== argument || node.attributes !== attributes || node.qualifier !== qualifier || node.typeArguments !== typeArguments ? createImportTypeNode(node.isTypeOf, argument, attributes, qualifier, typeArguments) : node; + return node.argument !== argument || node.attributes !== attributes || node.qualifier !== qualifier || node.typeArguments !== typeArguments ? update(createImportTypeNode(node.isTypeOf, argument, attributes, qualifier, typeArguments), node) : node; } export function updateImportClause(node: ImportClause, name?: Identifier, namedBindings?: NamedImportBindings): ImportClause { - return node.name !== name || node.namedBindings !== namedBindings ? createImportClause(node.phaseModifier, name, namedBindings) : node; + return node.name !== name || node.namedBindings !== namedBindings ? update(createImportClause(node.phaseModifier, name, namedBindings), node) : node; } export function updateImportSpecifier(node: ImportSpecifier, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier { - return node.propertyName !== propertyName || node.name !== name ? createImportSpecifier(node.isTypeOnly, propertyName, name) : node; + return node.propertyName !== propertyName || node.name !== name ? update(createImportSpecifier(node.isTypeOnly, propertyName, name), node) : node; } export function updateJSDocLink(node: JSDocLink, name?: EntityName): JSDocLink { - return node.name !== name ? createJSDocLink(name, node.text) : node; + return node.name !== name ? update(createJSDocLink(name, node.text), node) : node; } export function updateJSDocLinkPlain(node: JSDocLinkPlain, name?: EntityName): JSDocLinkPlain { - return node.name !== name ? createJSDocLinkPlain(name, node.text) : node; + return node.name !== name ? update(createJSDocLinkPlain(name, node.text), node) : node; } export function updateJSDocLinkCode(node: JSDocLinkCode, name?: EntityName): JSDocLinkCode { - return node.name !== name ? createJSDocLinkCode(name, node.text) : node; + return node.name !== name ? update(createJSDocLinkCode(name, node.text), node) : node; } export function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, constraint?: TypeNode, expression?: Expression, defaultType?: TypeNode): TypeParameterDeclaration { - return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint || node.expression !== expression || node.defaultType !== defaultType ? createTypeParameterDeclaration(modifiers, name, constraint, expression, defaultType) : node; + return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint || node.expression !== expression || node.defaultType !== defaultType ? update(createTypeParameterDeclaration(modifiers, name, constraint, expression, defaultType), node) : node; } export function updateSyntheticReferenceExpression(node: SyntheticReferenceExpression, expression: Expression, thisArg: Expression): SyntheticReferenceExpression { - return node.expression !== expression || node.thisArg !== thisArg ? createSyntheticReferenceExpression(expression, thisArg) : node; + return node.expression !== expression || node.thisArg !== thisArg ? update(createSyntheticReferenceExpression(expression, thisArg), node) : node; } export function updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsdocPropertyTags?: readonly JSDocTag[]): JSDocTypeLiteral { - return node.jsdocPropertyTags !== jsdocPropertyTags ? createJSDocTypeLiteral(jsdocPropertyTags, node.isArrayType) : node; + return node.jsdocPropertyTags !== jsdocPropertyTags ? update(createJSDocTypeLiteral(jsdocPropertyTags, node.isArrayType), node) : node; } export function updateForInStatement(node: ForInStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement { - return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? createForInStatement(awaitModifier, initializer, expression, statement) : node; + return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForInStatement(awaitModifier, initializer, expression, statement), node) : node; } export function updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement { - return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? createForOfStatement(awaitModifier, initializer, expression, statement) : node; + return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) : node; } export function updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]): ObjectBindingPattern { - return node.elements !== elements ? createObjectBindingPattern(elements) : node; + return node.elements !== elements ? update(createObjectBindingPattern(elements), node) : node; } export function updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly BindingElement[]): ArrayBindingPattern { - return node.elements !== elements ? createArrayBindingPattern(elements) : node; + return node.elements !== elements ? update(createArrayBindingPattern(elements), node) : node; } export function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier, name: EntityName, typeExpression: TypeNode | undefined, comment: readonly JSDocComment[] | undefined): JSDocParameterTag { - return node.tagName !== tagName || node.name !== name || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocParameterTag(tagName, name, node.isBracketed, typeExpression, node.isNameFirst, comment) : node; + return node.tagName !== tagName || node.name !== name || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, node.isBracketed, typeExpression, node.isNameFirst, comment), node) : node; } export function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier, name: EntityName, typeExpression: TypeNode | undefined, comment: readonly JSDocComment[] | undefined): JSDocPropertyTag { - return node.tagName !== tagName || node.name !== name || node.typeExpression !== typeExpression || node.comment !== comment ? createJSDocPropertyTag(tagName, name, node.isBracketed, typeExpression, node.isNameFirst, comment) : node; + return node.tagName !== tagName || node.name !== name || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, node.isBracketed, typeExpression, node.isNameFirst, comment), node) : node; } export function createSourceFile(statements: readonly Statement[], endOfFileToken: EndOfFile, text: string, fileName: RootedFilePath, path: PathKey): SourceFile { @@ -6104,6 +6113,6 @@ function cloneSourceFileWithChanges(source: SourceFile, statements: readonly Sta export function updateSourceFile(node: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile { return node.statements !== statements || node.endOfFileToken !== endOfFileToken - ? cloneSourceFileWithChanges(node, statements, endOfFileToken) + ? update(cloneSourceFileWithChanges(node, statements, endOfFileToken), node) : node; } diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index e4ea29af34439..4b8daa4f97534 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -58,6 +58,32 @@ export function formatSyntaxKind(kind: SyntaxKind): string { return getSyntaxKindNames().get(kind) ?? `Unknown(${kind})`; } +const originalNodes = new WeakMap(); + +/** + * Records `original` as the node that `node` was created from. Update and clone + * functions set this automatically. + */ +export function setOriginalNode(node: T, original: Node | undefined): T { + if (original && original !== node) { + originalNodes.set(node, original); + } + return node; +} + +/** + * Follows the chain of nodes recorded by {@link setOriginalNode} and returns the + * node at its root, or `node` itself if it has no original. + */ +export function getOriginalNode(node: Node): Node { + let original = originalNodes.get(node); + while (original) { + node = original; + original = originalNodes.get(node); + } + return node; +} + /** * Remove one extra leading underscore from an identifier name, recovering the * display form from its escaped {@link __String} key. diff --git a/packages/typescript/src/ast/visitor.ts b/packages/typescript/src/ast/visitor.ts index ff02521dd6a86..1b23356c85eda 100644 --- a/packages/typescript/src/ast/visitor.ts +++ b/packages/typescript/src/ast/visitor.ts @@ -97,8 +97,15 @@ export { yieldEachChildOfJSDocParameterOrPropertyTag as yieldEachChildOfJSDocPar function visitEachChildOfJSDocParameterOrPropertyTag(node: JSDocParameterOrPropertyTag, visitor: Visitor): JSDocParameterOrPropertyTag { const _tagName = visitNode(node.tagName, visitor, isIdentifier); - const _name = visitNode(node.name, visitor, isEntityName); - const _typeExpression = visitNode(node.typeExpression, visitor, isTypeNode); + let _name, _typeExpression; + if (node.isNameFirst) { + _name = visitNode(node.name, visitor, isEntityName); + _typeExpression = visitNode(node.typeExpression, visitor, isTypeNode); + } + else { + _typeExpression = visitNode(node.typeExpression, visitor, isTypeNode); + _name = visitNode(node.name, visitor, isEntityName); + } const _comment = visitNodes(node.comment, visitor); return node.kind === SyntaxKind.JSDocParameterTag ? updateJSDocParameterTag(node, _tagName, _name, _typeExpression, _comment) diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 48af4109dcfcc..223dbe6dc2637 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -7,10 +7,12 @@ import { getJSDocCommentsAndTags, getJSDocTags, getSynthesizedDeepClone, + getSynthesizedDeepClones, getTextOfJSDocComment, type Identifier, InternalSymbolName, isArrayLiteralExpression, + isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -50,6 +52,7 @@ import { type PathKey, type PropertyAccessExpression, type RootedFilePath, + type Statement, symbolName, SyntaxKind, TokenFlags, @@ -79,6 +82,9 @@ import { createVariableDeclaration, createVariableDeclarationList, createVariableStatement, + updateArrayLiteralExpression, + updateBinaryExpression, + updateExpressionStatement, updateSourceFile, } from "@typescript/typescript/ast/factory"; import { visitEachChild } from "@typescript/typescript/ast/visitor"; @@ -91,6 +97,7 @@ import { type CreateSnapshotParams, DiagnosticCategory, type DocumentIdentifier, + type EmitContext, EmitFlags, EmitOnly, type FormatDiagnosticsHost, @@ -9341,6 +9348,145 @@ export const obj = { m: 1, s: "hi", b: true }; assert.strictEqual(await api.printer.printFile(updated), expected); }); + test("updateSourceFile preserves the shebang", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "#!/usr/bin/env node\nfoo();\nbar();\n"); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1]], sourceFile.endOfFileToken); + const expected = "#!/usr/bin/env node\nbar();\n"; + + assert.strictEqual(await api.printer.printNode(updated), expected); + assert.strictEqual(await api.printer.printFile(updated), expected); + }); + + test("updated nodes keep their source comments exactly once", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "// leading\nfoo(1); // trailing\n/** doc */\nbaz();\n"); + const { sourceFile } = lease; + function rename(node: Node): Node { + if (node.kind === SyntaxKind.Identifier && (node as Identifier).text === "foo") return createIdentifier("bar"); + return visitEachChild(node, rename); + } + const updated = visitEachChild(sourceFile, rename); + assert.notStrictEqual(updated.statements[0], sourceFile.statements[0]); + + assert.strictEqual(await api.printer.printFile(updated), "// leading\nbar(1); // trailing\n/** doc */\nbaz();\n"); + + const emitContext = api.printer.createEmitContext(); + emitContext.setEmitFlags(updated.statements[0], EmitFlags.NoComments); + assert.strictEqual(await api.printer.printFile(updated, { emitContext }), "bar(1);\n/** doc */\nbaz();\n"); + }); + + test("getSynthesizedDeepClone keeps source comments exactly once", async () => { + await using api = spawnAPI(); + const text = "#!/usr/bin/env node\n// leading\nfoo(/* arg */ 1); // trailing\n/** doc */\nfunction f() {\n // inner\n return 1;\n}\n"; + await using lease = await api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + + assert.strictEqual(await api.printer.printFile(getSynthesizedDeepClone(sourceFile)), await api.printer.printFile(sourceFile)); + }); + + test("suppressLeadingAndTrailingComments keeps inner comments of a cloned node", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "// leading\nfoo(/* arg */ 1); // trailing\nbar();\n"); + const { sourceFile } = lease; + const printWithClone = async (clone: Statement, emitContext?: EmitContext) => api.printer.printFile(updateSourceFile(sourceFile, [sourceFile.statements[1], clone], sourceFile.endOfFileToken), { emitContext }); + + assert.strictEqual(await printWithClone(getSynthesizedDeepClone(sourceFile.statements[0])), "bar();\n// leading\nfoo(/* arg */ 1); // trailing\n"); + + const emitContext = api.printer.createEmitContext(); + const clone = emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(sourceFile.statements[0])); + assert.strictEqual(clone.pos, sourceFile.statements[0].pos); + assert.strictEqual(clone.end, sourceFile.statements[0].end); + assert.strictEqual(await printWithClone(clone, emitContext), "bar();\nfoo(/* arg */ 1);\n"); + }); + + test("suppressLeadingAndTrailingComments keeps comments inside delimiters", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "// leading\nfoo(1 /* keep */); // trailing\n{\n // keep\n foo();\n} // trailing\nbar();\n"); + const { sourceFile } = lease; + const emitContext = api.printer.createEmitContext(); + const clones = sourceFile.statements.slice(0, 2).map(s => emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(s))); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[2], ...clones], sourceFile.endOfFileToken); + assert.strictEqual(await api.printer.printFile(updated, { emitContext }), "bar();\nfoo(1 /* keep */);\n{\n // keep\n foo();\n}\n"); + }); + + test("suppressLeadingAndTrailingComments keeps comments before a function body's closing brace", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "function f() {\n foo();\n // keep\n} // trailing\nbar();\n"); + const { sourceFile } = lease; + const emitContext = api.printer.createEmitContext(); + const clone = emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(sourceFile.statements[0])); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1], clone], sourceFile.endOfFileToken); + assert.strictEqual(await api.printer.printFile(updated, { emitContext }), "bar();\nfunction f() {\n foo();\n // keep\n}\n"); + }); + + test("suppressLeadingAndTrailingComments reaches parsed children of created nodes", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "// leading\nfoo() /* trailing */;\nbar();\n"); + const { sourceFile } = lease; + const statement = sourceFile.statements[0]; + assert(isExpressionStatement(statement)); + const emitContext = api.printer.createEmitContext(); + const created = emitContext.suppressLeadingAndTrailingComments(createExpressionStatement(statement.expression)); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1], created], sourceFile.endOfFileToken); + assert.strictEqual(await api.printer.printFile(updated, { emitContext }), "bar();\nfoo();\n"); + }); + + test("deep clones keep comments next to tokens", async () => { + await using api = spawnAPI(); + const text = "function f() { return /* keep */ 1; }\n{ /* keep */ }\n"; + await using lease = await api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, getSynthesizedDeepClones(sourceFile.statements), sourceFile.endOfFileToken); + assert.strictEqual(await api.printer.printFile(updated), text); + }); + + test("printing clones of a released source file", async () => { + await using api = spawnAPI(); + const lease = await api.createSourceFile("/test.ts", "function f() { return /* keep */ 1; }\n"); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, getSynthesizedDeepClones(sourceFile.statements), sourceFile.endOfFileToken); + await lease.dispose(); + assert.match(await api.printer.printFile(updated), /^function f\(\) \{ return (\/\* keep \*\/ )?1; \}\n$/); + }); + + test("updated mixed ?? and || operands are parenthesized", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "a || b || c;\n"); + const { sourceFile } = lease; + const statement = sourceFile.statements[0]; + assert(isExpressionStatement(statement) && isBinaryExpression(statement.expression)); + const outer = statement.expression; + const inner = outer.left; + assert(isBinaryExpression(inner)); + const newInner = updateBinaryExpression(inner, /*modifiers*/ undefined, inner.left, /*type*/ undefined, createToken(SyntaxKind.QuestionQuestionToken), inner.right); + const newOuter = updateBinaryExpression(outer, /*modifiers*/ undefined, newInner, /*type*/ undefined, outer.operatorToken, outer.right); + const updated = updateSourceFile(sourceFile, [updateExpressionStatement(statement, newOuter)], sourceFile.endOfFileToken); + assert.strictEqual(newInner.pos, inner.pos); + assert.strictEqual(await api.printer.printFile(updated), "(a ?? b) || c;\n"); + }); + + test("updated nodes keep a trailing array hole", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "[1];\n[2,,];\n"); + const { sourceFile } = lease; + const [first, second] = sourceFile.statements; + assert(isExpressionStatement(first) && isArrayLiteralExpression(first.expression)); + assert(isExpressionStatement(second) && isArrayLiteralExpression(second.expression)); + const updated = updateSourceFile(sourceFile, [updateExpressionStatement(first, updateArrayLiteralExpression(first.expression, second.expression.elements))], sourceFile.endOfFileToken); + assert.strictEqual((await api.printer.printFile(updated)).replace(/\s/g, ""), "[2,,];"); + }); + + test("printing keeps comments in files with non-ASCII text", async () => { + await using api = spawnAPI(); + await using lease = await api.createSourceFile("/test.ts", "// é\nfoo(); // trailing\n"); + const { sourceFile } = lease; + assert.strictEqual(await api.printer.printFile(sourceFile), "// é\nfoo(); // trailing\n"); + const updated = updateSourceFile(sourceFile, [getSynthesizedDeepClone(sourceFile.statements[0])], sourceFile.endOfFileToken); + assert.strictEqual(await api.printer.printFile(updated), "// é\nfoo(); // trailing\n"); + }); + test("printFile", async () => { await using api = spawnAPI(emitterFiles); diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 60d31de065ac6..cdc3075d129f8 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -15,10 +15,12 @@ import { getJSDocCommentsAndTags, getJSDocTags, getSynthesizedDeepClone, + getSynthesizedDeepClones, getTextOfJSDocComment, type Identifier, InternalSymbolName, isArrayLiteralExpression, + isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -58,6 +60,7 @@ import { type PathKey, type PropertyAccessExpression, type RootedFilePath, + type Statement, symbolName, SyntaxKind, TokenFlags, @@ -87,6 +90,9 @@ import { createVariableDeclaration, createVariableDeclarationList, createVariableStatement, + updateArrayLiteralExpression, + updateBinaryExpression, + updateExpressionStatement, updateSourceFile, } from "@typescript/typescript/ast/factory"; import { visitEachChild } from "@typescript/typescript/ast/visitor"; @@ -113,6 +119,7 @@ import { type CreateSnapshotParams, DiagnosticCategory, type DocumentIdentifier, + type EmitContext, EmitFlags, EmitOnly, type FormatDiagnosticsHost, @@ -9099,6 +9106,145 @@ export const obj = { m: 1, s: "hi", b: true }; assert.strictEqual(api.printer.printFile(updated), expected); }); + test("updateSourceFile preserves the shebang", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "#!/usr/bin/env node\nfoo();\nbar();\n"); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1]], sourceFile.endOfFileToken); + const expected = "#!/usr/bin/env node\nbar();\n"; + + assert.strictEqual(api.printer.printNode(updated), expected); + assert.strictEqual(api.printer.printFile(updated), expected); + }); + + test("updated nodes keep their source comments exactly once", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "// leading\nfoo(1); // trailing\n/** doc */\nbaz();\n"); + const { sourceFile } = lease; + function rename(node: Node): Node { + if (node.kind === SyntaxKind.Identifier && (node as Identifier).text === "foo") return createIdentifier("bar"); + return visitEachChild(node, rename); + } + const updated = visitEachChild(sourceFile, rename); + assert.notStrictEqual(updated.statements[0], sourceFile.statements[0]); + + assert.strictEqual(api.printer.printFile(updated), "// leading\nbar(1); // trailing\n/** doc */\nbaz();\n"); + + const emitContext = api.printer.createEmitContext(); + emitContext.setEmitFlags(updated.statements[0], EmitFlags.NoComments); + assert.strictEqual(api.printer.printFile(updated, { emitContext }), "bar(1);\n/** doc */\nbaz();\n"); + }); + + test("getSynthesizedDeepClone keeps source comments exactly once", () => { + using api = spawnAPI(); + const text = "#!/usr/bin/env node\n// leading\nfoo(/* arg */ 1); // trailing\n/** doc */\nfunction f() {\n // inner\n return 1;\n}\n"; + using lease = api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + + assert.strictEqual(api.printer.printFile(getSynthesizedDeepClone(sourceFile)), api.printer.printFile(sourceFile)); + }); + + test("suppressLeadingAndTrailingComments keeps inner comments of a cloned node", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "// leading\nfoo(/* arg */ 1); // trailing\nbar();\n"); + const { sourceFile } = lease; + const printWithClone = (clone: Statement, emitContext?: EmitContext) => api.printer.printFile(updateSourceFile(sourceFile, [sourceFile.statements[1], clone], sourceFile.endOfFileToken), { emitContext }); + + assert.strictEqual(printWithClone(getSynthesizedDeepClone(sourceFile.statements[0])), "bar();\n// leading\nfoo(/* arg */ 1); // trailing\n"); + + const emitContext = api.printer.createEmitContext(); + const clone = emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(sourceFile.statements[0])); + assert.strictEqual(clone.pos, sourceFile.statements[0].pos); + assert.strictEqual(clone.end, sourceFile.statements[0].end); + assert.strictEqual(printWithClone(clone, emitContext), "bar();\nfoo(/* arg */ 1);\n"); + }); + + test("suppressLeadingAndTrailingComments keeps comments inside delimiters", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "// leading\nfoo(1 /* keep */); // trailing\n{\n // keep\n foo();\n} // trailing\nbar();\n"); + const { sourceFile } = lease; + const emitContext = api.printer.createEmitContext(); + const clones = sourceFile.statements.slice(0, 2).map(s => emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(s))); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[2], ...clones], sourceFile.endOfFileToken); + assert.strictEqual(api.printer.printFile(updated, { emitContext }), "bar();\nfoo(1 /* keep */);\n{\n // keep\n foo();\n}\n"); + }); + + test("suppressLeadingAndTrailingComments keeps comments before a function body's closing brace", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "function f() {\n foo();\n // keep\n} // trailing\nbar();\n"); + const { sourceFile } = lease; + const emitContext = api.printer.createEmitContext(); + const clone = emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(sourceFile.statements[0])); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1], clone], sourceFile.endOfFileToken); + assert.strictEqual(api.printer.printFile(updated, { emitContext }), "bar();\nfunction f() {\n foo();\n // keep\n}\n"); + }); + + test("suppressLeadingAndTrailingComments reaches parsed children of created nodes", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "// leading\nfoo() /* trailing */;\nbar();\n"); + const { sourceFile } = lease; + const statement = sourceFile.statements[0]; + assert(isExpressionStatement(statement)); + const emitContext = api.printer.createEmitContext(); + const created = emitContext.suppressLeadingAndTrailingComments(createExpressionStatement(statement.expression)); + const updated = updateSourceFile(sourceFile, [sourceFile.statements[1], created], sourceFile.endOfFileToken); + assert.strictEqual(api.printer.printFile(updated, { emitContext }), "bar();\nfoo();\n"); + }); + + test("deep clones keep comments next to tokens", () => { + using api = spawnAPI(); + const text = "function f() { return /* keep */ 1; }\n{ /* keep */ }\n"; + using lease = api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, getSynthesizedDeepClones(sourceFile.statements), sourceFile.endOfFileToken); + assert.strictEqual(api.printer.printFile(updated), text); + }); + + test("printing clones of a released source file", () => { + using api = spawnAPI(); + const lease = api.createSourceFile("/test.ts", "function f() { return /* keep */ 1; }\n"); + const { sourceFile } = lease; + const updated = updateSourceFile(sourceFile, getSynthesizedDeepClones(sourceFile.statements), sourceFile.endOfFileToken); + lease.dispose(); + assert.match(api.printer.printFile(updated), /^function f\(\) \{ return (\/\* keep \*\/ )?1; \}\n$/); + }); + + test("updated mixed ?? and || operands are parenthesized", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "a || b || c;\n"); + const { sourceFile } = lease; + const statement = sourceFile.statements[0]; + assert(isExpressionStatement(statement) && isBinaryExpression(statement.expression)); + const outer = statement.expression; + const inner = outer.left; + assert(isBinaryExpression(inner)); + const newInner = updateBinaryExpression(inner, /*modifiers*/ undefined, inner.left, /*type*/ undefined, createToken(SyntaxKind.QuestionQuestionToken), inner.right); + const newOuter = updateBinaryExpression(outer, /*modifiers*/ undefined, newInner, /*type*/ undefined, outer.operatorToken, outer.right); + const updated = updateSourceFile(sourceFile, [updateExpressionStatement(statement, newOuter)], sourceFile.endOfFileToken); + assert.strictEqual(newInner.pos, inner.pos); + assert.strictEqual(api.printer.printFile(updated), "(a ?? b) || c;\n"); + }); + + test("updated nodes keep a trailing array hole", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "[1];\n[2,,];\n"); + const { sourceFile } = lease; + const [first, second] = sourceFile.statements; + assert(isExpressionStatement(first) && isArrayLiteralExpression(first.expression)); + assert(isExpressionStatement(second) && isArrayLiteralExpression(second.expression)); + const updated = updateSourceFile(sourceFile, [updateExpressionStatement(first, updateArrayLiteralExpression(first.expression, second.expression.elements))], sourceFile.endOfFileToken); + assert.strictEqual((api.printer.printFile(updated)).replace(/\s/g, ""), "[2,,];"); + }); + + test("printing keeps comments in files with non-ASCII text", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", "// é\nfoo(); // trailing\n"); + const { sourceFile } = lease; + assert.strictEqual(api.printer.printFile(sourceFile), "// é\nfoo(); // trailing\n"); + const updated = updateSourceFile(sourceFile, [getSynthesizedDeepClone(sourceFile.statements[0])], sourceFile.endOfFileToken); + assert.strictEqual(api.printer.printFile(updated), "// é\nfoo(); // trailing\n"); + }); + test("printFile", () => { using api = spawnAPI(emitterFiles); diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index eb618df9ebecf..38a09b6b8f034 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -28,6 +28,7 @@ import { getChildren, getCombinedModifierFlags, getNameOfDeclaration, + getOriginalNode, getTokenAtPosition, isClassDeclaration, isExternalModule, @@ -942,16 +943,6 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { assert.strictEqual(clone.text, "hello"); }); - test("deeply clones identifier without trivia", () => { - const id = createIdentifier("hello"); - const clone = getSynthesizedDeepClone(id, /*includeTrivia*/ false); - - assert.strictEqual(clone.kind, SyntaxKind.Identifier); - assert.strictEqual(clone.text, "hello"); - assert.strictEqual(clone.pos, -1); - assert.strictEqual(clone.end, -1); - }); - test("deeply clones binary expression", () => { const left = createIdentifier("a"); const right = createNumericLiteral("42", TokenFlags.None); @@ -990,6 +981,22 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { assert.strictEqual(clone.operatorToken.parent, clone); }); + test("records each cloned node's original", () => { + const left = createIdentifier("a"); + const right = createNumericLiteral("42", TokenFlags.None); + const op = createToken(SyntaxKind.PlusToken); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); + + const clone = getSynthesizedDeepClone(bin); + const cloneOfClone = getSynthesizedDeepClone(clone); + + assert.strictEqual(getOriginalNode(clone), bin); + assert.strictEqual(getOriginalNode(clone.left), left); + assert.strictEqual(getOriginalNode(clone.right), right); + assert.strictEqual(getOriginalNode(cloneOfClone.operatorToken), op); + assert.strictEqual(getOriginalNode(bin), bin); + }); + test("returns undefined for undefined input", () => { const result = getSynthesizedDeepClone(/*node*/ undefined); assert.strictEqual(result, /*expected*/ undefined); @@ -1462,6 +1469,85 @@ interface I extends Parent {} }); }); +describe("text ranges of updated and cloned nodes", { concurrency }, () => { + const text = `import { foo } from "./foo";\nfunction f(a: number) {\n return a + foo;\n}\n`; + + function collectRanges(node: Node): [SyntaxKind, number, number][] { + const ranges: [SyntaxKind, number, number][] = [[node.kind, node.pos, node.end]]; + node.forEachChild(child => { + ranges.push(...collectRanges(child)); + return undefined; + }); + return ranges; + } + + test("update functions preserve the original node's range", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", text); + const fn = lease.sourceFile.statements[1] as FunctionDeclaration; + function rename(node: Node): Node { + if (node.kind === SyntaxKind.Identifier && (node as Identifier).text === "foo") return createIdentifier("bar"); + return visitEachChild(node, rename); + } + const updated = visitEachChild(fn, rename); + + assert.notStrictEqual(updated, fn); + assert.strictEqual(updated.pos, fn.pos); + assert.strictEqual(updated.end, fn.end); + const statement = updated.body!.statements[0]; + assert.notStrictEqual(statement, fn.body!.statements[0]); + assert.strictEqual(statement.pos, fn.body!.statements[0].pos); + assert.strictEqual(statement.end, fn.body!.statements[0].end); + }); + + test("updateSourceFile preserves the original source file's range", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + const updated = factory.updateSourceFile(sourceFile, createNodeArray(sourceFile.statements.slice(1)), sourceFile.endOfFileToken); + + assert.notStrictEqual(updated, sourceFile); + assert.strictEqual(updated.pos, sourceFile.pos); + assert.strictEqual(updated.end, sourceFile.end); + }); + + test("getSynthesizedDeepClone preserves ranges of every node", () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.ts", text); + const { sourceFile } = lease; + const clone = getSynthesizedDeepClone(sourceFile); + + assert.deepStrictEqual(collectRanges(clone), collectRanges(sourceFile)); + const statement = clone.statements[1] as FunctionDeclaration; + assert.strictEqual(statement.parameters.pos, (sourceFile.statements[1] as FunctionDeclaration).parameters.pos); + assert.strictEqual(statement.parameters.end, (sourceFile.statements[1] as FunctionDeclaration).parameters.end); + }); +}); + +describe("JSDoc parameter tag visiting", { concurrency }, () => { + for ( + const [description, tagText, expected] of [ + ["type first", "@param {string} x comment", [SyntaxKind.Identifier, SyntaxKind.JSDocTypeExpression, SyntaxKind.Identifier, SyntaxKind.JSDocText]], + ["name first", "@param x {string} comment", [SyntaxKind.Identifier, SyntaxKind.Identifier, SyntaxKind.JSDocTypeExpression, SyntaxKind.JSDocText]], + ] as const + ) { + test(`visitEachChild visits children in source order (${description})`, () => { + using api = spawnAPI(); + using lease = api.createSourceFile("/test.js", `/** ${tagText} */\nfunction f(x) {}\n`); + const declaration = lease.sourceFile.statements[0] as FunctionDeclaration; + const tag = astModule.getJSDocTags(declaration).find(astModule.isJSDocParameterTag); + assert.ok(tag); + + const visitOrder: SyntaxKind[] = []; + visitEachChild(tag, child => { + visitOrder.push(child.kind); + return child; + }); + assert.deepStrictEqual(visitOrder, expected); + }); + } +}); + describe("RemoteNode + visitEachChild", { concurrency }, () => { test("identity visitor returns same remote node", () => { const api = spawnAPI(); diff --git a/tools/scripts/tsc/generate-ts-ast.ts b/tools/scripts/tsc/generate-ts-ast.ts index 777e54af5dcf5..3e05f6040e44f 100644 --- a/tools/scripts/tsc/generate-ts-ast.ts +++ b/tools/scripts/tsc/generate-ts-ast.ts @@ -669,9 +669,9 @@ function generateFactory(): string { out.push(`} from "./ast.ts";`); out.push(`import { getModifiers, modifierToFlag } from "./modifiers.ts";`); out.push(`import { getChildren, getFirstToken, getLastToken, getTokenPosOfNode } from "./astnav.ts";`); - if (handWrittenCloneHelpers.length > 0) { + { out.push(`import {`); - for (const helperName of [...new Set(handWrittenCloneHelpers.map(h => h.helperName))].sort((a, b) => a.localeCompare(b))) { + for (const helperName of [...new Set([...handWrittenCloneHelpers.map(h => h.helperName), "setOriginalNode"])].sort((a, b) => a.localeCompare(b))) { out.push(` ${helperName},`); } out.push(`} from "./utils.ts";`); @@ -705,7 +705,7 @@ function generateFactory(): string { out.push(`/** @internal */`); out.push(`export class NodeObject {`); out.push(` readonly kind: SyntaxKind;`); - out.push(` flags: NodeFlags = 0 as NodeFlags;`); + out.push(` flags: NodeFlags = NodeFlags.Synthesized;`); out.push(` readonly pos: number = -1;`); out.push(` readonly end: number = -1;`); out.push(` parent: Node = undefined!;`); @@ -821,13 +821,19 @@ function generateFactory(): string { out.push(` return arr;`); out.push(`}`); out.push(``); + out.push(`function update(updated: T, original: T): T {`); + out.push(` (updated as any).pos = original.pos;`); + out.push(` (updated as any).end = original.end;`); + out.push(` return setOriginalNode(updated, original);`); + out.push(`}`); + out.push(``); out.push(`export function cloneNode(node: T): T {`); out.push(` const data = cloneNodeData(node);`); out.push(` const clone = new NodeObject(node.kind, data);`); - out.push(` (clone as any).flags = node.flags;`); + out.push(` (clone as any).flags = node.flags | NodeFlags.Synthesized;`); out.push(` (clone as any).pos = node.pos;`); out.push(` (clone as any).end = node.end;`); - out.push(` return clone as unknown as T;`); + out.push(` return setOriginalNode(clone as unknown as T, node);`); out.push(`}`); out.push(``); @@ -1128,7 +1134,8 @@ function generateFactory(): string { if (nodeProps.length > 0) { out.push(` const node = new NodeObject(${kindExpr}, ${dataStr}) as unknown as ${returnType};`); for (const { propName, paramName } of nodeProps) { - out.push(` (node as any).${propName} = ${paramName};`); + const value = propName === "flags" ? `${paramName} | NodeFlags.Synthesized` : paramName; + out.push(` (node as any).${propName} = ${value};`); } out.push(` return node;`); } @@ -1241,7 +1248,7 @@ function generateFactory(): string { }); out.push(`export function ${funcName}(${paramParts.join(", ")}): ${iface} {`); - out.push(` return ${comparisons.join(" || ")} ? create${iface}(${createArgs.join(", ")}) : node;`); + out.push(` return ${comparisons.join(" || ")} ? update(create${iface}(${createArgs.join(", ")}), node) : node;`); out.push(`}`); out.push(``); } @@ -1279,7 +1286,7 @@ function generateFactory(): string { }); out.push(`export function update${v.tsName}(${paramParts.join(", ")}): ${v.tsName} {`); - out.push(` return ${comparisons.join(" || ")} ? create${v.tsName}(${createArgs.join(", ")}) : node;`); + out.push(` return ${comparisons.join(" || ")} ? update(create${v.tsName}(${createArgs.join(", ")}), node) : node;`); out.push(`}`); out.push(``); } @@ -1313,7 +1320,7 @@ function generateFactory(): string { // ── updateSourceFile (hand-written in schema) ── out.push(`export function updateSourceFile(node: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile {`); out.push(` return node.statements !== statements || node.endOfFileToken !== endOfFileToken`); - out.push(` ? cloneSourceFileWithChanges(node, statements, endOfFileToken)`); + out.push(` ? update(cloneSourceFileWithChanges(node, statements, endOfFileToken), node)`); out.push(` : node;`); out.push(`}`); out.push(``); diff --git a/tsc/internal/api/encoder/decoder.go b/tsc/internal/api/encoder/decoder.go index 54bcd45ab4d7c..0b1015b8a0fb6 100644 --- a/tsc/internal/api/encoder/decoder.go +++ b/tsc/internal/api/encoder/decoder.go @@ -158,6 +158,23 @@ func (d *astDecoder) decode() (*ast.Node, error) { // child at most once, so nodeCount is an upper bound on total child pointers. d.nodeArena = make([]*ast.Node, 0, d.nodeCount) + // Encoded positions are UTF-16 offsets into the root source file's text. + positionMap, err := d.rootPositionMap() + if err != nil { + return nil, err + } + newTextRange := func(pos, end int32) core.TextRange { + if positionMap != nil { + if pos >= 0 { + pos = int32(positionMap.UTF16ToUTF8(int(pos))) + } + if end >= 0 { + end = int32(positionMap.UTF16ToUTF8(int(end))) + } + } + return core.NewTextRange(int(pos), int(end)) + } + // Process bottom-up so children exist before parents. for i := d.nodeCount - 1; i >= 1; i-- { kind := d.nodeField(i, NodeOffsetKind) @@ -174,7 +191,7 @@ func (d *astDecoder) decode() (*ast.Node, error) { } } nl := d.factory.NewNodeList(childNodes) - nl.Loc = core.NewTextRange(int(pos), int(end)) + nl.Loc = newTextRange(pos, end) d.nodeLists[i] = nl continue } @@ -183,7 +200,7 @@ func (d *astDecoder) decode() (*ast.Node, error) { if err != nil { return nil, fmt.Errorf("at node %d (kind %v): %w", i, ast.Kind(kind), err) } - node.Loc = core.NewTextRange(int(pos), int(end)) + node.Loc = newTextRange(pos, end) node.Flags = ast.NodeFlags(d.nodeField(i, NodeOffsetFlags)) if kind == uint32(ast.KindSourceFile) { node.AsSourceFile().IsDeclarationFile = node.Flags&ast.NodeFlagsAmbient != 0 @@ -197,6 +214,24 @@ func (d *astDecoder) decode() (*ast.Node, error) { return d.nodes[1], nil } +// rootPositionMap returns the position map of the root source file's text, or nil if the +// root is not a source file or its UTF-16 and UTF-8 offsets are identical. +func (d *astDecoder) rootPositionMap() (*ast.PositionMap, error) { + if d.nodeField(1, NodeOffsetKind) != uint32(ast.KindSourceFile) { + return nil, nil + } + extOff := int(d.extData) + int(d.nodeField(1, NodeOffsetData)&NodeDataStringIndexMask) + text, err := d.getString(readLE32(d.raw, extOff)) + if err != nil { + return nil, err + } + positionMap := ast.ComputePositionMap(text) + if positionMap.IsAsciiOnly() { + return nil, nil + } + return positionMap, nil +} + // getModifierList creates a *ast.ModifierList from a child index that is a NodeList. func (d *astDecoder) getModifierList(ci int) *ast.ModifierList { nl := d.nodeLists[ci] diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 40270f4e4209c..2f8e0f8241140 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -2011,6 +2011,17 @@ type PrintNodeParams struct { NeverAsciiEscape bool `json:"neverAsciiEscape,omitempty"` TerminateUnterminatedLiterals bool `json:"terminateUnterminatedLiterals,omitempty"` EmitNodes map[int]*PrintEmitNode `json:"emitNodes,omitempty"` + // OriginalFiles are the source files containing the nodes referenced by OriginalNodes. + OriginalFiles []SourceFileDescriptor `json:"originalFiles,omitempty"` + // OriginalNodes maps encoded node indices to the parsed nodes they were created from. + OriginalNodes map[int]*PrintOriginalNode `json:"originalNodes,omitempty"` +} + +// PrintOriginalNode identifies a parsed node by the index of its source file in +// PrintNodeParams.OriginalFiles and its index within that file. +type PrintOriginalNode struct { + File uint32 `json:"file"` + Index uint32 `json:"index"` } type EmitParams struct { diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index f078a1201aa7f..6c42c2321cbf5 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -4399,7 +4399,12 @@ func (s *Session) handleSymbolToString(ctx context.Context, params *SymbolToStri // handlePrintNode decodes a binary-encoded AST node and prints it to text. func (s *Session) handlePrintNode(_ context.Context, params *PrintNodeParams) (string, error) { - node, emitContext, err := decodePrintNode(params.Data, params.EmitNodes) + originals, release, err := s.resolvePrintOriginals(params.OriginalFiles, params.OriginalNodes) + if err != nil { + return "", err + } + defer release() + node, emitContext, err := decodePrintNode(params.Data, params.EmitNodes, originals) if err != nil { return "", err } @@ -4423,7 +4428,52 @@ func mapComments(comments []PrintSynthesizedComment) []printer.SynthesizedCommen }) } -func decodePrintNode(encoded string, emitNodes map[int]*PrintEmitNode) (*ast.Node, *printer.EmitContext, error) { +// resolvePrintOriginals finds the parsed nodes that printed nodes were created from. Originals +// whose source files are no longer cached are skipped. The returned function releases the +// source files and must be called once printing is finished. +func (s *Session) resolvePrintOriginals(files []SourceFileDescriptor, nodes map[int]*PrintOriginalNode) (map[int]*ast.Node, func(), error) { + if len(nodes) == 0 { + return nil, func() {}, nil + } + leases := make([]*project.SourceFileLease, len(files)) + release := func() { + for _, lease := range leases { + if lease != nil { + lease.Release() + } + } + } + acquired := make([]bool, len(files)) + originals := make(map[int]*ast.Node, len(nodes)) + for index, original := range nodes { + if original == nil { + continue + } + if int(original.File) >= len(files) { + release() + return nil, nil, fmt.Errorf("%w: original node %d references file %d outside of originalFiles", ErrClientError, index, original.File) + } + if !acquired[original.File] { + acquired[original.File] = true + if lease, err := s.acquireCachedSourceFile(files[original.File]); err == nil { + leases[original.File] = lease + } + } + lease := leases[original.File] + if lease == nil { + continue + } + table := encoder.GetNodeIndexTable(lease.SourceFile()) + if original.Index != 0 && int(original.Index) < len(table.Nodes) { + if parsed := table.Nodes[original.Index]; parsed != nil { + originals[index] = parsed + } + } + } + return originals, release, nil +} + +func decodePrintNode(encoded string, emitNodes map[int]*PrintEmitNode, originals map[int]*ast.Node) (*ast.Node, *printer.EmitContext, error) { emitContext := printer.NewEmitContext() data, err := base64.StdEncoding.DecodeString(encoded) if err != nil { @@ -4443,6 +4493,11 @@ func decodePrintNode(encoded string, emitNodes map[int]*PrintEmitNode) (*ast.Nod } usedEmitNodes := 0 node, err := encoder.DecodeNodesWithCallback(data, func(node *ast.Node, index int) { + // A decoded source file stays its own original so that emit flags set on it + // by the client are not hidden behind the cached file. + if original := originals[index]; original != nil && original.Kind == node.Kind && !ast.IsSourceFile(node) { + emitContext.SetOriginal(node, original) + } emitNode, ok := emitNodes[index] if !ok || emitNode == nil { return diff --git a/tsc/internal/api/session_printnode_test.go b/tsc/internal/api/session_printnode_test.go index 1aca23f4e0eb9..ca1a21db1017a 100644 --- a/tsc/internal/api/session_printnode_test.go +++ b/tsc/internal/api/session_printnode_test.go @@ -39,7 +39,7 @@ func TestDecodePrintNodeAppliesEmitNodes(t *testing.T) { } node, emitContext, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{ 1: {EmitFlags: uint32(printer.EFSingleLine), LeadingComments: comments, TrailingComments: comments}, - }) + }, nil) assert.NilError(t, err) assert.Equal(t, node.Kind, ast.KindTypeAliasDeclaration) assert.Equal(t, emitContext.EmitFlags(node), printer.EFSingleLine) @@ -50,14 +50,14 @@ func TestDecodePrintNodeAppliesEmitNodes(t *testing.T) { func TestDecodePrintNodeRejectsNullEmitNode(t *testing.T) { t.Parallel() - _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1: nil}) + _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1: nil}, nil) assert.ErrorIs(t, err, ErrClientError) } func TestDecodePrintNodeRejectsUnknownEmitNodeIndex(t *testing.T) { t.Parallel() - _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1 << 20: {}}) + _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1 << 20: {}}, nil) assert.ErrorIs(t, err, ErrClientError) } @@ -83,7 +83,7 @@ func TestDecodePrintNodeRejectsInvalidCommentKind(t *testing.T) { } else { emitNode.TrailingComments = comments } - _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1: emitNode}) + _, _, err := decodePrintNode(encodePrintNodeForTest(t), map[int]*PrintEmitNode{1: emitNode}, nil) assert.ErrorIs(t, err, ErrClientError) }) } @@ -94,7 +94,7 @@ func TestDecodePrintNodeRejectsInvalidCommentKind(t *testing.T) { // attach synthetic comments to one of its nodes, and prints it without a source file. func printStatementWithComments(t *testing.T, text string, attach func(statement *ast.Node, emitContext *printer.EmitContext)) string { t.Helper() - node, emitContext, err := decodePrintNode(encodeStatementForTest(t, text), nil) + node, emitContext, err := decodePrintNode(encodeStatementForTest(t, text), nil, nil) assert.NilError(t, err) attach(node, emitContext) return newPrinter(&PrintNodeParams{}, emitContext).Emit(node, nil) diff --git a/tsc/internal/printer/printer.go b/tsc/internal/printer/printer.go index e1f4135e0d7ec..d0cdb0b2db07e 100644 --- a/tsc/internal/printer/printer.go +++ b/tsc/internal/printer/printer.go @@ -2871,10 +2871,10 @@ func (p *Printer) getBinaryExpressionPrecedence(node *ast.BinaryExpression) (lef func (p *Printer) emitBinaryExpression(node *ast.BinaryExpression) { leftPrec, rightPrec := p.getBinaryExpressionPrecedence(node) - if emittedLeft := ast.SkipPartiallyEmittedExpressions(node.Left); ast.NodeIsSynthesized(emittedLeft) && emittedLeft.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedLeft.AsBinaryExpression().OperatorToken.Kind) { + if emittedLeft := ast.SkipPartiallyEmittedExpressions(node.Left); isSynthesizedForEmit(emittedLeft) && emittedLeft.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedLeft.AsBinaryExpression().OperatorToken.Kind) { leftPrec = ast.OperatorPrecedenceHighest } - if emittedRight := ast.SkipPartiallyEmittedExpressions(node.Right); ast.NodeIsSynthesized(emittedRight) && emittedRight.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedRight.AsBinaryExpression().OperatorToken.Kind) { + if emittedRight := ast.SkipPartiallyEmittedExpressions(node.Right); isSynthesizedForEmit(emittedRight) && emittedRight.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedRight.AsBinaryExpression().OperatorToken.Kind) { rightPrec = ast.OperatorPrecedenceHighest } state := p.enterNode(node.AsNode()) @@ -4879,6 +4879,10 @@ func (p *Printer) hasTrailingComma(parentNode *ast.Node, children *ast.NodeList) return false } +func isArrayHole(node *ast.Node) bool { + return ast.IsOmittedExpression(node) || ast.IsBindingElement(node) && node.Name() == nil +} + func (p *Printer) writeDelimiter(format ListFormat) { switch format & LFDelimitersMask { case LFNone: @@ -5003,7 +5007,8 @@ func (p *Printer) emitListItems( // Write a trailing comma, if requested. skipTrailingComments := p.commentsDisabled || !p.shouldEmitTrailingComments(previousSibling) - emitTrailingComma := hasTrailingComma && format&LFAllowTrailingComma != 0 && format&LFCommaDelimited != 0 + // A trailing hole is only an element if it is followed by a comma. + emitTrailingComma := (hasTrailingComma || previousSibling != nil && isArrayHole(previousSibling)) && format&LFAllowTrailingComma != 0 && format&LFCommaDelimited != 0 if emitTrailingComma { if previousSibling != nil && !skipTrailingComments { p.emitToken(ast.KindCommaToken, previousSibling.End(), WriteKindPunctuation, previousSibling) diff --git a/tsc/internal/printer/printer_test.go b/tsc/internal/printer/printer_test.go index 50ec1afa3c1f3..d451d42f7ca44 100644 --- a/tsc/internal/printer/printer_test.go +++ b/tsc/internal/printer/printer_test.go @@ -1655,6 +1655,42 @@ func TestParenthesizeSpreadElement1(t *testing.T) { emittestutil.CheckEmit(t, nil, file.AsSourceFile(), "[...(a, b)];") } +func TestEmitTrailingArrayHoles(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + file := factory.NewSourceFile(ast.SourceFileParseOptions{FileName: "/file.ts", PathKey: "/file.ts"}, "", factory.NewNodeList( + []*ast.Node{ + factory.NewExpressionStatement( + factory.NewArrayLiteralExpression( + factory.NewNodeList([]*ast.Node{ + factory.NewNumericLiteral("1", ast.TokenFlagsNone), + factory.NewOmittedExpression(), + }), + false, /*multiLine*/ + ), + ), + factory.NewVariableStatement(nil, factory.NewVariableDeclarationList( + factory.NewNodeList([]*ast.Node{ + factory.NewVariableDeclaration( + factory.NewBindingPattern(ast.KindArrayBindingPattern, factory.NewNodeList([]*ast.Node{ + factory.NewBindingElement(nil, nil, factory.NewIdentifier("a"), nil), + factory.NewBindingElement(nil, nil, nil, nil), + })), + nil, /*exclamationToken*/ + nil, /*typeNode*/ + factory.NewIdentifier("b"), + ), + }), + ast.NodeFlagsConst, + )), + }, + ), factory.NewToken(ast.KindEndOfFile)) + + parsetestutil.MarkSyntheticRecursive(file) + emittestutil.CheckEmit(t, nil, file.AsSourceFile(), "[1, ,];\nconst [a, ,] = b;") +} + func TestParenthesizeSpreadElement2(t *testing.T) { t.Parallel() diff --git a/tsc/internal/printer/utilities.go b/tsc/internal/printer/utilities.go index 3ca7d9f50401a..5b7edf2635562 100644 --- a/tsc/internal/printer/utilities.go +++ b/tsc/internal/printer/utilities.go @@ -652,6 +652,12 @@ func isBinaryOperation(node *ast.Node, token ast.Kind) bool { node.AsBinaryExpression().OperatorToken.Kind == token } +// Reports whether a node was not produced by the parser, either because it has no +// source position or because a factory marked it as synthesized. +func isSynthesizedForEmit(node *ast.Node) bool { + return ast.NodeIsSynthesized(node) || node.Flags&ast.NodeFlagsSynthesized != 0 +} + func mixingBinaryOperatorsRequiresParentheses(a ast.Kind, b ast.Kind) bool { if a == ast.KindQuestionQuestionToken { return b == ast.KindAmpersandAmpersandToken || b == ast.KindBarBarToken