Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 1 addition & 12 deletions packages/typescript/src/api/async/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
readSourceFileLease,
RemoteNode,
RemoteSourceFile,
sourceFileDescriptor,
} from "../node/node.ts";
import { Wtf8Decoder } from "../node/wtf8.ts";
import type {
Expand Down Expand Up @@ -125,7 +126,6 @@ import type {
ResolveTypeReferenceDirectiveResult,
SignaturePropertyMethod,
SignatureResponse,
SourceFileDescriptor,
SourceFileMetadata,
StaticModuleResolution,
SymbolPropertyMethod,
Expand Down Expand Up @@ -946,17 +946,6 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo

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

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;
Expand Down
30 changes: 30 additions & 0 deletions packages/typescript/src/api/node/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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).
Expand Down
82 changes: 77 additions & 5 deletions packages/typescript/src/api/printer.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -43,12 +53,38 @@ export interface EmitContext {
addSyntheticTrailingComment(node: Node, kind: CommentKind, text: string, hasTrailingNewLine: boolean, hasLeadingNewLine: boolean): Node;
setSyntheticTrailingComments<T extends Node>(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<T extends Node>(node: T): T;
}

/** @internal */
export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): { data: string; emitNodes: Record<number, EmitNode> | undefined; } {
export function encodePrintNode(node: Node, emitContext: EmitContext | undefined): {
data: string;
emitNodes: Record<number, EmitNode> | undefined;
originalFiles: SourceFileDescriptor[] | undefined;
originalNodes: Record<number, PrintOriginalNode> | undefined;
} {
let emitNodes: Record<number, EmitNode> | undefined;
let originalFiles: SourceFileDescriptor[] | undefined;
let originalNodes: Record<number, PrintOriginalNode> | undefined;
const fileIndices = new Map<RemoteSourceFile, number>();
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] = {
Expand All @@ -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 */
Expand Down Expand Up @@ -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;
Comment thread
andrewbranch marked this conversation as resolved.
Resolved
}
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;
}
13 changes: 13 additions & 0 deletions packages/typescript/src/api/proto.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1238,6 +1238,10 @@ export interface PrintNodeParams {
neverAsciiEscape?: boolean | undefined;
terminateUnterminatedLiterals?: boolean | undefined;
emitNodes?: Record<number, PrintEmitNode | null> | 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<number, PrintOriginalNode | null> | undefined;
}

export interface EmitParams {
Expand Down Expand Up @@ -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;
Expand Down
13 changes: 1 addition & 12 deletions packages/typescript/src/api/sync/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import {
readSourceFileLease,
RemoteNode,
RemoteSourceFile,
sourceFileDescriptor,
} from "../node/node.ts";
import { Wtf8Decoder } from "../node/wtf8.ts";
import type {
Expand Down Expand Up @@ -144,7 +145,6 @@ import type {
ResolveTypeReferenceDirectiveResult,
SignaturePropertyMethod,
SignatureResponse,
SourceFileDescriptor,
SourceFileMetadata,
StaticModuleResolution,
SymbolPropertyMethod,
Expand Down Expand Up @@ -1555,17 +1555,6 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo

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

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;
Expand Down
35 changes: 12 additions & 23 deletions packages/typescript/src/ast/clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] {
Expand Down Expand Up @@ -87,35 +88,23 @@ function setTextRange<T extends Node>(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<T extends Node>(node: T, includeTrivia?: boolean): T;
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined, includeTrivia?: boolean): T | undefined;
export function getSynthesizedDeepClone<T extends Node>(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<T extends Node>(node: T): T;
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined): T | undefined;
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined): T | undefined {
return setParentRecursive(node && getSynthesizedDeepCloneWorker(node));
}

/**
* Creates deep clones of a NodeArray and all its elements.
*/
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T>, includeTrivia?: boolean): NodeArray<T>;
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined, includeTrivia?: boolean): NodeArray<T> | undefined;
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined, includeTrivia = true): NodeArray<T> | undefined {
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T>): NodeArray<T>;
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined): NodeArray<T> | undefined;
export function getSynthesizedDeepClones<T extends Node>(nodes: NodeArray<T> | undefined): NodeArray<T> | 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;
}
Expand All @@ -131,7 +120,7 @@ function getSynthesizedDeepCloneWorker<T extends Node>(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.
Expand Down
Loading
Loading