From 3da2bc939ce9547d72dd146120fd1139dfce0256 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:15:35 -0800 Subject: [PATCH 01/13] Export findAncestor with narrowing and early termination Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/is.ts | 7 +++++-- packages/typescript/test/sync/ast.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/typescript/src/ast/is.ts b/packages/typescript/src/ast/is.ts index 16ba8c4390e11..c5fc3609c8ef7 100644 --- a/packages/typescript/src/ast/is.ts +++ b/packages/typescript/src/ast/is.ts @@ -217,9 +217,12 @@ function isShorthandPropertyNameUseSite(useSite: Node): boolean { return isIdentifier(useSite) && isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite; } -type AncestorCallbackResult = boolean | "quit"; +export type AncestorCallbackResult = boolean | "quit"; -function findAncestor(node: Node, callback: (node: Node) => AncestorCallbackResult): Node | undefined { +/** Searches a node and its ancestors, stopping if the callback returns `"quit"`. */ +export function findAncestor(node: Node | undefined, callback: (node: Node) => node is T): T | undefined; +export function findAncestor(node: Node | undefined, callback: (node: Node) => AncestorCallbackResult): Node | undefined; +export function findAncestor(node: Node | undefined, callback: (node: Node) => AncestorCallbackResult): Node | undefined { while (node) { const result = callback(node); if (result === "quit") { diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index d3e33409b6cbf..2d9a9310fe8b9 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -89,6 +89,29 @@ import { runBenchmarks } from "./ast.bench.ts"; const concurrency = areTestsFiltered(); +test("findAncestor visits the starting node and supports narrowing and early termination", () => { + using api = spawnAPI(); + const source = api.createSourceFile("/ancestor.ts", "class C { method() { return 1; } }").sourceFile; + const declaration = source.statements[0]; + assert.ok(astModule.isClassDeclaration(declaration)); + const member = declaration.members[0]; + assert.ok(astModule.isMethodDeclaration(member)); + const ancestor: ClassDeclaration | undefined = astModule.findAncestor(member, astModule.isClassDeclaration); + assert.strictEqual(ancestor, declaration); + assert.strictEqual(astModule.findAncestor(member, node => node === member), member); + const visited: Node[] = []; + assert.strictEqual( + astModule.findAncestor(member, node => { + visited.push(node); + return node === declaration ? "quit" : false; + }), + undefined, + ); + assert.deepStrictEqual(visited, [member, declaration]); + assert.strictEqual(astModule.findAncestor(source, () => false), undefined); + assert.strictEqual(astModule.findAncestor(undefined, () => true), undefined); +}); + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- From 715e2da494731b4d2750b99a4078487b32eabf4b Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:16:42 -0800 Subject: [PATCH 02/13] Expose canHaveDecorators declaration guard Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/ast.ts | 14 +++++++++++ packages/typescript/src/ast/is.ts | 16 +++++++++++++ packages/typescript/test/sync/ast.test.ts | 29 +++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/packages/typescript/src/ast/ast.ts b/packages/typescript/src/ast/ast.ts index cb3c6dcd2d731..c27947dd46fbd 100644 --- a/packages/typescript/src/ast/ast.ts +++ b/packages/typescript/src/ast/ast.ts @@ -11,6 +11,8 @@ import type { AssertionExpression, BindingElement, CaseClause, + ClassDeclaration, + ClassExpression, ComputedPropertyName, Decorator, DoStatement, @@ -22,12 +24,14 @@ import type { ForInStatement, ForOfStatement, ForStatement, + GetAccessorDeclaration, Identifier, IfStatement, JsxAttribute, JsxExpression, JsxSpreadAttribute, KeywordSyntaxKind, + MethodDeclaration, ModifierSyntaxKind, ParameterDeclaration, PropertyAccessExpression, @@ -37,6 +41,7 @@ import type { PunctuationSyntaxKind, ReturnStatement, SatisfiesExpression, + SetAccessorDeclaration, ShorthandPropertyAssignment, SpreadAssignment, Statement, @@ -57,6 +62,15 @@ export { TokenFlags } from "../../enums/tokenFlags.js"; export * from "./ast.generated.ts"; export * as factory from "./factory.generated.ts"; +export type CanHaveDecorators = + | ParameterDeclaration + | PropertyDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | ClassExpression + | ClassDeclaration; + // ── Core types ── declare const rootedPathBrand: unique symbol; diff --git a/packages/typescript/src/ast/is.ts b/packages/typescript/src/ast/is.ts index c5fc3609c8ef7..694a1d1b4e48e 100644 --- a/packages/typescript/src/ast/is.ts +++ b/packages/typescript/src/ast/is.ts @@ -11,6 +11,7 @@ import type { BindingPattern, BlockOrExpression, BooleanLiteral, + CanHaveDecorators, ComputedPropertyName, ConciseBody, ExclamationToken, @@ -67,6 +68,21 @@ import { export * from "./is.generated.ts"; +export function canHaveDecorators(node: Node): node is CanHaveDecorators { + switch (node.kind) { + case SyntaxKind.Parameter: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.ClassExpression: + case SyntaxKind.ClassDeclaration: + return true; + default: + return false; + } +} + type JSDocNamespaceDeclaration = ModuleDeclaration; type WrappedExpression = diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index 2d9a9310fe8b9..9eb02baad432e 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -89,6 +89,35 @@ import { runBenchmarks } from "./ast.bench.ts"; const concurrency = areTestsFiltered(); +test("canHaveDecorators narrows all supported declarations, even without decorators", () => { + using api = spawnAPI(); + const source = api.createSourceFile( + "/decorators.ts", + "class C { property; method(parameter) {} get value() {} set value(v) {} } const expression = class {};", + ).sourceFile; + const supported = new Set([ + SyntaxKind.Parameter, + SyntaxKind.PropertyDeclaration, + SyntaxKind.MethodDeclaration, + SyntaxKind.GetAccessor, + SyntaxKind.SetAccessor, + SyntaxKind.ClassExpression, + SyntaxKind.ClassDeclaration, + ]); + const seen = new Set(); + function walk(node: Node): void { + assert.strictEqual(astModule.canHaveDecorators(node), supported.has(node.kind)); + if (astModule.canHaveDecorators(node)) { + const declaration: astModule.CanHaveDecorators = node; + assert.strictEqual(declaration.modifiers, undefined); + seen.add(node.kind); + } + node.forEachChild(walk); + } + walk(source); + assert.deepStrictEqual(seen, supported); +}); + test("findAncestor visits the starting node and supports narrowing and early termination", () => { using api = spawnAPI(); const source = api.createSourceFile("/ancestor.ts", "class C { method() { return 1; } }").sourceFile; From 3c768e10ea228be2b125797905c9364f582b07eb Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:17:33 -0800 Subject: [PATCH 03/13] Expose canHaveModifiers declaration guard Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/ast.ts | 45 ++++++++++++++++ packages/typescript/src/ast/is.ts | 35 +++++++++++++ packages/typescript/test/sync/ast.test.ts | 64 +++++++++++++++++++++++ 3 files changed, 144 insertions(+) diff --git a/packages/typescript/src/ast/ast.ts b/packages/typescript/src/ast/ast.ts index c27947dd46fbd..260ee470615d3 100644 --- a/packages/typescript/src/ast/ast.ts +++ b/packages/typescript/src/ast/ast.ts @@ -8,31 +8,45 @@ import type { NodeFlags } from "../../enums/nodeFlags.js"; import type { ScriptKind } from "../../enums/scriptKind.js"; import { SyntaxKind } from "../../enums/syntaxKind.js"; import type { + ArrowFunction, AssertionExpression, BindingElement, CaseClause, ClassDeclaration, ClassExpression, ComputedPropertyName, + ConstructorDeclaration, + ConstructorTypeNode, Decorator, DoStatement, EndOfFile, EntityName, + EnumDeclaration, EnumMember, + ExportAssignment, + ExportDeclaration, Expression, ExpressionStatement, ForInStatement, ForOfStatement, ForStatement, + FunctionDeclaration, + FunctionExpression, GetAccessorDeclaration, Identifier, IfStatement, + ImportDeclaration, + ImportEqualsDeclaration, + IndexSignatureDeclaration, + InterfaceDeclaration, JsxAttribute, JsxExpression, JsxSpreadAttribute, KeywordSyntaxKind, MethodDeclaration, + MethodSignatureDeclaration, ModifierSyntaxKind, + ModuleDeclaration, ParameterDeclaration, PropertyAccessExpression, PropertyAssignment, @@ -50,7 +64,10 @@ import type { ThisExpression, ThrowStatement, Token, + TypeAliasDeclaration, + TypeParameterDeclaration, VariableDeclaration, + VariableStatement, WhileStatement, WithStatement, } from "./ast.generated.ts"; @@ -71,6 +88,34 @@ export type CanHaveDecorators = | ClassExpression | ClassDeclaration; +export type CanHaveModifiers = + | TypeParameterDeclaration + | ParameterDeclaration + | PropertySignatureDeclaration + | PropertyDeclaration + | MethodSignatureDeclaration + | MethodDeclaration + | ConstructorDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | IndexSignatureDeclaration + | ConstructorTypeNode + | FunctionExpression + | ArrowFunction + | ClassExpression + | VariableStatement + | FunctionDeclaration + | ClassDeclaration + | InterfaceDeclaration + | TypeAliasDeclaration + | EnumDeclaration + | ModuleDeclaration + | ImportEqualsDeclaration + | ImportDeclaration + | (Omit & { readonly kind: SyntaxKind.JSImportDeclaration; }) + | ExportAssignment + | ExportDeclaration; + // ── Core types ── declare const rootedPathBrand: unique symbol; diff --git a/packages/typescript/src/ast/is.ts b/packages/typescript/src/ast/is.ts index 694a1d1b4e48e..14ef5396bef75 100644 --- a/packages/typescript/src/ast/is.ts +++ b/packages/typescript/src/ast/is.ts @@ -12,6 +12,7 @@ import type { BlockOrExpression, BooleanLiteral, CanHaveDecorators, + CanHaveModifiers, ComputedPropertyName, ConciseBody, ExclamationToken, @@ -83,6 +84,40 @@ export function canHaveDecorators(node: Node): node is CanHaveDecorators { } } +export function canHaveModifiers(node: Node): node is CanHaveModifiers { + switch (node.kind) { + case SyntaxKind.TypeParameter: + case SyntaxKind.Parameter: + case SyntaxKind.PropertySignature: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.Constructor: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.IndexSignature: + case SyntaxKind.ConstructorType: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.ClassExpression: + case SyntaxKind.VariableStatement: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.JSImportDeclaration: + case SyntaxKind.ExportAssignment: + case SyntaxKind.ExportDeclaration: + return true; + default: + return false; + } +} + type JSDocNamespaceDeclaration = ModuleDeclaration; type WrappedExpression = diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index 9eb02baad432e..2571036412532 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -89,6 +89,70 @@ import { runBenchmarks } from "./ast.bench.ts"; const concurrency = areTestsFiltered(); +test("canHaveModifiers includes the reparsed import kind in its narrowed type", () => { + using api = spawnAPI(); + const source = api.createSourceFile("/imports.js", '/** @import { Foo } from "./foo" */\nlet value;').sourceFile; + const node: Node = source.statements[0]; + assert.ok(astModule.canHaveModifiers(node)); + if (node.kind === SyntaxKind.JSImportDeclaration) { + assert.strictEqual(node.moduleSpecifier.kind, SyntaxKind.StringLiteral); + assert.strictEqual(node.importClause?.namedBindings?.kind, SyntaxKind.NamedImports); + } + else { + assert.fail("Expected the reparsed JSDoc import"); + } +}); + +test("canHaveModifiers recognizes declarations without an existing modifier list", () => { + using api = spawnAPI(); + const source = api.createSourceFile( + "/modifiers.ts", + ` +export class C { + property; + method(parameter) {} + constructor() {} + get value() {} + set value(v) {} + [key: string]: any; +} +interface I { property: string; method(): void; } +const fn = async () => {}; +import x from "x"; +export { x }; +`, + ).sourceFile; + const supported = new Set([ + SyntaxKind.ClassDeclaration, + SyntaxKind.TypeParameter, + SyntaxKind.PropertyDeclaration, + SyntaxKind.MethodDeclaration, + SyntaxKind.Parameter, + SyntaxKind.Constructor, + SyntaxKind.GetAccessor, + SyntaxKind.SetAccessor, + SyntaxKind.IndexSignature, + SyntaxKind.InterfaceDeclaration, + SyntaxKind.PropertySignature, + SyntaxKind.MethodSignature, + SyntaxKind.VariableStatement, + SyntaxKind.ArrowFunction, + SyntaxKind.ImportDeclaration, + SyntaxKind.ExportDeclaration, + ]); + const seen = new Set(); + function walk(node: Node): void { + assert.strictEqual(astModule.canHaveModifiers(node), supported.has(node.kind), formatSyntaxKind(node.kind)); + if (astModule.canHaveModifiers(node)) { + const declaration: astModule.CanHaveModifiers = node; + seen.add(declaration.kind); + } + node.forEachChild(walk); + } + walk(source); + assert.deepStrictEqual(seen, supported); +}); + test("canHaveDecorators narrows all supported declarations, even without decorators", () => { using api = spawnAPI(); const source = api.createSourceFile( From 2898fee1b9b1235a093e6e1502aa1440c56430fd Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:18:06 -0800 Subject: [PATCH 04/13] Expose getCombinedNodeFlags using shared declaration traversal Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/utils.ts | 15 ++++++++++--- packages/typescript/test/sync/ast.test.ts | 26 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index 1b0085e51478b..ac3ecea87abac 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -137,17 +137,26 @@ function getModifierFlags(node: Node): ModifierFlags { } export function getCombinedModifierFlags(node: Declaration): ModifierFlags { + return getCombinedFlags(node, getModifierFlags); +} + +/** Includes flags carried by a binding's root declaration, declaration list, and statement. */ +export function getCombinedNodeFlags(node: Node): NodeFlags { + return getCombinedFlags(node, node => node.flags); +} + +function getCombinedFlags(node: Node, getFlags: (node: Node) => number): number { let current: Node | undefined = getRootDeclaration(node); - let flags = getModifierFlags(current); + let flags = getFlags(current); if (current.kind === SyntaxKind.VariableDeclaration) { current = current.parent; } if (current?.kind === SyntaxKind.VariableDeclarationList) { - flags |= getModifierFlags(current); + flags |= getFlags(current); current = current.parent; } if (current?.kind === SyntaxKind.VariableStatement) { - flags |= getModifierFlags(current); + flags |= getFlags(current); } return flags; } diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index 2571036412532..fd11c5c387324 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -103,6 +103,32 @@ test("canHaveModifiers includes the reparsed import kind in its narrowed type", } }); +test("getCombinedNodeFlags follows binding declarations to their list and statement", () => { + using api = spawnAPI(); + const source = api.createSourceFile( + "/flags.ts", + "/** @deprecated */ export const [{ value }] = input; let other = 1; var plain = 2;", + ).sourceFile; + for (const statement of source.statements) { + assert.ok(astModule.isVariableStatement(statement)); + const list = statement.declarationList; + const declaration = list.declarations[0]; + const expected = declaration.flags | list.flags | statement.flags; + assert.strictEqual(astModule.getCombinedNodeFlags(declaration), expected); + assert.strictEqual(astModule.getCombinedNodeFlags(list), list.flags | statement.flags); + assert.strictEqual(astModule.getCombinedNodeFlags(statement), statement.flags); + declaration.forEachChild(function walk(node) { + if (astModule.isBindingElement(node)) { + assert.strictEqual(astModule.getCombinedNodeFlags(node), expected); + } + node.forEachChild(walk); + }); + } + assert.strictEqual(astModule.getCombinedNodeFlags(source), source.flags); + const detached = factory.createVariableDeclaration(factory.createIdentifier("detached")); + assert.strictEqual(astModule.getCombinedNodeFlags(detached), detached.flags); +}); + test("canHaveModifiers recognizes declarations without an existing modifier list", () => { using api = spawnAPI(); const source = api.createSourceFile( From f3dc482a6ce4ced82204e2d18ab5ad0041016d04 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:19:47 -0800 Subject: [PATCH 05/13] Expose AST hasRestParameter with JSDoc variadic support Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/utils.ts | 15 ++++++++++ packages/typescript/test/sync/ast.test.ts | 34 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index ac3ecea87abac..eef946f5dd7a8 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -17,10 +17,12 @@ import type { Expression, HasExpression, HasInitializer, + JSDocSignature, ModifierLike, ObjectAssignmentInitializer, PropertyAccessExpression, PropertyAssignment, + SignatureDeclaration, SourceFile, VariableDeclaration, } from "./ast.ts"; @@ -28,6 +30,7 @@ import type { Node } from "./ast.ts"; import { isAccessExpression, isIdentifier, + isJSDocTypeExpression, isNumericLiteral, isStringLiteralLikeNode, } from "./is.generated.ts"; @@ -116,6 +119,18 @@ export function isExternalModule(file: SourceFile): boolean { return file.externalModuleIndicator !== undefined; } +/** Reports whether the final parameter is a rest parameter, including JSDoc variadic types. */ +export function hasRestParameter(node: SignatureDeclaration | JSDocSignature): boolean { + const last = node.parameters[node.parameters.length - 1]; + if (!last) return false; + if (last.kind === SyntaxKind.Parameter && last.dotDotDotToken) return true; + let type = last.kind === SyntaxKind.Parameter ? last.type + : last.kind === SyntaxKind.JSDocParameterTag ? last.typeExpression + : undefined; + if (type && isJSDocTypeExpression(type)) type = type.type; + return type?.kind === SyntaxKind.JSDocVariadicType; +} + function getRootDeclaration(node: Node): Node { while (node.kind === SyntaxKind.BindingElement) { node = node.parent.parent; diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index fd11c5c387324..01f14c62aa5da 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -103,6 +103,40 @@ test("canHaveModifiers includes the reparsed import kind in its narrowed type", } }); +test("hasRestParameter handles syntax, JSDoc signatures, and empty parameter lists", () => { + using api = spawnAPI(); + const source = api.createSourceFile( + "/rest.ts", + "function empty() {} function ordinary(value: string) {} function rest(first: number, ...values: string[]) {} type F = (...values: string[]) => void;", + ).sourceFile; + const functions = source.statements.filter(astModule.isFunctionDeclaration); + assert.deepStrictEqual(functions.map(astModule.hasRestParameter), [false, false, true]); + const alias = source.statements[3]; + assert.ok(astModule.isTypeAliasDeclaration(alias)); + assert.ok(astModule.isFunctionTypeNode(alias.type)); + assert.strictEqual(astModule.hasRestParameter(alias.type), true); + + const js = api.createSourceFile( + "/rest.js", + `/** + * @callback Callback + * @param {...string} values + */ +function callback() {} +`, + ).sourceFile; + const callback = js.statements.find(astModule.isFunctionDeclaration)?.jsDoc?.[0]; + assert.ok(callback && astModule.isJSDoc(callback)); + const tag = callback.tags?.[0]; + assert.ok(tag && astModule.isJSDocCallbackTag(tag) && astModule.isJSDocSignature(tag.typeExpression)); + assert.strictEqual(astModule.hasRestParameter(tag.typeExpression), true); + const variadic = factory.createJSDocVariadicType(factory.createKeywordTypeNode(SyntaxKind.NumberKeyword)); + const parameter = factory.createParameterDeclaration(undefined, undefined, factory.createIdentifier("values"), undefined, variadic); + const fnType = factory.createFunctionTypeNode(undefined, [parameter], factory.createKeywordTypeNode(SyntaxKind.VoidKeyword)); + assert.strictEqual(astModule.hasRestParameter(fnType), true); + assert.strictEqual(astModule.hasRestParameter(factory.createJSDocSignature(undefined, [], undefined)), false); +}); + test("getCombinedNodeFlags follows binding declarations to their list and statement", () => { using api = spawnAPI(); const source = api.createSourceFile( From d23b15bc651bf22961de0ddb1dbcaaa66dd61098 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:20:29 -0800 Subject: [PATCH 06/13] Expose identifierToKeywordKind through the scanner keyword table Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/ast/scanner.ts | 7 +++++++ packages/typescript/test/scanner.test.ts | 25 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/packages/typescript/src/ast/scanner.ts b/packages/typescript/src/ast/scanner.ts index 0f5c53d94dc59..c8a858b9e1077 100644 --- a/packages/typescript/src/ast/scanner.ts +++ b/packages/typescript/src/ast/scanner.ts @@ -6,6 +6,7 @@ import { ScriptTarget } from "../../enums/scriptTarget.js"; import { SyntaxKind } from "../../enums/syntaxKind.js"; import { TokenFlags } from "../../enums/tokenFlags.js"; import type { + Identifier, JsxTokenSyntaxKind, KeywordSyntaxKind, } from "./ast.ts"; @@ -120,6 +121,7 @@ export const textToKeywordObj: Record = { function: SyntaxKind.FunctionKeyword, get: SyntaxKind.GetKeyword, if: SyntaxKind.IfKeyword, + immediate: SyntaxKind.ImmediateKeyword, implements: SyntaxKind.ImplementsKeyword, import: SyntaxKind.ImportKeyword, in: SyntaxKind.InKeyword, @@ -177,6 +179,11 @@ export const textToKeywordObj: Record = { const textToKeyword = new Map(Object.entries(textToKeywordObj)); +/** Returns the keyword represented by an identifier's decoded text, if any. */ +export function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined { + return textToKeyword.get(node.text); +} + const textToToken = new Map(Object.entries({ ...textToKeywordObj, "{": SyntaxKind.OpenBraceToken, diff --git a/packages/typescript/test/scanner.test.ts b/packages/typescript/test/scanner.test.ts index 86a5d1f19b503..6c78610f55ca2 100644 --- a/packages/typescript/test/scanner.test.ts +++ b/packages/typescript/test/scanner.test.ts @@ -1,10 +1,35 @@ import { createScanner, + identifierToKeywordKind, SyntaxKind, } from "@typescript/typescript/ast"; +import { createIdentifier } from "@typescript/typescript/ast/factory"; import assert from "node:assert"; import { test } from "node:test"; +test("identifierToKeywordKind recognizes reserved, contextual, and type keywords", () => { + assert.strictEqual(identifierToKeywordKind(createIdentifier("class")), SyntaxKind.ClassKeyword); + assert.strictEqual(identifierToKeywordKind(createIdentifier("async")), SyntaxKind.AsyncKeyword); + assert.strictEqual(identifierToKeywordKind(createIdentifier("constructor")), SyntaxKind.ConstructorKeyword); + assert.strictEqual(identifierToKeywordKind(createIdentifier("immediate")), SyntaxKind.ImmediateKeyword); + assert.strictEqual(identifierToKeywordKind(createIdentifier("string")), SyntaxKind.StringKeyword); + for (const text of ["ordinary", "Class", "__type", "toString", "__proto__", "{"]) { + assert.strictEqual(identifierToKeywordKind(createIdentifier(text)), undefined); + } + const scanner = createScanner(true); + scanner.setText("\\u0074ype"); + scanner.scan(); + assert.strictEqual(identifierToKeywordKind(createIdentifier(scanner.getTokenValue())), SyntaxKind.TypeKeyword); +}); + +test("the scanner recognizes immediate as a keyword", () => { + const scanner = createScanner(true); + scanner.setText("immediate value"); + assert.strictEqual(scanner.scan(), SyntaxKind.ImmediateKeyword); + assert.strictEqual(scanner.getTokenValue(), "immediate"); + assert.strictEqual(scanner.scan(), SyntaxKind.Identifier); +}); + test("scanJsDocToken respects a range ending in a hyphen", () => { const text = "/** x-yy"; const scanner = createScanner(/*skipTrivia*/ true); From 4da4c9e22708cdc0b911934286d869fe668ef0b1 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:23:56 -0800 Subject: [PATCH 07/13] Add Node.getModifiers to remote and synthesized AST nodes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../typescript/src/api/node/node.generated.ts | 6 ++++ packages/typescript/src/ast/ast.ts | 3 ++ .../typescript/src/ast/factory.generated.ts | 10 ++++++- packages/typescript/src/ast/modifiers.ts | 12 ++++++++ packages/typescript/test/sync/ast.test.ts | 30 +++++++++++++++++++ tools/scripts/tsc/generate-encoder.ts | 6 ++++ tools/scripts/tsc/generate-ts-ast.ts | 7 ++++- 7 files changed, 72 insertions(+), 2 deletions(-) diff --git a/packages/typescript/src/api/node/node.generated.ts b/packages/typescript/src/api/node/node.generated.ts index 15782dc0b2a0a..768802ab70791 100644 --- a/packages/typescript/src/api/node/node.generated.ts +++ b/packages/typescript/src/api/node/node.generated.ts @@ -5,12 +5,14 @@ import { getFirstToken, getLastToken, getTokenPosOfNode, + type Modifier, ModifierFlags, type Node, type NodeArray, type SourceFile, SyntaxKind, } from "../../ast/index.ts"; +import { getModifiers } from "../../ast/modifiers.ts"; import { modifierToFlag, NODE_CHILD_MASK, @@ -961,6 +963,10 @@ export class RemoteNode extends RemoteNodeBase implements Node { // ═══ Generated extended data property getters ═══ + getModifiers(): readonly Modifier[] | undefined { + return getModifiers(this as unknown as Node); + } + // ═══ Other property getters ═══ get flags(): number { diff --git a/packages/typescript/src/ast/ast.ts b/packages/typescript/src/ast/ast.ts index 260ee470615d3..30349a8b2a6f6 100644 --- a/packages/typescript/src/ast/ast.ts +++ b/packages/typescript/src/ast/ast.ts @@ -45,6 +45,7 @@ import type { KeywordSyntaxKind, MethodDeclaration, MethodSignatureDeclaration, + Modifier, ModifierSyntaxKind, ModuleDeclaration, ParameterDeclaration, @@ -214,6 +215,8 @@ export interface Node extends ReadonlyTextRange { getChildren(sourceFile?: SourceFile): readonly Node[]; getFirstToken(sourceFile?: SourceFile): Node | undefined; getLastToken(sourceFile?: SourceFile): Node | undefined; + /** Gets syntactic modifiers without decorators, or `undefined` if there are none. */ + getModifiers(): readonly Modifier[] | undefined; } export interface FileReference extends TextRange { diff --git a/packages/typescript/src/ast/factory.generated.ts b/packages/typescript/src/ast/factory.generated.ts index 32087b20cb5dd..fa16010e07c81 100644 --- a/packages/typescript/src/ast/factory.generated.ts +++ b/packages/typescript/src/ast/factory.generated.ts @@ -160,6 +160,7 @@ import type { MethodSignatureDeclaration, MinusToken, MissingDeclaration, + Modifier, ModifierLike, ModuleBlock, ModuleBody, @@ -266,7 +267,10 @@ import { getLastToken, getTokenPosOfNode, } from "./astnav.ts"; -import { modifierToFlag } from "./modifiers.ts"; +import { + getModifiers, + modifierToFlag, +} from "./modifiers.ts"; import { cloneSourceFileData } from "./utils.ts"; import { forEachChildOfJSDocParameterTag, @@ -700,6 +704,10 @@ export class NodeObject { return flags; } + getModifiers(): readonly Modifier[] | undefined { + return getModifiers(this as unknown as Node); + } + forEachChild(visitor: (node: Node) => T, visitArray?: (nodes: NodeArray) => T): T | undefined { const fn = forEachChildTable[this.kind]; return fn ? fn(this._data, visitor, visitArray) : undefined; diff --git a/packages/typescript/src/ast/modifiers.ts b/packages/typescript/src/ast/modifiers.ts index 32ca0c053ba47..e1892c7dbe951 100644 --- a/packages/typescript/src/ast/modifiers.ts +++ b/packages/typescript/src/ast/modifiers.ts @@ -1,5 +1,17 @@ import { ModifierFlags } from "../../enums/modifierFlags.js"; import { SyntaxKind } from "../../enums/syntaxKind.js"; +import type { + Modifier, + ModifierLike, + Node, +} from "./ast.ts"; +import { isModifier } from "./is.generated.ts"; + +/** @internal */ +export function getModifiers(node: Node & { readonly modifiers?: readonly ModifierLike[] | undefined; }): readonly Modifier[] | undefined { + const modifiers = node.modifiers?.filter(isModifier); + return modifiers?.length ? modifiers : undefined; +} export function modifierToFlag(kind: SyntaxKind): ModifierFlags { switch (kind) { diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index 01f14c62aa5da..daa0eba553697 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -103,6 +103,36 @@ test("canHaveModifiers includes the reparsed import kind in its narrowed type", } }); +test("Node.getModifiers excludes decorators on parsed, synthesized, and cloned nodes", () => { + using api = spawnAPI(); + const source = api.createSourceFile( + "/nodeModifiers.ts", + "@dec export class C { @dec public static method() {} } @dec class Decorated {} class Plain {}", + ).sourceFile; + const declaration = source.statements[0]; + assert.ok(astModule.isClassDeclaration(declaration)); + const node: Node = declaration; + const modifiers: readonly astModule.Modifier[] | undefined = node.getModifiers(); + assert.deepStrictEqual(modifiers?.map(modifier => modifier.kind), [SyntaxKind.ExportKeyword]); + assert.deepStrictEqual( + declaration.members[0].getModifiers()?.map(modifier => modifier.kind), + [SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword], + ); + assert.strictEqual(source.statements[1].getModifiers(), undefined); + assert.strictEqual(source.statements[2].getModifiers(), undefined); + assert.strictEqual(source.getModifiers(), undefined); + const synthesized = factory.createClassDeclaration(declaration.modifiers, declaration.name, undefined, undefined, []); + assert.deepStrictEqual(synthesized.getModifiers()?.map(modifier => modifier.kind), [SyntaxKind.ExportKeyword]); + assert.deepStrictEqual(cloneNode(synthesized).getModifiers()?.map(modifier => modifier.kind), [SyntaxKind.ExportKeyword]); + assert.strictEqual(factory.createClassDeclaration([], undefined, undefined, undefined, []).getModifiers(), undefined); + const recovery = factory.createMissingDeclaration([ + factory.createDecorator(factory.createIdentifier("dec")), + factory.createToken(SyntaxKind.ExportKeyword), + ]); + assert.strictEqual(astModule.canHaveModifiers(recovery), false); + assert.deepStrictEqual(recovery.getModifiers()?.map(modifier => modifier.kind), [SyntaxKind.ExportKeyword]); +}); + test("hasRestParameter handles syntax, JSDoc signatures, and empty parameter lists", () => { using api = spawnAPI(); const source = api.createSourceFile( diff --git a/tools/scripts/tsc/generate-encoder.ts b/tools/scripts/tsc/generate-encoder.ts index fa8d7236adf21..5ded04fee48aa 100644 --- a/tools/scripts/tsc/generate-encoder.ts +++ b/tools/scripts/tsc/generate-encoder.ts @@ -1486,11 +1486,13 @@ function emitNodeGeneratedImports(w: CodeWriter) { w.write(` getLastToken,`); w.write(` getTokenPosOfNode,`); w.write(` ModifierFlags,`); + w.write(` type Modifier,`); w.write(` type Node,`); w.write(` type NodeArray,`); w.write(` type SourceFile,`); w.write(` SyntaxKind,`); w.write(`} from "../../ast/index.ts";`); + w.write(`import { getModifiers } from "../../ast/modifiers.ts";`); w.write(`import {`); w.write(` childProperties,`); w.write(` KIND_NODE_LIST,`); @@ -2028,6 +2030,10 @@ function emitExtendedDataGetters(w: CodeWriter) { } function emitRemoteNodeClassClose(w: CodeWriter) { + w.write(` getModifiers(): readonly Modifier[] | undefined {`); + w.write(` return getModifiers(this as unknown as Node);`); + w.write(` }`); + w.write(``); w.write(` // ═══ Other property getters ═══`); w.write(``); w.write(` get flags(): number {`); diff --git a/tools/scripts/tsc/generate-ts-ast.ts b/tools/scripts/tsc/generate-ts-ast.ts index 7aef579c62b06..777e54af5dcf5 100644 --- a/tools/scripts/tsc/generate-ts-ast.ts +++ b/tools/scripts/tsc/generate-ts-ast.ts @@ -651,6 +651,7 @@ function generateFactory(): string { importTypes.delete("NodeFlags"); importTypes.delete("SyntaxKind"); importTypes.delete("TokenFlags"); + importTypes.add("Modifier"); // ── Header ── out.push(`// Code generated by tools/scripts/tsc/generate-ts-ast.ts. DO NOT EDIT.`); @@ -666,7 +667,7 @@ function generateFactory(): string { out.push(` ${t},`); } out.push(`} from "./ast.ts";`); - out.push(`import { modifierToFlag } from "./modifiers.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 {`); @@ -731,6 +732,10 @@ function generateFactory(): string { out.push(``); // Methods + out.push(` getModifiers(): readonly Modifier[] | undefined {`); + out.push(` return getModifiers(this as unknown as Node);`); + out.push(` }`); + out.push(``); out.push(` forEachChild(visitor: (node: Node) => T, visitArray?: (nodes: NodeArray) => T): T | undefined {`); out.push(` const fn = forEachChildTable[this.kind];`); out.push(` return fn ? fn(this._data, visitor, visitArray) : undefined;`); From f2f50ccad9aa3796b7091036a0dc4272687b374d Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:27:24 -0800 Subject: [PATCH 08/13] Expose private symbol display names through Symbol.name Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 4 +-- .../typescript/src/api/proto.generated.ts | 1 + packages/typescript/src/api/sync/api.ts | 4 +-- packages/typescript/test/async/api.test.ts | 26 +++++++++++++++++++ packages/typescript/test/sync/api.test.ts | 26 +++++++++++++++++++ tsc/internal/api/proto.go | 1 + tsc/internal/api/session.go | 3 +++ 7 files changed, 61 insertions(+), 4 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 7256e47c0da36..6efa7e360aaa8 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -3444,7 +3444,7 @@ export class Symbol { } /** The escaped (`__String`) name, used as the key in member/export tables. */ readonly escapedName: __String; - /** The display name (escaped underscores removed). */ + /** The display name, including the source spelling of private identifiers. */ readonly name: string; readonly flags: SymbolFlags; readonly checkFlags: CheckFlags; @@ -3466,7 +3466,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = unescapeLeadingUnderscores(data.name as __String); + this.name = data.displayName ?? unescapeLeadingUnderscores(data.name as __String); this.flags = data.flags; this.checkFlags = data.checkFlags ?? 0; this.declarationHandles = data.declarations; diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index a86805e142df9..e019b6071c459 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -283,6 +283,7 @@ export interface GetSymbolOfDeclarationParams { export interface SymbolResponse { reference: SymbolReference; name: string; + displayName?: string | undefined; flags: number; checkFlags?: number | undefined; declarations?: string[] | undefined; diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5534ffd53e1df..99235a03639df 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -7086,7 +7086,7 @@ export class Symbol { } /** The escaped (`__String`) name, used as the key in member/export tables. */ readonly escapedName: __String; - /** The display name (escaped underscores removed). */ + /** The display name, including the source spelling of private identifiers. */ readonly name: string; readonly flags: SymbolFlags; readonly checkFlags: CheckFlags; @@ -7108,7 +7108,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = unescapeLeadingUnderscores(data.name as __String); + this.name = data.displayName ?? unescapeLeadingUnderscores(data.name as __String); this.flags = data.flags; this.checkFlags = data.checkFlags ?? 0; this.declarationHandles = data.declarations; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 3f303868a73cc..9202d0069e831 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -19,6 +19,7 @@ import { isJSDoc, isJSDocParameterTag, isJsxSelfClosingElement, + isMethodDeclaration, isModuleDeclaration, isNamedImports, isObjectLiteralExpression, @@ -7171,6 +7172,31 @@ notCallable(); }); describe("Symbol - escaped names and tables", { concurrency }, () => { + test("private member display names do not expose unique symbol table keys", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": "export class A { #value = 1; #method() {} } export class B { #value = 2; }", + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = await project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const symbols = []; + for (const declaration of source.statements.filter(isClassDeclaration)) { + for (const member of declaration.members) { + if (!(isPropertyDeclaration(member) || isMethodDeclaration(member)) || !isPrivateIdentifier(member.name)) continue; + const symbol = await project.checker.getSymbolAtLocation(member.name); + assert.ok(symbol); + assert.strictEqual(symbol.name, member.name.text); + assert.notStrictEqual(symbol.escapedName, symbol.name); + symbols.push(symbol); + } + } + assert.strictEqual(symbols.length, 3); + assert.notStrictEqual(symbols[0].escapedName, symbols[2].escapedName); + assert.strictEqual(symbols[0].name, symbols[2].name); + }); + test("getExports/getMembers return a cached Map keyed by escaped name", async () => { await using api = spawnAPI({ "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index c57ca53e905bc..01f520483e25c 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -27,6 +27,7 @@ import { isJSDoc, isJSDocParameterTag, isJsxSelfClosingElement, + isMethodDeclaration, isModuleDeclaration, isNamedImports, isObjectLiteralExpression, @@ -6929,6 +6930,31 @@ notCallable(); }); describe("Symbol - escaped names and tables", { concurrency }, () => { + test("private member display names do not expose unique symbol table keys", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": "export class A { #value = 1; #method() {} } export class B { #value = 2; }", + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const symbols = []; + for (const declaration of source.statements.filter(isClassDeclaration)) { + for (const member of declaration.members) { + if (!(isPropertyDeclaration(member) || isMethodDeclaration(member)) || !isPrivateIdentifier(member.name)) continue; + const symbol = project.checker.getSymbolAtLocation(member.name); + assert.ok(symbol); + assert.strictEqual(symbol.name, member.name.text); + assert.notStrictEqual(symbol.escapedName, symbol.name); + symbols.push(symbol); + } + } + assert.strictEqual(symbols.length, 3); + assert.notStrictEqual(symbols[0].escapedName, symbols[2].escapedName); + assert.strictEqual(symbols[0].name, symbols[2].name); + }); + test("getExports/getMembers return a cached Map keyed by escaped name", () => { using api = spawnAPI({ "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index bd3e25f6d929e..c84bda136600d 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -1171,6 +1171,7 @@ type GetSymbolsAtLocationsParams struct { type SymbolResponse struct { Reference SymbolReference `json:"reference"` Name string `json:"name"` + DisplayName string `json:"displayName,omitempty"` Flags uint32 `json:"flags"` CheckFlags uint32 `json:"checkFlags,omitzero"` Declarations []NodeHandle `json:"declarations,omitempty"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 7916279532872..a8fc3a290c912 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -254,6 +254,9 @@ func buildSymbolResponse(symbol *ast.Symbol, reference SymbolReference, owner *a Parent: newSymbolReference(symbol.Parent()), ExportSymbol: newSymbolReference(symbol.ExportSymbol()), } + if name := ast.SymbolName(symbol); name != symbol.Name() { + resp.DisplayName = name + } if owner != nil { // A client resolves a file-owned symbol's relationships through its own source file. compilerdebug.Assert(symbol.Parent() == nil || symbolOwnerFile(symbol.Parent()) == owner, "File-owned symbol parent belongs to another owner") From b423761bf3aadbf83079b369d3094353d65967c9 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:31:34 -0800 Subject: [PATCH 09/13] Expose native default formatting settings on API Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 8 +++++ .../typescript/src/api/proto.generated.ts | 10 ++++-- packages/typescript/src/api/sync/api.ts | 22 ++++++++++++ packages/typescript/test/async/api.test.ts | 36 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 1 + packages/typescript/test/sync/api.test.ts | 36 +++++++++++++++++++ tools/gen-proto/main.go | 3 +- tools/gen-proto/main_test.go | 3 +- tsc/internal/api/proto.go | 2 ++ tsc/internal/api/session.go | 8 +++++ tsc/internal/ls/lsutil/formatcodeoptions.go | 25 +++++++++++++ 11 files changed, 150 insertions(+), 4 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 6efa7e360aaa8..f8a48cdc36d7f 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -88,6 +88,7 @@ import type { DocumentPosition, EmitOutputResponse as ProtocolEmitOutputResponse, FileNotifications, + FormatCodeSettings, ImportAdderAction, InferredProjectId, IntrinsicTypeMethod, @@ -219,6 +220,7 @@ export type { EmitOutputFile, EmitResult, FileNotifications, + FormatCodeSettings, FormatDiagnosticsHost, FreshableType, GenericType, @@ -506,6 +508,12 @@ export class API implements FormatDiagnosticsHo return orchestrator; } + /** Gets the compiler's default formatting settings, independent of snapshot preferences. */ + async getDefaultFormatCodeSettings(): Promise { + await this.ensureInitialized(); + return this.client.apiRequest("getDefaultFormatCodeSettings", null); + } + async parseConfigFile(file: DocumentIdentifier): Promise { await this.ensureInitialized(); return this.client.apiRequest("parseConfigFile", { file }); diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index e019b6071c459..097214faa235a 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -19,7 +19,10 @@ import type { CompilerOptions, PluginImport, } from "./compilerOptions.generated.ts"; -import type { UserPreferences } from "./userPreferences.generated.ts"; +import type { + FormatCodeSettings, + UserPreferences, +} from "./userPreferences.generated.ts"; export { CaseSensitivity } from "../../enums/caseSensitivity.js"; export { JsxEmit } from "../../enums/jsxEmit.js"; @@ -33,7 +36,7 @@ export { SymbolOwnerKind } from "../../enums/symbolOwnerKind.js"; export type { PathKey, RootedDirectoryPath, RootedFilePath, RootedPath } from "../ast/index.ts"; export type { CompilerOptions, PluginImport } from "./compilerOptions.generated.ts"; export * from "./compilerOptions.generated.ts"; -export type { UserPreferences } from "./userPreferences.generated.ts"; +export type { FormatCodeSettings, UserPreferences } from "./userPreferences.generated.ts"; export type APIMethod = { params: TParams; result: TResult; }; @@ -45,6 +48,7 @@ export interface APIMethodInfo { getSymbolOfDeclaration: APIMethod; batchRequests: APIMethod; initialize: APIMethod; + getDefaultFormatCodeSettings: APIMethod; createSnapshot: APIMethod; updateSnapshot: APIMethod; getCurrentLanguageServerSnapshot: APIMethod; @@ -1261,6 +1265,7 @@ export interface BatchRequest { | "getDeclarationDiagnostics" | "getDeclarationEmit" | "getDeclaredTypeOfSymbol" + | "getDefaultFormatCodeSettings" | "getDefaultFromTypeParameter" | "getDefaultProjectForFile" | "getDocumentationComment" @@ -1456,6 +1461,7 @@ export interface BatchResponse { | "getDeclarationDiagnostics" | "getDeclarationEmit" | "getDeclaredTypeOfSymbol" + | "getDefaultFormatCodeSettings" | "getDefaultFromTypeParameter" | "getDefaultProjectForFile" | "getDocumentationComment" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 99235a03639df..e41abe732bc58 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -107,6 +107,7 @@ import type { DocumentPosition, EmitOutputResponse as ProtocolEmitOutputResponse, FileNotifications, + FormatCodeSettings, ImportAdderAction, InferredProjectId, IntrinsicTypeMethod, @@ -237,6 +238,7 @@ export type { EmitOutputFile, EmitResult, FileNotifications, + FormatCodeSettings, FormatDiagnosticsHost, FreshableType, GenericType, @@ -633,6 +635,26 @@ export class API implements FormatDiagnosticsHo ); } + /** Gets the compiler's default formatting settings, independent of snapshot preferences. */ + get getDefaultFormatCodeSettings(): { + (): FormatCodeSettings; + gen(): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getDefaultFormatCodeSettings", + function (): FormatCodeSettings { + owner.ensureInitialized(); + return owner.client.apiRequest("getDefaultFormatCodeSettings", null); + }, + function* (): Generator { + yield* owner.ensureInitialized.gen(); + return yield* apiRequest("getDefaultFormatCodeSettings", null); + }, + ); + } + get parseConfigFile(): { (file: DocumentIdentifier): ParsedCommandLine; gen(file: DocumentIdentifier): Generator; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 9202d0069e831..399e5b2d5ce7d 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -171,6 +171,42 @@ import { const concurrency = areTestsFiltered(); describe("API", { concurrency }, () => { + test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", async () => { + await using api = spawnAPI(); + const defaults = await api.getDefaultFormatCodeSettings(); + assert.deepStrictEqual(defaults, { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: "smart", + trimTrailingWhitespace: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + semicolons: "ignore", + indentSwitchCase: true, + }); + const snapshot = await api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } }); + assert.ok(snapshot); + defaults.indentSize = 2; + const next = await api.getDefaultFormatCodeSettings(); + assert.strictEqual(next.indentSize, 4); + assert.strictEqual(next.convertTabsToSpaces, true); + }); + test("getCurrentLanguageServerSnapshot is LSP-only", async () => { if (!!false) { await using standalone = new API(); diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 32122666a9e48..39d6be9a1f038 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1594,6 +1594,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => exercisedMethods.add("API.createModuleResolver"); const cases: ParityCase[] = [ + parityCase("API", "getDefaultFormatCodeSettings", api.getDefaultFormatCodeSettings, assertDeepEquivalent), parityCase("API", "parseConfigFile", api.parseConfigFile, assertDeepEquivalent, "/tsconfig.json"), parityCase("API", "parseCommandLine", api.parseCommandLine, assertDeepEquivalent, ["--strict", "--noEmit"]), parityCase("API", "readConfigFile", api.readConfigFile, assertDeepEquivalent, "/tsconfig.json"), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 01f520483e25c..b31330853df92 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -179,6 +179,42 @@ import { const concurrency = areTestsFiltered(); describe("API", { concurrency }, () => { + test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", () => { + using api = spawnAPI(); + const defaults = api.getDefaultFormatCodeSettings(); + assert.deepStrictEqual(defaults, { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: "smart", + trimTrailingWhitespace: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + semicolons: "ignore", + indentSwitchCase: true, + }); + const snapshot = api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } }); + assert.ok(snapshot); + defaults.indentSize = 2; + const next = api.getDefaultFormatCodeSettings(); + assert.strictEqual(next.indentSize, 4); + assert.strictEqual(next.convertTabsToSpaces, true); + }); + test("getCurrentLanguageServerSnapshot is LSP-only", () => { if (!!false) { using standalone = new API(); diff --git a/tools/gen-proto/main.go b/tools/gen-proto/main.go index ba89387965e9a..a9436aa43d0d7 100644 --- a/tools/gen-proto/main.go +++ b/tools/gen-proto/main.go @@ -520,7 +520,8 @@ func (r *typeRenderer) namedType(named *types.Named) string { return r.importTypeOnly("CompilerOptions", "./compilerOptions.generated.ts") case "github.com/microsoft/TypeScript/tsc/internal/core.PluginImport": return r.importTypeOnly("PluginImport", "./compilerOptions.generated.ts") - case "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.UserPreferences": + case "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.UserPreferences", + "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil.FormatCodeSettings": return r.importTypeOnly(obj.Name(), "./userPreferences.generated.ts") case "github.com/microsoft/TypeScript/tsc/internal/core.JsxEmit": return r.importType("JsxEmit", "../../enums/jsxEmit.js") diff --git a/tools/gen-proto/main_test.go b/tools/gen-proto/main_test.go index c7cb555c4cd36..90bdb7b99f3d3 100644 --- a/tools/gen-proto/main_test.go +++ b/tools/gen-proto/main_test.go @@ -33,7 +33,8 @@ func TestGenerate(t *testing.T) { `export interface UpdateSnapshotParams`, `export interface CreateSnapshotParams extends SnapshotRequestChangesParams`, `export interface LanguageServerSnapshotChanges extends SnapshotRequestChangesParams`, - `import type { UserPreferences } from "./userPreferences.generated.ts";`, + `import type { FormatCodeSettings, UserPreferences } from "./userPreferences.generated.ts";`, + `getDefaultFormatCodeSettings: APIMethod;`, `userPreferences?: UserPreferences | undefined;`, `prepareAutoImports?: DocumentIdentifier | undefined;`, `openProjects?: readonly DocumentIdentifier[] | undefined;`, diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index c84bda136600d..41b80e1c61081 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -76,6 +76,7 @@ const ( MethodBatchRequests Method = "batchRequests" MethodInitialize Method = "initialize" + MethodGetDefaultFormatCodeSettings Method = "getDefaultFormatCodeSettings" MethodCreateSnapshot Method = "createSnapshot" MethodUpdateSnapshot Method = "updateSnapshot" MethodGetCurrentLanguageServerSnapshot Method = "getCurrentLanguageServerSnapshot" @@ -616,6 +617,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetCachedSourceFile: unmarshallerFor[GetCachedSourceFileParams], MethodGetSymbolOfDeclaration: unmarshallerFor[GetSymbolOfDeclarationParams], MethodInitialize: noParams, + MethodGetDefaultFormatCodeSettings: noParams, MethodCreateSnapshot: unmarshallerFor[CreateSnapshotParams], MethodUpdateSnapshot: unmarshallerFor[UpdateSnapshotParams], MethodGetCurrentLanguageServerSnapshot: unmarshallerFor[GetCurrentLanguageServerSnapshotParams], diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index a8fc3a290c912..9eb36aa1ea5d8 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -34,6 +34,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ls" "github.com/microsoft/TypeScript/tsc/internal/ls/autoimport" "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/module" "github.com/microsoft/TypeScript/tsc/internal/nodebuilder" @@ -904,6 +905,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetSymbolOfDeclaration(parsed.(*GetSymbolOfDeclarationParams)) case string(MethodInitialize): return s.handleInitialize(ctx) + case string(MethodGetDefaultFormatCodeSettings): + return s.handleGetDefaultFormatCodeSettings() case string(MethodCreateSnapshot): return s.handleCreateSnapshot(ctx, parsed.(*CreateSnapshotParams)) case string(MethodUpdateSnapshot): @@ -1442,6 +1445,11 @@ func (s *Session) handleInitialize(ctx context.Context) (*InitializeResponse, er }, nil } +func (s *Session) handleGetDefaultFormatCodeSettings() (*lsutil.FormatCodeSettings, error) { + settings := lsutil.GetDefaultFormatCodeSettings() + return &settings, nil +} + // handleCreateSnapshot creates a new independent snapshot. func (s *Session) handleCreateSnapshot(ctx context.Context, params *CreateSnapshotParams) (*CreateSnapshotResponse, error) { apiRequest, err := s.toAPISnapshotRequest(ctx, ¶ms.SnapshotRequestChangesParams) diff --git a/tsc/internal/ls/lsutil/formatcodeoptions.go b/tsc/internal/ls/lsutil/formatcodeoptions.go index bbfd79e98a4c3..40c5deb0ab691 100644 --- a/tsc/internal/ls/lsutil/formatcodeoptions.go +++ b/tsc/internal/ls/lsutil/formatcodeoptions.go @@ -1,7 +1,10 @@ package lsutil import ( + "fmt" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/json" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/printer" ) @@ -22,6 +25,28 @@ const ( SemicolonPreferenceRemove SemicolonPreference = "remove" ) +func (settings *FormatCodeSettings) MarshalJSONTo(enc *json.Encoder) error { + var indentStyle string + switch settings.IndentStyle { + case IndentStyleNone: + indentStyle = "none" + case IndentStyleBlock: + indentStyle = "block" + case IndentStyleSmart: + indentStyle = "smart" + default: + return fmt.Errorf("invalid indent style: %d", settings.IndentStyle) + } + type formatCodeSettings FormatCodeSettings + return json.MarshalEncode(enc, struct { + *formatCodeSettings + IndentStyle string `json:"indentStyle"` + }{ + formatCodeSettings: (*formatCodeSettings)(settings), + IndentStyle: indentStyle, + }) +} + func FromLSFormatOptions(f FormatCodeSettings, opt *lsproto.FormattingOptions) FormatCodeSettings { updatedSettings := f updatedSettings.TabSize = int(opt.TabSize) From 8db3076c0471da1692d21a5a4d999ec284c0984e Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Thu, 19 Nov 2026 13:00:57 -0800 Subject: [PATCH 10/13] Expose client-side symbolName without extending symbol responses Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 4 ++-- .../typescript/src/api/proto.generated.ts | 1 - packages/typescript/src/api/sync/api.ts | 4 ++-- packages/typescript/src/ast/utils.ts | 6 ++++++ packages/typescript/test/async/api.test.ts | 19 +++++++++++++++++++ packages/typescript/test/sync/api.test.ts | 19 +++++++++++++++++++ tsc/internal/api/proto.go | 1 - tsc/internal/api/session.go | 3 --- 8 files changed, 48 insertions(+), 9 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index f8a48cdc36d7f..eca8780f3a82f 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -35,9 +35,9 @@ import { type RootedFilePath, type SourceFile, type StringLiteralLikeNode, + symbolName, type SyntaxKind, type TypeNode, - unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { assertNever } from "../../internal/utils.ts"; import { @@ -3474,7 +3474,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = data.displayName ?? unescapeLeadingUnderscores(data.name as __String); + this.name = symbolName(this); this.flags = data.flags; this.checkFlags = data.checkFlags ?? 0; this.declarationHandles = data.declarations; diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 097214faa235a..735e79b009fef 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -287,7 +287,6 @@ export interface GetSymbolOfDeclarationParams { export interface SymbolResponse { reference: SymbolReference; name: string; - displayName?: string | undefined; flags: number; checkFlags?: number | undefined; declarations?: string[] | undefined; diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index e41abe732bc58..74b0257aa93f3 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -54,9 +54,9 @@ import { type RootedFilePath, type SourceFile, type StringLiteralLikeNode, + symbolName, type SyntaxKind, type TypeNode, - unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { assertNever } from "../../internal/utils.ts"; import { @@ -7130,7 +7130,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = data.displayName ?? unescapeLeadingUnderscores(data.name as __String); + this.name = symbolName(this); this.flags = data.flags; this.checkFlags = data.checkFlags ?? 0; this.declarationHandles = data.declarations; diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index eef946f5dd7a8..7f834fe5caf7b 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -67,6 +67,12 @@ export function unescapeLeadingUnderscores(identifier: __String): string { : id; } +/** Gets a symbol's display name from its escaped symbol-table key. */ +export function symbolName(symbol: { readonly escapedName: __String; }): string { + const privateName = /^__#\d+@(#.*)$/.exec(symbol.escapedName); + return privateName ? privateName[1] : unescapeLeadingUnderscores(symbol.escapedName); +} + /** * Add an extra leading underscore to a display name that already begins with * `__`, producing its escaped {@link __String} key. diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 399e5b2d5ce7d..360996dc29a12 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -43,6 +43,7 @@ import { type PathKey, type RootedFilePath, type SourceFile, + symbolName, SyntaxKind, tryGetAmbientModuleNameFromSymbolName, unescapeLeadingUnderscores, @@ -7223,6 +7224,7 @@ describe("Symbol - escaped names and tables", { concurrency }, () => { if (!(isPropertyDeclaration(member) || isMethodDeclaration(member)) || !isPrivateIdentifier(member.name)) continue; const symbol = await project.checker.getSymbolAtLocation(member.name); assert.ok(symbol); + assert.strictEqual(symbolName(symbol), member.name.text); assert.strictEqual(symbol.name, member.name.text); assert.notStrictEqual(symbol.escapedName, symbol.name); symbols.push(symbol); @@ -7331,6 +7333,23 @@ export { x as '${maliciousName}' }; }); }); +describe("ast - symbolName", { concurrency }, () => { + test("decodes private keys without changing escaped user names or internal names", () => { + for ( + const [escapedName, expected] of [ + ["__#1@#value", "#value"], + ["__#42@#method", "#method"], + [escapeLeadingUnderscores("__#1@#value"), "__#1@#value"], + [escapeLeadingUnderscores("__value"), "__value"], + [InternalSymbolName.Type, "__type"], + ["value", "value"], + ] + ) { + assert.strictEqual(symbolName({ escapedName: escapedName as __String }), expected); + } + }); +}); + describe("ast - escapeLeadingUnderscores", { concurrency }, () => { test("round-trips display and escaped names", () => { assert.equal(escapeLeadingUnderscores("foo"), "foo"); diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index b31330853df92..1704282758758 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -51,6 +51,7 @@ import { type PathKey, type RootedFilePath, type SourceFile, + symbolName, SyntaxKind, tryGetAmbientModuleNameFromSymbolName, unescapeLeadingUnderscores, @@ -6981,6 +6982,7 @@ describe("Symbol - escaped names and tables", { concurrency }, () => { if (!(isPropertyDeclaration(member) || isMethodDeclaration(member)) || !isPrivateIdentifier(member.name)) continue; const symbol = project.checker.getSymbolAtLocation(member.name); assert.ok(symbol); + assert.strictEqual(symbolName(symbol), member.name.text); assert.strictEqual(symbol.name, member.name.text); assert.notStrictEqual(symbol.escapedName, symbol.name); symbols.push(symbol); @@ -7089,6 +7091,23 @@ export { x as '${maliciousName}' }; }); }); +describe("ast - symbolName", { concurrency }, () => { + test("decodes private keys without changing escaped user names or internal names", () => { + for ( + const [escapedName, expected] of [ + ["__#1@#value", "#value"], + ["__#42@#method", "#method"], + [escapeLeadingUnderscores("__#1@#value"), "__#1@#value"], + [escapeLeadingUnderscores("__value"), "__value"], + [InternalSymbolName.Type, "__type"], + ["value", "value"], + ] + ) { + assert.strictEqual(symbolName({ escapedName: escapedName as __String }), expected); + } + }); +}); + describe("ast - escapeLeadingUnderscores", { concurrency }, () => { test("round-trips display and escaped names", () => { assert.equal(escapeLeadingUnderscores("foo"), "foo"); diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 41b80e1c61081..7971f16f9c96e 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -1173,7 +1173,6 @@ type GetSymbolsAtLocationsParams struct { type SymbolResponse struct { Reference SymbolReference `json:"reference"` Name string `json:"name"` - DisplayName string `json:"displayName,omitempty"` Flags uint32 `json:"flags"` CheckFlags uint32 `json:"checkFlags,omitzero"` Declarations []NodeHandle `json:"declarations,omitempty"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 9eb36aa1ea5d8..eabc32626804a 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -255,9 +255,6 @@ func buildSymbolResponse(symbol *ast.Symbol, reference SymbolReference, owner *a Parent: newSymbolReference(symbol.Parent()), ExportSymbol: newSymbolReference(symbol.ExportSymbol()), } - if name := ast.SymbolName(symbol); name != symbol.Name() { - resp.DisplayName = name - } if owner != nil { // A client resolves a file-owned symbol's relationships through its own source file. compilerdebug.Assert(symbol.Parent() == nil || symbolOwnerFile(symbol.Parent()) == owner, "File-owned symbol parent belongs to another owner") From 025487beeaf2b7af7f7d91e7da92a8d2ab8b8f92 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Thu, 19 Nov 2026 13:01:33 -0800 Subject: [PATCH 11/13] Avoid pinning default formatting settings in API tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/test/async/api.test.ts | 36 +++++----------------- packages/typescript/test/sync/api.test.ts | 36 +++++----------------- 2 files changed, 14 insertions(+), 58 deletions(-) diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 360996dc29a12..cad9ff5412b50 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -175,37 +175,15 @@ describe("API", { concurrency }, () => { test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", async () => { await using api = spawnAPI(); const defaults = await api.getDefaultFormatCodeSettings(); - assert.deepStrictEqual(defaults, { - baseIndentSize: 0, - indentSize: 4, - tabSize: 4, - newLineCharacter: "\n", - convertTabsToSpaces: true, - indentStyle: "smart", - trimTrailingWhitespace: true, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - semicolons: "ignore", - indentSwitchCase: true, - }); - const snapshot = await api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } }); + const { indentSize, convertTabsToSpaces } = defaults; + assert.ok(typeof indentSize === "number"); + assert.ok(typeof convertTabsToSpaces === "boolean"); + const snapshot = await api.createSnapshot({ userPreferences: { indentSize: indentSize + 1, convertTabsToSpaces: !convertTabsToSpaces } }); assert.ok(snapshot); - defaults.indentSize = 2; + defaults.indentSize = indentSize + 1; const next = await api.getDefaultFormatCodeSettings(); - assert.strictEqual(next.indentSize, 4); - assert.strictEqual(next.convertTabsToSpaces, true); + assert.strictEqual(next.indentSize, indentSize); + assert.strictEqual(next.convertTabsToSpaces, convertTabsToSpaces); }); test("getCurrentLanguageServerSnapshot is LSP-only", async () => { diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 1704282758758..115b29e70691c 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -183,37 +183,15 @@ describe("API", { concurrency }, () => { test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", () => { using api = spawnAPI(); const defaults = api.getDefaultFormatCodeSettings(); - assert.deepStrictEqual(defaults, { - baseIndentSize: 0, - indentSize: 4, - tabSize: 4, - newLineCharacter: "\n", - convertTabsToSpaces: true, - indentStyle: "smart", - trimTrailingWhitespace: true, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - semicolons: "ignore", - indentSwitchCase: true, - }); - const snapshot = api.createSnapshot({ userPreferences: { indentSize: 8, convertTabsToSpaces: false } }); + const { indentSize, convertTabsToSpaces } = defaults; + assert.ok(typeof indentSize === "number"); + assert.ok(typeof convertTabsToSpaces === "boolean"); + const snapshot = api.createSnapshot({ userPreferences: { indentSize: indentSize + 1, convertTabsToSpaces: !convertTabsToSpaces } }); assert.ok(snapshot); - defaults.indentSize = 2; + defaults.indentSize = indentSize + 1; const next = api.getDefaultFormatCodeSettings(); - assert.strictEqual(next.indentSize, 4); - assert.strictEqual(next.convertTabsToSpaces, true); + assert.strictEqual(next.indentSize, indentSize); + assert.strictEqual(next.convertTabsToSpaces, convertTabsToSpaces); }); test("getCurrentLanguageServerSnapshot is LSP-only", () => { From f02d36a6fd94e726713428cf7f8c1c0b4ab520cb Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 12:26:06 -0800 Subject: [PATCH 12/13] Use string-backed indent style preferences Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/userPreferences.schema.json | 2 -- tsc/internal/ls/lsutil/formatcodeoptions.go | 33 +++--------------- .../ls/lsutil/userpreferences_generated.go | 10 ++---- .../ls/lsutil/userpreferences_test.go | 34 +++++++++++++++++-- .../state/codeLensAcrossProjects.baseline | 2 +- 5 files changed, 39 insertions(+), 42 deletions(-) diff --git a/tools/userPreferences.schema.json b/tools/userPreferences.schema.json index d2f1837b5c0c2..9e34f23963aee 100644 --- a/tools/userPreferences.schema.json +++ b/tools/userPreferences.schema.json @@ -89,8 +89,6 @@ ], "type": "string", "x-config": "format.indentStyle", - "x-go-underlying": "int", - "x-accept-number": true, "default": "smart" }, "newLineCharacter": { diff --git a/tsc/internal/ls/lsutil/formatcodeoptions.go b/tsc/internal/ls/lsutil/formatcodeoptions.go index 40c5deb0ab691..bb932437eaba7 100644 --- a/tsc/internal/ls/lsutil/formatcodeoptions.go +++ b/tsc/internal/ls/lsutil/formatcodeoptions.go @@ -1,20 +1,17 @@ package lsutil import ( - "fmt" - "github.com/microsoft/TypeScript/tsc/internal/core" - "github.com/microsoft/TypeScript/tsc/internal/json" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/printer" ) -type IndentStyle int +type IndentStyle string const ( - IndentStyleNone IndentStyle = iota - IndentStyleBlock - IndentStyleSmart + IndentStyleNone IndentStyle = "none" + IndentStyleBlock IndentStyle = "block" + IndentStyleSmart IndentStyle = "smart" ) type SemicolonPreference string @@ -25,28 +22,6 @@ const ( SemicolonPreferenceRemove SemicolonPreference = "remove" ) -func (settings *FormatCodeSettings) MarshalJSONTo(enc *json.Encoder) error { - var indentStyle string - switch settings.IndentStyle { - case IndentStyleNone: - indentStyle = "none" - case IndentStyleBlock: - indentStyle = "block" - case IndentStyleSmart: - indentStyle = "smart" - default: - return fmt.Errorf("invalid indent style: %d", settings.IndentStyle) - } - type formatCodeSettings FormatCodeSettings - return json.MarshalEncode(enc, struct { - *formatCodeSettings - IndentStyle string `json:"indentStyle"` - }{ - formatCodeSettings: (*formatCodeSettings)(settings), - IndentStyle: indentStyle, - }) -} - func FromLSFormatOptions(f FormatCodeSettings, opt *lsproto.FormattingOptions) FormatCodeSettings { updatedSettings := f updatedSettings.TabSize = int(opt.TabSize) diff --git a/tsc/internal/ls/lsutil/userpreferences_generated.go b/tsc/internal/ls/lsutil/userpreferences_generated.go index a552acb6e46ca..47c1ef9bca61f 100644 --- a/tsc/internal/ls/lsutil/userpreferences_generated.go +++ b/tsc/internal/ls/lsutil/userpreferences_generated.go @@ -201,12 +201,6 @@ func parsePreferenceIndentStyle(value any) IndentStyle { return IndentStyleSmart } } - switch value := value.(type) { - case int: - return IndentStyle(value) - case float64: - return IndentStyle(value) - } return IndentStyleSmart } @@ -1061,8 +1055,8 @@ func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error { if p.FormatCodeSettings.EditorSettings.IndentSize != 0 { setNestedValue(config, "format.indentSize", int(p.FormatCodeSettings.EditorSettings.IndentSize)) } - if p.FormatCodeSettings.EditorSettings.IndentStyle != 0 { - setNestedValue(config, "format.indentStyle", int(p.FormatCodeSettings.EditorSettings.IndentStyle)) + if p.FormatCodeSettings.EditorSettings.IndentStyle != "" { + setNestedValue(config, "format.indentStyle", string(p.FormatCodeSettings.EditorSettings.IndentStyle)) } if p.FormatCodeSettings.EditorSettings.NewLineCharacter != "" { setNestedValue(config, "format.newLineCharacter", string(p.FormatCodeSettings.EditorSettings.NewLineCharacter)) diff --git a/tsc/internal/ls/lsutil/userpreferences_test.go b/tsc/internal/ls/lsutil/userpreferences_test.go index 42222958eca16..d9960fd857e79 100644 --- a/tsc/internal/ls/lsutil/userpreferences_test.go +++ b/tsc/internal/ls/lsutil/userpreferences_test.go @@ -35,6 +35,7 @@ func TestUserPreferencesParsingEdgeCases(t *testing.T) { "quotePreference": "SINGLE", "jsxAttributeCompletionStyle": "BRACES", "organizeImportsCaseFirst": "LOWER", "includeInlayParameterNameHints": "ALL", "organizeImportsTypeOrder": "FIRST", "workspaceSymbolsScope": "CURRENTPROJECT", + "indentStyle": "BLOCK", }, expected: func(p *UserPreferences) { p.QuotePreference = QuotePreferenceSingle @@ -43,6 +44,7 @@ func TestUserPreferencesParsingEdgeCases(t *testing.T) { p.InlayHintsPreferences.IncludeInlayParameterNameHints = IncludeInlayParameterNameHintsAll p.OrganizeImportsTypeOrder = OrganizeImportsTypeOrderFirst p.WorkspaceSymbolsScope = WorkspaceSymbolsScopeCurrentProject + p.IndentStyle = IndentStyleBlock }, }, { @@ -62,12 +64,11 @@ func TestUserPreferencesParsingEdgeCases(t *testing.T) { { name: "numeric conversion and array filtering", config: map[string]any{ - "maximumHoverLength": float64(9.8), "indentStyle": float64(1.7), + "maximumHoverLength": float64(9.8), "autoImportFileExcludePatterns": []any{"first", false, 3, "second"}, }, expected: func(p *UserPreferences) { p.MaximumHoverLength = 9 - p.IndentStyle = IndentStyleBlock p.AutoImportFileExcludePatterns = []string{"first", "second"} }, }, @@ -138,6 +139,8 @@ func getValidStringValue(t reflect.Type) string { return string(IncludeInlayParameterNameHintsAll) case "lsutil.SemicolonPreference": return string(SemicolonPreferenceInsert) + case "lsutil.IndentStyle": + return string(IndentStyleBlock) case "modulespecifiers.ImportModuleSpecifierPreference": return string(modulespecifiers.ImportModuleSpecifierPreferenceRelative) case "modulespecifiers.ImportModuleSpecifierEndingPreference": @@ -174,6 +177,33 @@ func TestUserPreferencesRoundtrip(t *testing.T) { }) } +func TestIndentStyleJSON(t *testing.T) { + t.Parallel() + for _, name := range []string{"none", "block", "smart"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + var prefs UserPreferences + assert.NilError(t, json.Unmarshal([]byte(`{"format":{"indentStyle":"`+name+`"}}`), &prefs)) + + encoded, err := json.Marshal(&prefs) + assert.NilError(t, err) + var config map[string]any + assert.NilError(t, json.Unmarshal(encoded, &config)) + assert.Equal(t, config["format"].(map[string]any)["indentStyle"], any(name)) + + encoded, err = json.Marshal(&prefs.FormatCodeSettings) + assert.NilError(t, err) + var settings map[string]any + assert.NilError(t, json.Unmarshal(encoded, &settings)) + assert.Equal(t, settings["indentStyle"], any(name)) + + var decoded FormatCodeSettings + assert.NilError(t, json.Unmarshal(encoded, &decoded)) + assert.Equal(t, decoded.IndentStyle, prefs.IndentStyle) + }) + } +} + func TestUserPreferencesSerialize(t *testing.T) { t.Parallel() diff --git a/tsc/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline b/tsc/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline index ddd2dc0a25c67..3138a9e4a9681 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline @@ -595,7 +595,7 @@ Config:: "convertTabsToSpaces": true, "enabled": true, "indentSize": 4, - "indentStyle": 2, + "indentStyle": "smart", "indentSwitchCase": true, "insertSpaceAfterCommaDelimiter": true, "insertSpaceAfterConstructor": false, From 83c59abbe9a42fb7fb54667920c3ec21ca7c4e13 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 12:26:56 -0800 Subject: [PATCH 13/13] Remove dedicated indent style JSON test Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../ls/lsutil/userpreferences_test.go | 27 ------------------- 1 file changed, 27 deletions(-) diff --git a/tsc/internal/ls/lsutil/userpreferences_test.go b/tsc/internal/ls/lsutil/userpreferences_test.go index d9960fd857e79..a1c4064f686c7 100644 --- a/tsc/internal/ls/lsutil/userpreferences_test.go +++ b/tsc/internal/ls/lsutil/userpreferences_test.go @@ -177,33 +177,6 @@ func TestUserPreferencesRoundtrip(t *testing.T) { }) } -func TestIndentStyleJSON(t *testing.T) { - t.Parallel() - for _, name := range []string{"none", "block", "smart"} { - t.Run(name, func(t *testing.T) { - t.Parallel() - var prefs UserPreferences - assert.NilError(t, json.Unmarshal([]byte(`{"format":{"indentStyle":"`+name+`"}}`), &prefs)) - - encoded, err := json.Marshal(&prefs) - assert.NilError(t, err) - var config map[string]any - assert.NilError(t, json.Unmarshal(encoded, &config)) - assert.Equal(t, config["format"].(map[string]any)["indentStyle"], any(name)) - - encoded, err = json.Marshal(&prefs.FormatCodeSettings) - assert.NilError(t, err) - var settings map[string]any - assert.NilError(t, json.Unmarshal(encoded, &settings)) - assert.Equal(t, settings["indentStyle"], any(name)) - - var decoded FormatCodeSettings - assert.NilError(t, json.Unmarshal(encoded, &decoded)) - assert.Equal(t, decoded.IndentStyle, prefs.IndentStyle) - }) - } -} - func TestUserPreferencesSerialize(t *testing.T) { t.Parallel()