Skip to content

Commit b9f8778

Browse files
Preserve text ranges on updated and cloned API nodes (#65649)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 502a981 commit b9f8778

20 files changed

Lines changed: 923 additions & 266 deletions

File tree

‎packages/typescript/src/api/async/api.ts‎

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
readSourceFileLease,
6363
RemoteNode,
6464
RemoteSourceFile,
65+
sourceFileDescriptor,
6566
} from "../node/node.ts";
6667
import { Wtf8Decoder } from "../node/wtf8.ts";
6768
import type {
@@ -125,7 +126,6 @@ import type {
125126
ResolveTypeReferenceDirectiveResult,
126127
SignaturePropertyMethod,
127128
SignatureResponse,
128-
SourceFileDescriptor,
129129
SourceFileMetadata,
130130
StaticModuleResolution,
131131
SymbolPropertyMethod,
@@ -946,17 +946,6 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
946946

947947
type EnsureInitialized = () => Promise<void>; // @sync: type EnsureInitialized = (() => void) & { gen(): Generator<ProtocolRequest, void, ProtocolResponse["result"]>; };
948948

949-
function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor {
950-
return {
951-
fileName: sourceFile.fileName,
952-
path: sourceFile.path,
953-
contentHash: sourceFile.contentHash,
954-
parseOptionsKey: sourceFile.parseOptionsKey,
955-
scriptKind: sourceFile.scriptKind,
956-
nodeId: sourceFile.nodeId,
957-
};
958-
}
959-
960949
/** Returns whether a node is backed by a remote compiler response. */
961950
export function isRemoteNode(node: Node): boolean {
962951
return node instanceof RemoteNode;

‎packages/typescript/src/api/node/node.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "../../ast/index.ts";
1515
import type { API as AsyncAPI } from "../async/api.ts";
1616
import { tryPathKeyFromCanonical } from "../path.ts";
17+
import type { SourceFileDescriptor } from "../proto.generated.ts";
1718
import type { CachedSourceFile } from "../sourceFileCache.ts";
1819
import type { API as SyncAPI } from "../sync/api.ts";
1920
import type { TimingCollector } from "../timing.ts";
@@ -148,6 +149,11 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo {
148149
return readSourceFileNodeId(this.view);
149150
}
150151

152+
/** @internal */
153+
get hasServerIdentity(): boolean {
154+
return this.view.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, /*littleEndian*/ true) !== 0n;
155+
}
156+
151157
/**
152158
* The file component of node handles sent to the server: `#` followed by the
153159
* server's identity for this exact source file.
@@ -555,6 +561,30 @@ export function decodeNode(data: Uint8Array): Node {
555561
return sf;
556562
}
557563

564+
/** @internal */
565+
export function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor {
566+
return {
567+
fileName: sourceFile.fileName,
568+
path: sourceFile.path,
569+
contentHash: sourceFile.contentHash,
570+
parseOptionsKey: sourceFile.parseOptionsKey,
571+
scriptKind: sourceFile.scriptKind,
572+
nodeId: sourceFile.nodeId,
573+
};
574+
}
575+
576+
/**
577+
* Returns the server source file containing `node` and the node's index within it,
578+
* or `undefined` if `node` was not decoded from a server source file.
579+
* @internal
580+
*/
581+
export function getRemoteNodeLocation(node: Node): { sourceFile: RemoteSourceFile; index: number; } | undefined {
582+
if (!(node instanceof RemoteNode)) return undefined;
583+
const sourceFile = node["_sourceFile"];
584+
if (!(sourceFile instanceof RemoteSourceFile) || !sourceFile.hasServerIdentity) return undefined;
585+
return { sourceFile, index: node["index"] };
586+
}
587+
558588
/**
559589
* Get the unique ID string for a remote node.
560590
* Throws if the node is not a RemoteNode (i.e. not decoded from binary data).

‎packages/typescript/src/api/printer.ts‎

Lines changed: 77 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
import { EmitFlags } from "../../enums/emitFlags.js";
2-
import type {
3-
Node,
4-
SyntaxKind,
2+
import { SyntaxKind } from "../../enums/syntaxKind.js";
3+
import {
4+
getOriginalNode,
5+
type Node,
56
} from "../ast/index.ts";
67
import {
78
encodeNode,
89
uint8ArrayToBase64,
910
} from "./node/encoder.ts";
11+
import {
12+
getRemoteNodeLocation,
13+
type RemoteSourceFile,
14+
sourceFileDescriptor,
15+
} from "./node/node.ts";
16+
import type {
17+
PrintOriginalNode,
18+
SourceFileDescriptor,
19+
} from "./proto.generated.ts";
1020

1121
export interface PrintNodeOptions {
1222
preserveSourceNewlines?: boolean | undefined;
@@ -43,12 +53,38 @@ export interface EmitContext {
4353
addSyntheticTrailingComment(node: Node, kind: CommentKind, text: string, hasTrailingNewLine: boolean, hasLeadingNewLine: boolean): Node;
4454
setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]): T;
4555
getSyntheticTrailingComments(node: Node): readonly SynthesizedComment[] | undefined;
56+
57+
/**
58+
* Suppresses emission of the source comments before and after `node`. Comments inside the
59+
* node are still emitted. `NoLeadingComments` and `NoTrailingComments` hide comments at a
60+
* node's start and end, including those of descendants sharing that position, so the flags
61+
* are also added to first and last descendants until one with a source position is reached.
62+
*/
63+
suppressLeadingAndTrailingComments<T extends Node>(node: T): T;
4664
}
4765

4866
/** @internal */
49-
export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): { data: string; emitNodes: Record<number, EmitNode> | undefined; } {
67+
export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): {
68+
data: string;
69+
emitNodes: Record<number, EmitNode> | undefined;
70+
originalFiles: SourceFileDescriptor[] | undefined;
71+
originalNodes: Record<number, PrintOriginalNode> | undefined;
72+
} {
5073
let emitNodes: Record<number, EmitNode> | undefined;
74+
let originalFiles: SourceFileDescriptor[] | undefined;
75+
let originalNodes: Record<number, PrintOriginalNode> | undefined;
76+
const fileIndices = new Map<RemoteSourceFile, number>();
5177
const encoded = encodeNode(node, (node, index) => {
78+
const original = getOriginalNode(node);
79+
const location = original !== node ? getRemoteNodeLocation(original) : undefined;
80+
if (location) {
81+
let file = fileIndices.get(location.sourceFile);
82+
if (file === undefined) {
83+
file = (originalFiles ??= []).push(sourceFileDescriptor(location.sourceFile)) - 1;
84+
fileIndices.set(location.sourceFile, file);
85+
}
86+
(originalNodes ??= {})[index] = { file, index: location.index };
87+
}
5288
const emitNode = emitContext?.getEmitNode(node);
5389
if (emitNode === undefined) return;
5490
(emitNodes ??= {})[index] = {
@@ -57,7 +93,7 @@ export function encodePrintNode(node: Node, emitContext: EmitContext | undefined
5793
trailingComments: emitNode.trailingComments?.map(c => ({ ...c })),
5894
};
5995
});
60-
return { data: uint8ArrayToBase64(encoded), emitNodes };
96+
return { data: uint8ArrayToBase64(encoded), emitNodes, originalFiles, originalNodes };
6197
}
6298

6399
/** @internal */
@@ -108,5 +144,41 @@ export function createEmitContext(): EmitContext {
108144
getSyntheticTrailingComments(node) {
109145
return emitNodes.get(node)?.trailingComments;
110146
},
147+
148+
suppressLeadingAndTrailingComments(node) {
149+
for (let n: Node | undefined = node; n; n = n.pos < 0 ? getFirstChild(n) : undefined) {
150+
getOrCreateEmitNode(n).emitFlags |= EmitFlags.NoLeadingComments;
151+
}
152+
for (let n: Node | undefined = node; n; n = n.end < 0 ? getLastChild(n) : undefined) {
153+
getOrCreateEmitNode(n).emitFlags |= EmitFlags.NoTrailingComments;
154+
}
155+
return node;
156+
},
111157
};
112158
}
159+
160+
function getFirstChild(node: Node): Node | undefined {
161+
return node.forEachChild(child => child);
162+
}
163+
164+
function getLastChild(node: Node): Node | undefined {
165+
let lastChild: Node | undefined;
166+
node.forEachChild(
167+
child => {
168+
if (nodeIsPresent(child)) lastChild = child;
169+
},
170+
children => {
171+
for (let i = children.length - 1; i >= 0; i--) {
172+
if (nodeIsPresent(children[i])) {
173+
lastChild = children[i];
174+
break;
175+
}
176+
}
177+
},
178+
);
179+
return lastChild;
180+
}
181+
182+
function nodeIsPresent(node: Node): boolean {
183+
return node.pos !== node.end || node.pos < 0 || node.kind === SyntaxKind.EndOfFile;
184+
}

‎packages/typescript/src/api/proto.generated.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,6 +1238,10 @@ export interface PrintNodeParams {
12381238
neverAsciiEscape?: boolean | undefined;
12391239
terminateUnterminatedLiterals?: boolean | undefined;
12401240
emitNodes?: Record<number, PrintEmitNode | null> | undefined;
1241+
/** OriginalFiles are the source files containing the nodes referenced by OriginalNodes. */
1242+
originalFiles?: readonly SourceFileDescriptor[] | undefined;
1243+
/** OriginalNodes maps encoded node indices to the parsed nodes they were created from. */
1244+
originalNodes?: Record<number, PrintOriginalNode | null> | undefined;
12411245
}
12421246

12431247
export interface EmitParams {
@@ -1957,6 +1961,15 @@ export interface PrintEmitNode {
19571961
trailingComments?: PrintSynthesizedComment[] | undefined;
19581962
}
19591963

1964+
/**
1965+
* PrintOriginalNode identifies a parsed node by the index of its source file in
1966+
* PrintNodeParams.OriginalFiles and its index within that file.
1967+
*/
1968+
export interface PrintOriginalNode {
1969+
file: number;
1970+
index: number;
1971+
}
1972+
19601973
export interface EmitOutputFile {
19611974
fileName: RootedFilePath;
19621975
text: string;

‎packages/typescript/src/api/sync/api.ts‎

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import {
8181
readSourceFileLease,
8282
RemoteNode,
8383
RemoteSourceFile,
84+
sourceFileDescriptor,
8485
} from "../node/node.ts";
8586
import { Wtf8Decoder } from "../node/wtf8.ts";
8687
import type {
@@ -144,7 +145,6 @@ import type {
144145
ResolveTypeReferenceDirectiveResult,
145146
SignaturePropertyMethod,
146147
SignatureResponse,
147-
SourceFileDescriptor,
148148
SourceFileMetadata,
149149
StaticModuleResolution,
150150
SymbolPropertyMethod,
@@ -1555,17 +1555,6 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
15551555

15561556
type EnsureInitialized = (() => void) & { gen(): Generator<ProtocolRequest, void, ProtocolResponse["result"]>; };
15571557

1558-
function sourceFileDescriptor(sourceFile: RemoteSourceFile): SourceFileDescriptor {
1559-
return {
1560-
fileName: sourceFile.fileName,
1561-
path: sourceFile.path,
1562-
contentHash: sourceFile.contentHash,
1563-
parseOptionsKey: sourceFile.parseOptionsKey,
1564-
scriptKind: sourceFile.scriptKind,
1565-
nodeId: sourceFile.nodeId,
1566-
};
1567-
}
1568-
15691558
/** Returns whether a node is backed by a remote compiler response. */
15701559
export function isRemoteNode(node: Node): boolean {
15711560
return node instanceof RemoteNode;

‎packages/typescript/src/ast/clone.ts‎

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
createNumericLiteral,
1313
createStringLiteral,
1414
} from "./factory.generated.ts";
15+
import { setOriginalNode } from "./utils.ts";
1516
import { visitEachChild } from "./visitor.ts";
1617

1718
function isArray(value: any): value is readonly unknown[] {
@@ -87,35 +88,23 @@ function setTextRange<T extends Node>(node: T, range: ReadonlyTextRange | undefi
8788

8889
/**
8990
* Creates a deep clone of a node and its subtree, synthesizing new nodes for every child.
90-
* The resulting tree has fully set parent pointers.
91-
*
92-
* @param node The node to clone.
93-
* @param includeTrivia Whether to preserve the text range (pos/end) on the clone.
91+
* Every cloned node keeps the text range of the node it was cloned from, and the resulting
92+
* tree has fully set parent pointers.
9493
*/
95-
export function getSynthesizedDeepClone<T extends Node>(node: T, includeTrivia?: boolean): T;
96-
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined, includeTrivia?: boolean): T | undefined;
97-
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined, includeTrivia = true): T | undefined {
98-
const clone = node && getSynthesizedDeepCloneWorker(node);
99-
if (clone && !includeTrivia) {
100-
(clone as any).pos = -1;
101-
(clone as any).end = -1;
102-
}
103-
return setParentRecursive(clone);
94+
export function getSynthesizedDeepClone<T extends Node>(node: T): T;
95+
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined): T | undefined;
96+
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined): T | undefined {
97+
return setParentRecursive(node && getSynthesizedDeepCloneWorker(node));
10498
}
10599

106100
/**
107101
* Creates deep clones of a NodeArray and all its elements.
108102
*/
109-
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T>, includeTrivia?: boolean): NodeArray<T>;
110-
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined, includeTrivia?: boolean): NodeArray<T> | undefined;
111-
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined, includeTrivia = true): NodeArray<T> | undefined {
103+
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T>): NodeArray<T>;
104+
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined): NodeArray<T> | undefined;
105+
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined): NodeArray<T> | undefined {
112106
if (nodes) {
113-
const cloned = createNodeArray(
114-
nodes.map(n => getSynthesizedDeepClone(n, includeTrivia)),
115-
nodes.pos,
116-
nodes.end,
117-
);
118-
return cloned;
107+
return createNodeArray(nodes.map(n => getSynthesizedDeepClone(n)), nodes.pos, nodes.end);
119108
}
120109
return nodes;
121110
}
@@ -131,7 +120,7 @@ function getSynthesizedDeepCloneWorker<T extends Node>(node: T): T {
131120
: node.kind === SyntaxKind.NumericLiteral
132121
? createNumericLiteral((node as Node as NumericLiteral).text, (node as Node as NumericLiteral).tokenFlags) as Node as T
133122
: cloneNode(node);
134-
return setTextRange(clone, node);
123+
return setOriginalNode(setTextRange(clone, node), node);
135124
}
136125

137126
// visitEachChild already created a new node with visited children.

0 commit comments

Comments
 (0)