diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 0eda8697d70d6..6042da5009d04 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -43,10 +43,10 @@ import { type RootedFilePath, type SourceFile, type StringLiteralLikeNode, + symbolName, type SyntaxKind, type TypeNode, type TypeParameterDeclaration, - unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { assertNever } from "../../internal/utils.ts"; import { @@ -103,6 +103,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, @@ -525,6 +527,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); + } + /** Returns configured type roots or ancestor node_modules/@types candidates, without checking directory existence. */ async getEffectiveTypeRoots(compilerOptions: RawCompilerOptions): Promise { await this.ensureInitialized(); @@ -3659,7 +3667,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; @@ -3681,7 +3689,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = 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/node/node.generated.ts b/packages/typescript/src/api/node/node.generated.ts index 2df187c1d6aa3..f63f4167277eb 100644 --- a/packages/typescript/src/api/node/node.generated.ts +++ b/packages/typescript/src/api/node/node.generated.ts @@ -7,12 +7,14 @@ import { getTokenPosOfNode, isJSDoc, type JSDoc, + 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, @@ -963,6 +965,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/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 5e1aab1e3af0a..a3da313200faa 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; @@ -1366,6 +1370,7 @@ export interface BatchRequest { | "getDeclarationDiagnostics" | "getDeclarationEmit" | "getDeclaredTypeOfSymbol" + | "getDefaultFormatCodeSettings" | "getDefaultFromTypeParameter" | "getDefaultProjectForFile" | "getDocumentationComment" @@ -1579,6 +1584,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 9e9926d803800..adb09a2a9b2cc 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -62,10 +62,10 @@ import { type RootedFilePath, type SourceFile, type StringLiteralLikeNode, + symbolName, type SyntaxKind, type TypeNode, type TypeParameterDeclaration, - unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { assertNever } from "../../internal/utils.ts"; import { @@ -122,6 +122,7 @@ import type { DocumentPosition, EmitOutputResponse as ProtocolEmitOutputResponse, FileNotifications, + FormatCodeSettings, ImportAdderAction, InferredProjectId, IntrinsicTypeMethod, @@ -255,6 +256,7 @@ export type { EmitOutputFile, EmitResult, FileNotifications, + FormatCodeSettings, FormatDiagnosticsHost, FreshableType, GenericType, @@ -652,6 +654,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); + }, + ); + } + /** Returns configured type roots or ancestor node_modules/@types candidates, without checking directory existence. */ get getEffectiveTypeRoots(): { (compilerOptions: RawCompilerOptions): readonly RootedDirectoryPath[]; @@ -7650,7 +7672,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; @@ -7672,7 +7694,7 @@ export class Symbol { this.reference = data.reference; this.escapedName = data.name as __String; - this.name = 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/ast.ts b/packages/typescript/src/ast/ast.ts index d502577d7b256..efe7cc946d001 100644 --- a/packages/typescript/src/ast/ast.ts +++ b/packages/typescript/src/ast/ast.ts @@ -8,18 +8,25 @@ 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, BindingPattern, CallExpression, CaseClause, + ClassDeclaration, + ClassExpression, ComputedPropertyName, + ConstructorDeclaration, + ConstructorTypeNode, Decorator, DoStatement, ElementAccessExpression, EndOfFile, EntityName, + EnumDeclaration, EnumMember, + ExportAssignment, ExportDeclaration, ExportSpecifier, Expression, @@ -27,17 +34,27 @@ import type { ForInStatement, ForOfStatement, ForStatement, + FunctionDeclaration, + FunctionExpression, + GetAccessorDeclaration, Identifier, IfStatement, ImportClause, + ImportDeclaration, ImportEqualsDeclaration, ImportSpecifier, + IndexSignatureDeclaration, + InterfaceDeclaration, JSDoc, JsxAttribute, JsxExpression, JsxSpreadAttribute, KeywordSyntaxKind, + MethodDeclaration, + MethodSignatureDeclaration, + Modifier, ModifierSyntaxKind, + ModuleDeclaration, NamedExports, NamedImports, NamespaceExport, @@ -51,6 +68,7 @@ import type { PunctuationSyntaxKind, ReturnStatement, SatisfiesExpression, + SetAccessorDeclaration, ShorthandPropertyAssignment, SpreadAssignment, Statement, @@ -59,7 +77,10 @@ import type { ThisExpression, ThrowStatement, Token, + TypeAliasDeclaration, + TypeParameterDeclaration, VariableDeclaration, + VariableStatement, WhileStatement, WithStatement, } from "./ast.generated.ts"; @@ -71,6 +92,43 @@ 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; + +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; + declare const autoAccessorBrand: unique symbol; export interface AutoAccessorPropertyDeclaration extends PropertyDeclaration { readonly [autoAccessorBrand]: void; @@ -222,6 +280,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 141e9acd4f839..85c3ea3029f74 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/is.ts b/packages/typescript/src/ast/is.ts index c298cb04f8e0a..8d9ed4f0711f5 100644 --- a/packages/typescript/src/ast/is.ts +++ b/packages/typescript/src/ast/is.ts @@ -17,6 +17,8 @@ import type { BooleanLiteral, CallChain, CallExpression, + CanHaveDecorators, + CanHaveModifiers, ClassElement, ComputedPropertyName, ConciseBody, @@ -148,6 +150,55 @@ 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; + } +} + +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; + } +} + export function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAccessorPropertyDeclaration { return node.kind === SyntaxKind.PropertyDeclaration && !!((node as PropertyDeclaration).modifierFlags & ModifierFlags.Accessor); @@ -302,9 +353,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/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/src/ast/scanner.ts b/packages/typescript/src/ast/scanner.ts index 0f5c53d94dc59..835ea141868e1 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"; @@ -177,6 +178,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/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index dfaecc7ae1b5f..59a61a55eb0fd 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -18,10 +18,12 @@ import type { Expression, HasExpression, HasInitializer, + JSDocSignature, ModifierLike, ObjectAssignmentInitializer, PropertyAccessExpression, PropertyAssignment, + SignatureDeclaration, SourceFile, VariableDeclaration, } from "./ast.ts"; @@ -29,6 +31,7 @@ import type { Node } from "./ast.ts"; import { isAccessExpression, isIdentifier, + isJSDocTypeExpression, isNumericLiteral, isStringLiteralLikeNode, } from "./is.generated.ts"; @@ -65,6 +68,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. @@ -117,6 +126,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; +} + export function isExternalModuleNameRelative(moduleName: string): boolean { return /^\.\.?(?:$|[\\/])/.test(moduleName) || isRootedDiskPath(moduleName); } @@ -142,17 +163,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/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 99a808b8d9a71..584d534f63b19 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -22,6 +22,7 @@ import { isJSDoc, isJSDocParameterTag, isJsxSelfClosingElement, + isMethodDeclaration, isModuleDeclaration, isNamedImports, isObjectLiteralExpression, @@ -49,6 +50,7 @@ import { type PropertyAccessExpression, type RootedFilePath, type SourceFile, + symbolName, SyntaxKind, TokenFlags, tryGetAmbientModuleNameFromSymbolName, @@ -401,6 +403,20 @@ function g(before = 1, required: number, after = 2, ...rest: number[]) {} }); describe("API", { concurrency }, () => { + test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", async () => { + await using api = spawnAPI(); + const defaults = await api.getDefaultFormatCodeSettings(); + 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 = indentSize + 1; + const next = await api.getDefaultFormatCodeSettings(); + assert.strictEqual(next.indentSize, indentSize); + assert.strictEqual(next.convertTabsToSpaces, convertTabsToSpaces); + }); + test("getCurrentLanguageServerSnapshot is LSP-only", async () => { if (!!false) { await using standalone = new API(); @@ -7584,6 +7600,32 @@ 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(symbolName(symbol), member.name.text); + 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 } }), @@ -7682,6 +7724,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/scanner.test.ts b/packages/typescript/test/scanner.test.ts index 86a5d1f19b503..87049c854d57b 100644 --- a/packages/typescript/test/scanner.test.ts +++ b/packages/typescript/test/scanner.test.ts @@ -1,10 +1,34 @@ 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("string")), SyntaxKind.StringKeyword); + for (const text of ["ordinary", "immediate", "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 an identifier", () => { + const scanner = createScanner(true); + scanner.setText("immediate value"); + assert.strictEqual(scanner.scan(), SyntaxKind.Identifier); + 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); diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 0bcfb73730afe..a4ff1f34f5c4a 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1613,6 +1613,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => exercisedMethods.add("API.createModuleResolver"); const cases: ParityCase[] = [ + parityCase("API", "getDefaultFormatCodeSettings", api.getDefaultFormatCodeSettings, assertDeepEquivalent), parityCase("API", "getEffectiveTypeRoots", api.getEffectiveTypeRoots, assertDeepEquivalent, { typeRoots: ["types"] }), parityCase("API", "getTsBuildInfoEmitOutputFilePath", api.getTsBuildInfoEmitOutputFilePath, assertDeepEquivalent, { incremental: true, configFilePath: "/tsconfig.json" }), parityCase("API", "getTsBuildInfoEmitOutputFilePath", api.getTsBuildInfoEmitOutputFilePath, assertDeepEquivalent, {}), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 2359913ec1362..a446a5a6113a7 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -30,6 +30,7 @@ import { isJSDoc, isJSDocParameterTag, isJsxSelfClosingElement, + isMethodDeclaration, isModuleDeclaration, isNamedImports, isObjectLiteralExpression, @@ -57,6 +58,7 @@ import { type PropertyAccessExpression, type RootedFilePath, type SourceFile, + symbolName, SyntaxKind, TokenFlags, tryGetAmbientModuleNameFromSymbolName, @@ -409,6 +411,20 @@ function g(before = 1, required: number, after = 2, ...rest: number[]) {} }); describe("API", { concurrency }, () => { + test("getDefaultFormatCodeSettings returns native defaults independently of snapshot preferences", () => { + using api = spawnAPI(); + const defaults = api.getDefaultFormatCodeSettings(); + 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 = indentSize + 1; + const next = api.getDefaultFormatCodeSettings(); + assert.strictEqual(next.indentSize, indentSize); + assert.strictEqual(next.convertTabsToSpaces, convertTabsToSpaces); + }); + test("getCurrentLanguageServerSnapshot is LSP-only", () => { if (!!false) { using standalone = new API(); @@ -7342,6 +7358,32 @@ 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(symbolName(symbol), member.name.text); + 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 } }), @@ -7440,6 +7482,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/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index e71ee4b0847d4..db4a7604c6b67 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -89,6 +89,212 @@ 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("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( + "/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( + "/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( + "/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( + "/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; + 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 // --------------------------------------------------------------------------- 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/tools/scripts/tsc/generate-encoder.ts b/tools/scripts/tsc/generate-encoder.ts index 3ad98a3bf2ee8..f568383ebe572 100644 --- a/tools/scripts/tsc/generate-encoder.ts +++ b/tools/scripts/tsc/generate-encoder.ts @@ -1488,11 +1488,13 @@ function emitNodeGeneratedImports(w: CodeWriter) { w.write(` isJSDoc,`); w.write(` type JSDoc,`); 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,`); @@ -2030,6 +2032,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;`); 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/api/proto.go b/tsc/internal/api/proto.go index 12d1fd3c8da60..40270f4e4209c 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" @@ -653,6 +654,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 b40f0824effda..a5c4612f44c99 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" @@ -902,6 +903,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): @@ -1481,6 +1484,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..bb932437eaba7 100644 --- a/tsc/internal/ls/lsutil/formatcodeoptions.go +++ b/tsc/internal/ls/lsutil/formatcodeoptions.go @@ -6,12 +6,12 @@ import ( "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 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..a1c4064f686c7 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": 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,