From 663af1b2311ba4353969fd2ad35597923c350b5f Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 18 Nov 2026 17:52:08 +0000 Subject: [PATCH 1/5] generate content mapper Go types from json schema --- Herebyfile.mjs | 26 +- .../schemas/contentmapper.schema.json | 384 ++++++++++++++++++ tools/scripts/tsc/generate-contentmapper.ts | 247 +++++++++++ tsc/internal/contentmapper/hostimpl.go | 144 ------- .../contentmapper/protocol_generated.go | 160 ++++++++ 5 files changed, 811 insertions(+), 150 deletions(-) create mode 100644 packages/typescript/schemas/contentmapper.schema.json create mode 100644 tools/scripts/tsc/generate-contentmapper.ts create mode 100644 tsc/internal/contentmapper/protocol_generated.go diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 27a962cda89f4..73d9188a34a13 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -29,6 +29,7 @@ import { ensureModel as ensureLSPModel, outputs as lspModelOutputs, } from "./tools/scripts/lsp/fetchModel.mts"; +import { outputs as contentMapperOutputs } from "./tools/scripts/tsc/generate-contentmapper.ts"; import { outputs as encoderOutputs } from "./tools/scripts/tsc/generate-encoder.ts"; import { outputs as enumOutputs } from "./tools/scripts/tsc/generate-enums.ts"; import { outputs as goASTOutputs } from "./tools/scripts/tsc/generate-go-ast.ts"; @@ -677,6 +678,18 @@ export const generateAST = task({ run: runGenerateAST, }); +async function runGenerateContentMapper() { + const { default: generate } = await import("./tools/scripts/tsc/generate-contentmapper.ts"); + generate(!!options.force); +} + +export const generateContentMapper = task({ + name: "generate:contentmapper", + description: "Generates Go content mapper protocol declarations from the JSON schema.", + outputs: contentMapperOutputs, + run: runGenerateContentMapper, +}); + async function runGenerateSync() { const { generateSync } = await import("./packages/typescript/scripts/generateSync.ts"); generateSync(!!options.force); @@ -783,6 +796,7 @@ async function runGenerate() { await runWithConcurrencyLimit([runGenerateAST, runGenerateLSP], 2); await runGenerateGo(); }, + runGenerateContentMapper, runGenerateSync, async () => { await runGenerateExtension(); @@ -1164,11 +1178,13 @@ export const testTools = task({ export const testCodegen = task({ name: "test:codegen", description: "Runs codegen tests without regenerating sources.", - run: async () => { - await run("node", ["--test", "--test-concurrency=1", "./tools/scripts/gen/*.test.mts", "./tools/scripts/tsc/*.test.ts"]); - }, + run: runTestCodegen, }); +async function runTestCodegen() { + await run("node", ["--test", "--test-concurrency=1", "./tools/scripts/gen/*.test.mts", "./tools/scripts/tsc/*.test.ts"]); +} + export const buildAPI = task({ name: "build:api", description: "Builds @typescript/typescript JS API.", @@ -1520,9 +1536,7 @@ export const validate = task({ if (options.all) { await runValidation("check:herebyfile", runCheckHerebyfile); await runValidation("test:tools", runTestTools); - await runValidation("test:options", async () => { - await run("node", ["--test", "./tools/scripts/tsc/options.test.ts"]); - }); + await runValidation("test:codegen", runTestCodegen); await runValidation("test:smoke", runSmokeTest); // in CI this is run with `--race` } await runValidation("lint", runLint); diff --git a/packages/typescript/schemas/contentmapper.schema.json b/packages/typescript/schemas/contentmapper.schema.json new file mode 100644 index 0000000000000..9409cb068c6c3 --- /dev/null +++ b/packages/typescript/schemas/contentmapper.schema.json @@ -0,0 +1,384 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TypeScript content mapper protocol", + "description": "Content mapper JSON-RPC methods and reusable parameter and result definitions. Reference individual protocol types through #/definitions/. Positions use the encoding selected during initialization.", + "x-methods": { + "initialize": { + "params": { + "$ref": "#/definitions/InitializeParams" + }, + "result": { + "$ref": "#/definitions/InitializeResult" + } + }, + "openProject": { + "params": { + "$ref": "#/definitions/OpenProjectParams" + }, + "result": { + "$ref": "#/definitions/OpenProjectResult" + } + }, + "closeProject": { + "params": { + "$ref": "#/definitions/CloseProjectParams" + }, + "result": { + "type": "null" + } + }, + "transform": { + "params": { + "$ref": "#/definitions/TransformParams" + }, + "result": { + "$ref": "#/definitions/TransformResult" + } + } + }, + "definitions": { + "InitializeParams": { + "type": "object", + "description": "Parameters for the initialize request.", + "properties": { + "locale": { + "type": "string", + "description": "BCP 47 locale for mapper-authored diagnostic messages, when configured." + }, + "positionEncodings": { + "type": "array", + "items": { + "$ref": "#/definitions/PositionEncoding" + }, + "description": "Coordinate spaces accepted by the host." + } + }, + "required": ["positionEncodings"] + }, + "InitializeResult": { + "type": "object", + "description": "Response to the initialize request.", + "properties": { + "positionEncoding": { + "$ref": "#/definitions/PositionEncoding" + }, + "diagnosticSource": { + "type": "string", + "pattern": "\\S", + "description": "Prefix for mapper-authored diagnostic codes. It must not be whitespace-only or, ignoring case, typescript, tsc, or a native source extension without its leading dot." + } + }, + "required": ["positionEncoding", "diagnosticSource"] + }, + "OpenProjectParams": { + "type": "object", + "description": "Parameters for the openProject request.", + "properties": { + "configFileName": { + "type": "string", + "description": "Absolute project configuration file name, or an empty string when there is none." + }, + "projectHandle": { + "type": "string", + "description": "Opaque, process-local project handle assigned by the host." + }, + "options": { + "description": "Mapper entry's options from the project's contentMappers configuration." + }, + "compilerOptions": { + "description": "Project's effective compiler options, serialized by the host." + } + }, + "required": ["configFileName", "projectHandle", "compilerOptions"] + }, + "OpenProjectResult": { + "type": "object", + "description": "Response to an openProject request. Only mappers declaring dynamicConfig may return a non-empty configIdentity or watchedFiles.", + "properties": { + "configIdentity": { + "type": "string", + "description": "Stable fingerprint of all dynamic configuration affecting transforms. It must be non-empty for dynamicConfig mappers; otherwise it must be empty or omitted." + }, + "watchedFiles": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Absolute file names whose changes may alter configIdentity or transform output." + }, + "optionDiagnostics": { + "type": "array", + "items": { + "$ref": "#/definitions/OptionDiagnosticResult" + }, + "description": "Diagnostics reporting invalid mapper options." + } + } + }, + "OptionDiagnosticResult": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0 + } + ] + }, + "description": "Property names and array indices relative to the mapper entry's options object." + }, + "messageText": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647 + } + }, + "required": ["path", "messageText", "code"] + }, + "CloseProjectParams": { + "type": "object", + "description": "Parameters for the closeProject request.", + "properties": { + "projectHandle": { + "type": "string" + } + }, + "required": ["projectHandle"] + }, + "PositionEncoding": { + "type": "string", + "enum": ["utf-8", "utf-16"], + "description": "Coordinate space for mappings and diagnostics: UTF-8 byte offsets or UTF-16 code unit offsets." + }, + "TransformParams": { + "type": "object", + "description": "Parameters for the transform request.", + "properties": { + "fileName": { + "type": "string", + "description": "Absolute name of the content-mapped source file." + }, + "content": { + "type": "string", + "description": "Original source text." + }, + "projectHandle": { + "type": "string", + "description": "Handle for the project configuration opened for this transform." + } + }, + "required": ["fileName", "content", "projectHandle"] + }, + "MappedOutput": { + "type": "object", + "description": "Virtual source text and its mapping to the original input.", + "properties": { + "text": { + "type": "string", + "description": "Virtual source text." + }, + "extension": { + "type": "string", + "enum": [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".json"], + "description": "Extension determining the virtual source file's syntax." + }, + "mappings": { + "type": "array", + "items": { + "$ref": "#/definitions/SpanMapSegment" + }, + "description": "Span map tuples in the selected position encoding. Absent or empty mappings describe fully synthesized output." + }, + "diagnosticDirectives": { + "$ref": "#/definitions/DiagnosticDirectives" + } + }, + "required": ["text", "extension"] + }, + "SpanMapSegment": { + "type": "array", + "description": "[virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text.", + "items": [ + { + "type": "integer", + "minimum": 0, + "maximum": 2147483647, + "description": "Virtual start offset." + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2147483647, + "description": "Virtual span length." + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2147483647, + "description": "Original start offset." + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2147483647, + "description": "Original span length." + }, + { + "type": "integer", + "enum": [0, 1, 2], + "description": "Mapping kind: 0 is verbatim, 1 is atom, and 2 is alias." + }, + { + "type": "integer", + "minimum": 0, + "maximum": 1048575, + "description": "Language-service feature bitmask. Omitted means all features (1048575); 0 disables all features. Does not suppress diagnostics." + } + ], + "minItems": 5, + "maxItems": 6 + }, + "DiagnosticDirectivePolicy": { + "type": "integer", + "enum": [0, 1], + "description": "Diagnostic directive policy: 0 ignores diagnostics; 1 expects a diagnostic." + }, + "UnusedExpectDirectiveDiagnostic": { + "type": "object", + "description": "Diagnostic reported when an expect directive suppresses no diagnostic.", + "properties": { + "code": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647 + }, + "messageText": { + "type": "string" + } + }, + "required": ["code", "messageText"] + }, + "DiagnosticDirectives": { + "type": "object", + "description": "Shared unused-expect diagnostics and compact diagnostic directive tuples.", + "properties": { + "unusedExpectDirectiveDiagnostics": { + "type": "array", + "items": { + "$ref": "#/definitions/UnusedExpectDirectiveDiagnostic" + } + }, + "directives": { + "type": "array", + "items": { + "$ref": "#/definitions/MappedDiagnosticDirective" + }, + "description": "Directives with non-overlapping virtual ranges." + } + }, + "required": ["unusedExpectDirectiveDiagnostics", "directives"] + }, + "MappedDiagnosticDirective": { + "type": "array", + "description": "[originalStart, originalLength, virtualStart, virtualEnd, policy, unusedExpectDirectiveIndex?]. Expect directives require a valid original range. An omitted index selects the only shared unused-expect diagnostic and requires exactly one such diagnostic.", + "items": [ + { + "type": "integer", + "description": "Original start offset. It is ignored for ignore directives if the original range is invalid." + }, + { + "type": "integer", + "description": "Original span length. It is ignored for ignore directives if the original range is invalid." + }, + { + "type": "integer", + "minimum": 0, + "description": "Inclusive virtual start offset." + }, + { + "type": "integer", + "minimum": 0, + "description": "Exclusive virtual end offset, which must not precede the start." + }, + { + "$ref": "#/definitions/DiagnosticDirectivePolicy" + }, + { + "type": "integer", + "minimum": 0, + "description": "Index into unusedExpectDirectiveDiagnostics, used by expect directives." + } + ], + "minItems": 5, + "maxItems": 6, + "if": { + "items": [{}, {}, {}, {}, { "const": 1 }] + }, + "then": { + "items": [{ "minimum": 0 }, { "minimum": 0 }] + } + }, + "SupplementalOutput": { + "$ref": "#/definitions/MappedOutput" + }, + "TransformResult": { + "description": "Canonical output for one input file, with optional mapper diagnostics and supplemental compiler inputs.", + "allOf": [ + { + "$ref": "#/definitions/MappedOutput" + }, + { + "type": "object", + "properties": { + "diagnostics": { + "type": "array", + "items": { + "$ref": "#/definitions/Diagnostic" + }, + "description": "Mapper-authored errors in original-source coordinates." + }, + "supplemental": { + "type": "array", + "items": { + "$ref": "#/definitions/SupplementalOutput" + }, + "description": "Additional unnamed compiler inputs associated with this source file." + } + } + } + ] + }, + "Diagnostic": { + "type": "object", + "description": "Mapper-authored error in original-source coordinates using the selected position encoding.", + "properties": { + "messageText": { + "type": "string" + }, + "start": { + "type": "integer", + "minimum": 0 + }, + "length": { + "type": "integer", + "minimum": 0 + }, + "code": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647 + } + }, + "required": ["messageText", "start", "length", "code"] + } + } +} diff --git a/tools/scripts/tsc/generate-contentmapper.ts b/tools/scripts/tsc/generate-contentmapper.ts new file mode 100644 index 0000000000000..b91f74a9f9271 --- /dev/null +++ b/tools/scripts/tsc/generate-contentmapper.ts @@ -0,0 +1,247 @@ +/** + * Generates the Go content mapper protocol declarations from the JSON schema. + * Usage: npx hereby generate:contentmapper [--force] + */ + +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { GeneratedFile } from "../gen/generatedFile.mts"; +import { + formatFilesSync, + parseGeneratorArgs, + repoRoot, +} from "../gen/utils.mts"; + +interface Schema { + $ref?: string; + type?: string; + description?: string; + properties?: Record; + required?: string[]; + items?: Schema | Schema[]; + anyOf?: Schema[]; + allOf?: Schema[]; + enum?: (string | number)[]; + minimum?: number; + maximum?: number; + minItems?: number; + maxItems?: number; +} + +export interface SchemaDocument { + "definitions": Record; + "x-methods": Record; +} + +const schemaPath = path.join(repoRoot, "packages/typescript/schemas/contentmapper.schema.json"); +export const outputs = ["tsc/internal/contentmapper/protocol_generated.go"] as const; + +const enumNames: Record> = { + PositionEncoding: { "utf-8": "UTF8", "utf-16": "UTF16" }, + DiagnosticDirectivePolicy: { "0": "Ignore", "1": "Expect" }, +}; + +function referenceName(ref: string, definitions: Record): string { + const match = /^#\/definitions\/([A-Za-z][A-Za-z0-9]*)$/.exec(ref); + assert(match && definitions[match[1]], `Unsupported or missing schema reference: ${ref}`); + return match[1]; +} + +function goName(name: string): string { + assert(/^[a-zA-Z][a-zA-Z0-9]*$/.test(name), `Unsupported Go name: ${name}`); + return name[0].toUpperCase() + name.slice(1); +} + +function goType(schema: Schema, definitions: Record): string { + if (schema.$ref) return referenceName(schema.$ref, definitions); + if (schema.anyOf || (!schema.type && !schema.allOf)) return "json.Value"; + switch (schema.type) { + case "string": + return "string"; + case "integer": + return schema.minimum === -2147483648 && schema.maximum === 2147483647 ? "int32" : "int"; + case "array": + assert(schema.items && !Array.isArray(schema.items), "Unsupported array items"); + return `[]${goType(schema.items, definitions)}`; + default: + throw new Error(`Unsupported schema type: ${schema.type}`); + } +} + +function referencedDescription(schema: Schema, definitions: Record): string | undefined { + if (schema.description) return schema.description; + return schema.$ref ? definitions[referenceName(schema.$ref, definitions)].description : undefined; +} + +function nounPhrase(text: string): string { + const phrase = text.trim().replace(/\s+/g, " ").replace(/^[A-Z](?=[a-z]|\s|$)/, first => first.toLowerCase()); + return /^(?:a|an|the|this|these|those|some|all|no)\b/.test(phrase) ? phrase : `the ${phrase}`; +} + +function fieldDescription(name: string, schema: Schema, definitions: Record): string[] { + const text = referencedDescription(schema, definitions); + if (!text) return []; + const target = schema.$ref ? definitions[referenceName(schema.$ref, definitions)] : schema; + const verb = target.type === "array" ? "lists" : !target.type || target.type === "object" ? "contains" : "is"; + return [`// ${name} ${verb} ${nounPhrase(text)}`]; +} + +function typeDescription(name: string, text: string | undefined): string[] { + if (!text) return []; + const normalized = text.trim().replace(/\s+/g, " "); + const description = `${name} ${normalized.startsWith("[") ? `is encoded as ${normalized}` : `describes ${nounPhrase(normalized)}`}`; + const lines: string[] = []; + let line = "//"; + for (const word of description.split(" ")) { + if (line.length > 2 && line.length + 1 + word.length > 120) { + lines.push(line); + line = "//"; + } + line += ` ${word}`; + } + lines.push(line); + return lines; +} + +export function generateContentMapper(document: SchemaDocument): string { + const definitions = document.definitions; + assert(definitions && typeof definitions === "object", "Missing schema definitions"); + const methods = document["x-methods"]; + assert(methods && typeof methods === "object" && Object.keys(methods).length > 0, "Missing content mapper methods"); + const lines = [ + "// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT.", + "", + "package contentmapper", + "", + 'import "github.com/microsoft/TypeScript/tsc/internal/json"', + "", + "// Content mapper protocol method names.", + "const (", + ]; + const methodIdentifiers = new Set(); + for (const [method, definition] of Object.entries(methods)) { + const identifier = `Method${goName(method)}`; + assert(!methodIdentifiers.has(identifier), `Duplicate content mapper method identifier: ${identifier}`); + methodIdentifiers.add(identifier); + assert(definition.params?.$ref, `Missing params schema for content mapper method: ${method}`); + referenceName(definition.params.$ref, definitions); + if (definition.result?.$ref) { + referenceName(definition.result.$ref, definitions); + } + else { + assert(definition.result?.type === "null", `Unsupported result schema for content mapper method: ${method}`); + } + lines.push(`\t${identifier} = ${JSON.stringify(method)}`); + } + lines.push(")", ""); + + function objectFields(name: string, schema: Schema): void { + assert(schema.type === "object" && schema.properties, `Unsupported object: ${name}`); + const required = new Set(schema.required ?? []); + for (const property of required) assert(property in schema.properties, `Unknown required property ${name}.${property}`); + for (const [property, value] of Object.entries(schema.properties)) { + const field = goName(property); + let type = goType(value, definitions); + // Span maps are decoded by spanmap.Unmarshal, which consumes the entire raw JSON array. + if (name === "MappedOutput" && property === "mappings") { + assert(value.type === "array" && !Array.isArray(value.items) && value.items?.$ref === "#/definitions/SpanMapSegment", "Unsupported MappedOutput.mappings"); + type = "json.Value"; + } + if (!required.has(property) && value.$ref && definitions[referenceName(value.$ref, definitions)].type === "object") { + type = `*${type}`; + } + // Preserve the existing wire representation even though the schema makes this optional. + const optional = !required.has(property) && !(name === "OpenProjectResult" && property === "configIdentity"); + lines.push(...fieldDescription(field, value, definitions).map(line => `\t${line}`)); + lines.push(`\t${field} ${type} \`json:"${property}${optional ? ",omitempty" : ""}"\``); + } + } + + for (const [name, schema] of Object.entries(definitions)) { + goName(name); + lines.push(...typeDescription(name, schema.description)); + if (schema.$ref) { + const ref = referenceName(schema.$ref, definitions); + assert(definitions[ref].type === "object", `Unsupported definition reference: ${name}`); + lines.push(`type ${name} struct {`, `\t${ref}`, "}"); + } + else if (schema.allOf) { + lines.push(`type ${name} struct {`); + for (const part of schema.allOf) { + if (part.$ref) { + const ref = referenceName(part.$ref, definitions); + assert(definitions[ref].type === "object", `Unsupported allOf reference: ${name}`); + lines.push(`\t${ref}`); + } + else { + objectFields(name, part); + } + } + lines.push("}"); + } + else if (schema.type === "object") { + lines.push(`type ${name} struct {`); + objectFields(name, schema); + lines.push("}"); + } + else if (schema.enum) { + const names = enumNames[name]; + assert(names && schema.enum.length === Object.keys(names).length && schema.enum.every(value => Object.hasOwn(names, String(value))), `Unsupported ${name} enum`); + assert(schema.type === "string" || schema.type === "integer", `Unsupported ${name} enum type`); + lines.push(`type ${name} ${schema.type === "string" ? "string" : "uint8"}`, "", "const ("); + for (const value of schema.enum) lines.push(`\t${name}${names[String(value)]} ${name} = ${JSON.stringify(value)}`); + lines.push(")"); + } + else if (Array.isArray(schema.items)) { + assert(schema.type === "array" && schema.minItems === 5 && schema.maxItems === 6 && schema.items.length === 6, `Unsupported ${name} tuple`); + if (name === "SpanMapSegment") { + assert(schema.description?.startsWith("[virtualStart, virtualLength, originalStart, originalLength, kind, features?]"), `Unsupported ${name} tuple order`); + assert( + schema.items.every(item => + item.type === "integer" + && (item.enum + ? item.enum.every(value => typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647) + : item.minimum !== undefined && item.minimum >= -2147483648 && item.maximum !== undefined && item.maximum <= 2147483647) + ), + `Unsupported ${name} tuple items`, + ); + lines.push(`type ${name} []int32`); + } + else if (name === "MappedDiagnosticDirective") { + assert(schema.description?.startsWith("[originalStart, originalLength, virtualStart, virtualEnd, policy, unusedExpectDirectiveIndex?]"), `Unsupported ${name} tuple order`); + const names = ["OriginalStart", "OriginalLength", "VirtualStart", "VirtualEnd", "Policy", "UnusedExpectDirectiveIndex"]; + assert(schema.items.every((item, index) => index === 4 ? item.$ref === "#/definitions/DiagnosticDirectivePolicy" : item.type === "integer"), `Unsupported ${name} tuple items`); + lines.push(`type ${name} struct {`); + for (const [index, item] of schema.items.entries()) { + lines.push(...fieldDescription(names[index], item, definitions).map(line => `\t${line}`)); + lines.push(`\t${names[index]} ${index >= schema.minItems ? "*" : ""}${goType(item, definitions)}`); + } + lines.push("}"); + } + else { + throw new Error(`Unsupported ${name} tuple`); + } + } + else { + throw new Error(`Unsupported definition: ${name}`); + } + lines.push(""); + } + return lines.join("\n"); +} + +export default function generate(force = false): void { + const output = new GeneratedFile(path.join(repoRoot, outputs[0]), [import.meta.filename, schemaPath]); + if (output.isCurrent(force)) return; + const document: SchemaDocument = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + output.write(generateContentMapper(document)); + formatFilesSync([output.fileName]); + output.markCurrent(); + console.log(`Wrote ${output.fileName}`); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + generate(parseGeneratorArgs({}).force); +} diff --git a/tsc/internal/contentmapper/hostimpl.go b/tsc/internal/contentmapper/hostimpl.go index a1ce6789d28d6..1d7ad788eeb94 100644 --- a/tsc/internal/contentmapper/hostimpl.go +++ b/tsc/internal/contentmapper/hostimpl.go @@ -31,127 +31,6 @@ const initializeTimeoutSeconds = 5 const initializeTimeout = initializeTimeoutSeconds * time.Second -// Content mapper protocol method names. -const ( - MethodInitialize = "initialize" - MethodOpenProject = "openProject" - MethodCloseProject = "closeProject" - MethodTransform = "transform" -) - -// InitializeParams is the parameter object for the initialize request. -type InitializeParams struct { - // Locale is the BCP 47 locale to use for mapper-authored diagnostic messages, when configured. - Locale string `json:"locale,omitempty"` - // PositionEncodings lists the coordinate spaces the host accepts. - PositionEncodings []PositionEncoding `json:"positionEncodings"` -} - -// InitializeResult is the mapper's response to the initialize request. -type InitializeResult struct { - // PositionEncoding selects the coordinate space for all mappings and diagnostics. - PositionEncoding PositionEncoding `json:"positionEncoding"` - // DiagnosticSource is the prefix used for every mapper-authored diagnostic code. - DiagnosticSource string `json:"diagnosticSource"` -} - -// OpenProjectParams is the parameter object for the openProject request. -type OpenProjectParams struct { - // ConfigFileName is the absolute project configuration file name, or empty when there is none. - ConfigFileName string `json:"configFileName"` - // ProjectHandle is an opaque, process-local handle assigned by the host. - ProjectHandle string `json:"projectHandle"` - // Options is the mapper entry's options from the project's contentMappers configuration. - Options json.Value `json:"options,omitempty"` - // CompilerOptions contains the project's effective compiler options. - CompilerOptions json.Value `json:"compilerOptions"` -} - -// OpenProjectResult is the mapper's response to an openProject request. ConfigIdentity and WatchedFiles -// may only be returned by mappers that declare dynamicConfig. -type OpenProjectResult struct { - // ConfigIdentity is a stable fingerprint of all dynamic configuration that can affect transforms. - ConfigIdentity string `json:"configIdentity"` - // WatchedFiles are absolute files whose changes may alter ConfigIdentity or transform output. - WatchedFiles []string `json:"watchedFiles,omitempty"` - // OptionDiagnostics report invalid mapper options. Paths are relative to the mapper entry's options object. - OptionDiagnostics []OptionDiagnosticResult `json:"optionDiagnostics,omitempty"` -} - -type OptionDiagnosticResult struct { - Path []json.Value `json:"path"` - MessageText string `json:"messageText"` - Code int32 `json:"code"` -} - -// CloseProjectParams is the parameter object for the closeProject request. -type CloseProjectParams struct { - ProjectHandle string `json:"projectHandle"` -} - -// PositionEncoding is the coordinate space a mapper uses for mappings and diagnostics. -type PositionEncoding string - -const ( - PositionEncodingUTF8 PositionEncoding = "utf-8" - PositionEncodingUTF16 PositionEncoding = "utf-16" -) - -// TransformParams is the parameter object for the transform request. -type TransformParams struct { - // FileName is the absolute name of the content-mapped source file being transformed. - FileName string `json:"fileName"` - // Content is the content-mapped source file's text. - Content string `json:"content"` - // ProjectHandle identifies the mapper project configuration opened for this transform. - ProjectHandle string `json:"projectHandle"` -} - -// MappedOutput is virtual source text and its mapping to an original input. -type MappedOutput struct { - // Text is the virtual JavaScript or TypeScript source text. - Text string `json:"text"` - // Extension determines the virtual source file's syntax. - Extension string `json:"extension"` - // Mappings is the span map's tuple-array JSON (see spanmap.Marshal), expressed in the selected - // position encoding. Absent or empty means the output is fully synthesized. - Mappings json.Value `json:"mappings,omitempty"` - // DiagnosticDirectives describe framework directives that suppress TypeScript diagnostics in - // virtual ranges and optionally report an error when no diagnostic is produced. - DiagnosticDirectives *DiagnosticDirectives `json:"diagnosticDirectives,omitempty"` -} - -// DiagnosticDirectivePolicy is the numeric policy stored in a mapped diagnostic directive tuple. -type DiagnosticDirectivePolicy uint8 - -const ( - DiagnosticDirectivePolicyIgnore DiagnosticDirectivePolicy = iota - DiagnosticDirectivePolicyExpect -) - -type UnusedExpectDirectiveDiagnostic struct { - Code int32 `json:"code"` - MessageText string `json:"messageText"` -} - -// DiagnosticDirectives shares unused-expect diagnostics across compact directive tuples. -type DiagnosticDirectives struct { - UnusedExpectDirectiveDiagnostics []UnusedExpectDirectiveDiagnostic `json:"unusedExpectDirectiveDiagnostics"` - Directives []MappedDiagnosticDirective `json:"directives"` -} - -// MappedDiagnosticDirective is encoded as -// [originalStart, originalLength, virtualStart, virtualEnd, policy, unusedExpectDirectiveIndex?]. -// An omitted index selects the only unused-expect diagnostic and is invalid when there is not exactly one. -type MappedDiagnosticDirective struct { - OriginalStart int - OriginalLength int - VirtualStart int - VirtualEnd int - Policy DiagnosticDirectivePolicy - UnusedExpectDirectiveIndex *int -} - var ( _ json.MarshalerTo = MappedDiagnosticDirective{} _ json.UnmarshalerFrom = (*MappedDiagnosticDirective)(nil) @@ -190,29 +69,6 @@ func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error { return nil } -type SupplementalOutput struct { - MappedOutput -} - -// TransformResult is the canonical output for one input file. -type TransformResult struct { - MappedOutput - // Diagnostics are mapper-authored errors expressed in original-source coordinates. - Diagnostics []Diagnostic `json:"diagnostics,omitempty"` - // Supplemental contains additional unnamed compiler inputs associated with this source file. - Supplemental []SupplementalOutput `json:"supplemental,omitempty"` -} - -// Diagnostic is an error reported by a mapper in original-source coordinates. -type Diagnostic struct { - // MessageText is the diagnostic message. - MessageText string `json:"messageText"` - // Start and Length locate the diagnostic in the original content using the selected position encoding. - Start int `json:"start"` - Length int `json:"length"` - Code int32 `json:"code"` -} - // dialFunc establishes a running connection to a mapper. In production it spawns the mapper's process; // tests substitute an in-memory connection. It returns the connection and a closer that tears it down. type dialFunc func(ctx context.Context, mapper *Mapper, diagnosticLocale locale.Locale) (ipc.Conn, io.Closer, PositionEncoding, string, error) diff --git a/tsc/internal/contentmapper/protocol_generated.go b/tsc/internal/contentmapper/protocol_generated.go new file mode 100644 index 0000000000000..caf8a334b724c --- /dev/null +++ b/tsc/internal/contentmapper/protocol_generated.go @@ -0,0 +1,160 @@ +// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT. + +package contentmapper + +import "github.com/microsoft/TypeScript/tsc/internal/json" + +// Content mapper protocol method names. +const ( + MethodInitialize = "initialize" + MethodOpenProject = "openProject" + MethodCloseProject = "closeProject" + MethodTransform = "transform" +) + +// InitializeParams describes the parameters for the initialize request. +type InitializeParams struct { + // Locale is the BCP 47 locale for mapper-authored diagnostic messages, when configured. + Locale string `json:"locale,omitempty"` + // PositionEncodings lists the coordinate spaces accepted by the host. + PositionEncodings []PositionEncoding `json:"positionEncodings"` +} + +// InitializeResult describes the response to the initialize request. +type InitializeResult struct { + // PositionEncoding is the coordinate space for mappings and diagnostics: UTF-8 byte offsets or UTF-16 code unit offsets. + PositionEncoding PositionEncoding `json:"positionEncoding"` + // DiagnosticSource is the prefix for mapper-authored diagnostic codes. It must not be whitespace-only or, ignoring case, typescript, tsc, or a native source extension without its leading dot. + DiagnosticSource string `json:"diagnosticSource"` +} + +// OpenProjectParams describes the parameters for the openProject request. +type OpenProjectParams struct { + // ConfigFileName is the absolute project configuration file name, or an empty string when there is none. + ConfigFileName string `json:"configFileName"` + // ProjectHandle is the opaque, process-local project handle assigned by the host. + ProjectHandle string `json:"projectHandle"` + // Options contains the mapper entry's options from the project's contentMappers configuration. + Options json.Value `json:"options,omitempty"` + // CompilerOptions contains the project's effective compiler options, serialized by the host. + CompilerOptions json.Value `json:"compilerOptions"` +} + +// OpenProjectResult describes the response to an openProject request. Only mappers declaring dynamicConfig may return a +// non-empty configIdentity or watchedFiles. +type OpenProjectResult struct { + // ConfigIdentity is the stable fingerprint of all dynamic configuration affecting transforms. It must be non-empty for dynamicConfig mappers; otherwise it must be empty or omitted. + ConfigIdentity string `json:"configIdentity"` + // WatchedFiles lists the absolute file names whose changes may alter configIdentity or transform output. + WatchedFiles []string `json:"watchedFiles,omitempty"` + // OptionDiagnostics lists the diagnostics reporting invalid mapper options. + OptionDiagnostics []OptionDiagnosticResult `json:"optionDiagnostics,omitempty"` +} + +type OptionDiagnosticResult struct { + // Path lists the property names and array indices relative to the mapper entry's options object. + Path []json.Value `json:"path"` + MessageText string `json:"messageText"` + Code int32 `json:"code"` +} + +// CloseProjectParams describes the parameters for the closeProject request. +type CloseProjectParams struct { + ProjectHandle string `json:"projectHandle"` +} + +// PositionEncoding describes the coordinate space for mappings and diagnostics: UTF-8 byte offsets or UTF-16 code unit +// offsets. +type PositionEncoding string + +const ( + PositionEncodingUTF8 PositionEncoding = "utf-8" + PositionEncodingUTF16 PositionEncoding = "utf-16" +) + +// TransformParams describes the parameters for the transform request. +type TransformParams struct { + // FileName is the absolute name of the content-mapped source file. + FileName string `json:"fileName"` + // Content is the original source text. + Content string `json:"content"` + // ProjectHandle is the handle for the project configuration opened for this transform. + ProjectHandle string `json:"projectHandle"` +} + +// MappedOutput describes the virtual source text and its mapping to the original input. +type MappedOutput struct { + // Text is the virtual source text. + Text string `json:"text"` + // Extension is the extension determining the virtual source file's syntax. + Extension string `json:"extension"` + // Mappings lists the span map tuples in the selected position encoding. Absent or empty mappings describe fully synthesized output. + Mappings json.Value `json:"mappings,omitempty"` + // DiagnosticDirectives contains the shared unused-expect diagnostics and compact diagnostic directive tuples. + DiagnosticDirectives *DiagnosticDirectives `json:"diagnosticDirectives,omitempty"` +} + +// SpanMapSegment is encoded as [virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments +// must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text. +type SpanMapSegment []int32 + +// DiagnosticDirectivePolicy describes the diagnostic directive policy: 0 ignores diagnostics; 1 expects a diagnostic. +type DiagnosticDirectivePolicy uint8 + +const ( + DiagnosticDirectivePolicyIgnore DiagnosticDirectivePolicy = 0 + DiagnosticDirectivePolicyExpect DiagnosticDirectivePolicy = 1 +) + +// UnusedExpectDirectiveDiagnostic describes the diagnostic reported when an expect directive suppresses no diagnostic. +type UnusedExpectDirectiveDiagnostic struct { + Code int32 `json:"code"` + MessageText string `json:"messageText"` +} + +// DiagnosticDirectives describes the shared unused-expect diagnostics and compact diagnostic directive tuples. +type DiagnosticDirectives struct { + UnusedExpectDirectiveDiagnostics []UnusedExpectDirectiveDiagnostic `json:"unusedExpectDirectiveDiagnostics"` + // Directives lists the directives with non-overlapping virtual ranges. + Directives []MappedDiagnosticDirective `json:"directives"` +} + +// MappedDiagnosticDirective is encoded as [originalStart, originalLength, virtualStart, virtualEnd, policy, +// unusedExpectDirectiveIndex?]. Expect directives require a valid original range. An omitted index selects the only +// shared unused-expect diagnostic and requires exactly one such diagnostic. +type MappedDiagnosticDirective struct { + // OriginalStart is the original start offset. It is ignored for ignore directives if the original range is invalid. + OriginalStart int + // OriginalLength is the original span length. It is ignored for ignore directives if the original range is invalid. + OriginalLength int + // VirtualStart is the inclusive virtual start offset. + VirtualStart int + // VirtualEnd is the exclusive virtual end offset, which must not precede the start. + VirtualEnd int + // Policy is the diagnostic directive policy: 0 ignores diagnostics; 1 expects a diagnostic. + Policy DiagnosticDirectivePolicy + // UnusedExpectDirectiveIndex is the index into unusedExpectDirectiveDiagnostics, used by expect directives. + UnusedExpectDirectiveIndex *int +} + +type SupplementalOutput struct { + MappedOutput +} + +// TransformResult describes the canonical output for one input file, with optional mapper diagnostics and supplemental +// compiler inputs. +type TransformResult struct { + MappedOutput + // Diagnostics lists the mapper-authored errors in original-source coordinates. + Diagnostics []Diagnostic `json:"diagnostics,omitempty"` + // Supplemental lists the additional unnamed compiler inputs associated with this source file. + Supplemental []SupplementalOutput `json:"supplemental,omitempty"` +} + +// Diagnostic describes the mapper-authored error in original-source coordinates using the selected position encoding. +type Diagnostic struct { + MessageText string `json:"messageText"` + Start int `json:"start"` + Length int `json:"length"` + Code int32 `json:"code"` +} From 14d1545dffc9093f0f1c965bf07cfa405ac28da5 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 18 Nov 2026 18:44:35 +0000 Subject: [PATCH 2/5] generate marshalling stuff --- .../schemas/contentmapper.schema.json | 9 ++- tools/scripts/tsc/generate-contentmapper.ts | 60 ++++++++++++++++--- tsc/internal/contentmapper/hostimpl.go | 38 ------------ .../contentmapper/protocol_generated.go | 43 ++++++++++++- 4 files changed, 103 insertions(+), 47 deletions(-) diff --git a/packages/typescript/schemas/contentmapper.schema.json b/packages/typescript/schemas/contentmapper.schema.json index 9409cb068c6c3..2873f203fff6b 100644 --- a/packages/typescript/schemas/contentmapper.schema.json +++ b/packages/typescript/schemas/contentmapper.schema.json @@ -290,31 +290,38 @@ "MappedDiagnosticDirective": { "type": "array", "description": "[originalStart, originalLength, virtualStart, virtualEnd, policy, unusedExpectDirectiveIndex?]. Expect directives require a valid original range. An omitted index selects the only shared unused-expect diagnostic and requires exactly one such diagnostic.", + "title": "Diagnostic directive", "items": [ { "type": "integer", + "title": "originalStart", "description": "Original start offset. It is ignored for ignore directives if the original range is invalid." }, { "type": "integer", + "title": "originalLength", "description": "Original span length. It is ignored for ignore directives if the original range is invalid." }, { "type": "integer", "minimum": 0, + "title": "virtualStart", "description": "Inclusive virtual start offset." }, { "type": "integer", "minimum": 0, + "title": "virtualEnd", "description": "Exclusive virtual end offset, which must not precede the start." }, { - "$ref": "#/definitions/DiagnosticDirectivePolicy" + "$ref": "#/definitions/DiagnosticDirectivePolicy", + "title": "policy" }, { "type": "integer", "minimum": 0, + "title": "unusedExpectDirectiveIndex", "description": "Index into unusedExpectDirectiveDiagnostics, used by expect directives." } ], diff --git a/tools/scripts/tsc/generate-contentmapper.ts b/tools/scripts/tsc/generate-contentmapper.ts index b91f74a9f9271..889063ede43c9 100644 --- a/tools/scripts/tsc/generate-contentmapper.ts +++ b/tools/scripts/tsc/generate-contentmapper.ts @@ -28,6 +28,7 @@ interface Schema { maximum?: number; minItems?: number; maxItems?: number; + title?: string; } export interface SchemaDocument { @@ -115,7 +116,10 @@ export function generateContentMapper(document: SchemaDocument): string { "", "package contentmapper", "", - 'import "github.com/microsoft/TypeScript/tsc/internal/json"', + "import (", + '\t"fmt"', + '\t"github.com/microsoft/TypeScript/tsc/internal/json"', + ")", "", "// Content mapper protocol method names.", "const (", @@ -209,16 +213,58 @@ export function generateContentMapper(document: SchemaDocument): string { ); lines.push(`type ${name} []int32`); } - else if (name === "MappedDiagnosticDirective") { - assert(schema.description?.startsWith("[originalStart, originalLength, virtualStart, virtualEnd, policy, unusedExpectDirectiveIndex?]"), `Unsupported ${name} tuple order`); - const names = ["OriginalStart", "OriginalLength", "VirtualStart", "VirtualEnd", "Policy", "UnusedExpectDirectiveIndex"]; + else if (schema.items.every(item => item.title)) { + const names = schema.items.map(item => goName(item.title!)); + assert(schema.title, `Missing ${name} tuple title`); + const label = schema.title[0].toLowerCase() + schema.title.slice(1); + assert(schema.maxItems - schema.minItems === 1, `Unsupported ${name} tuple optional fields`); assert(schema.items.every((item, index) => index === 4 ? item.$ref === "#/definitions/DiagnosticDirectivePolicy" : item.type === "integer"), `Unsupported ${name} tuple items`); lines.push(`type ${name} struct {`); for (const [index, item] of schema.items.entries()) { - lines.push(...fieldDescription(names[index], item, definitions).map(line => `\t${line}`)); - lines.push(`\t${names[index]} ${index >= schema.minItems ? "*" : ""}${goType(item, definitions)}`); + const field = names[index]; + lines.push(...fieldDescription(field, item, definitions).map(line => `\t${line}`)); + lines.push(`\t${field} ${index >= schema.minItems ? "*" : ""}${goType(item, definitions)}`); } - lines.push("}"); + lines.push( + "}", + "", + "var (", + `\t_ json.MarshalerTo = ${name}{}`, + `\t_ json.UnmarshalerFrom = (*${name})(nil)`, + ")", + "", + `func (d ${name}) MarshalJSONTo(enc *json.Encoder) error {`, + `\ttuple := []any{${names.slice(0, schema.minItems).map(field => `d.${field}`).join(", ")}}`, + `\tif d.${names[schema.minItems]} != nil {`, + `\t\ttuple = append(tuple, *d.${names[schema.minItems]})`, + "\t}", + "\treturn json.MarshalEncode(enc, tuple)", + "}", + "", + `func (d *${name}) UnmarshalJSONFrom(dec *json.Decoder) error {`, + "\tvar tuple []json.Value", + "\tif err := json.UnmarshalDecode(dec, &tuple); err != nil {", + "\t\treturn err", + "\t}", + `\tif len(tuple) != ${schema.minItems} && len(tuple) != ${schema.maxItems} {`, + `\t\treturn fmt.Errorf(${JSON.stringify(`${label} tuple must contain ${schema.minItems} or ${schema.maxItems} elements, got %d`)}, len(tuple))`, + "\t}", + `\t*d = ${name}{}`, + `\tfields := []any{${names.slice(0, schema.minItems).map(field => `&d.${field}`).join(", ")}}`, + "\tfor i, field := range fields {", + "\t\tif err := json.Unmarshal(tuple[i], field); err != nil {", + `\t\t\treturn fmt.Errorf(${JSON.stringify(`invalid ${label} tuple element %d: %w`)}, i, err)`, + "\t\t}", + "\t}", + `\tif len(tuple) == ${schema.maxItems} {`, + `\t\td.${names[schema.minItems]} = new(${goType(schema.items[schema.minItems], definitions)})`, + `\t\tif err := json.Unmarshal(tuple[${schema.minItems}], d.${names[schema.minItems]}); err != nil {`, + `\t\t\treturn fmt.Errorf(${JSON.stringify(`invalid ${label} tuple element ${schema.minItems}: %w`)}, err)`, + "\t\t}", + "\t}", + "\treturn nil", + "}", + ); } else { throw new Error(`Unsupported ${name} tuple`); diff --git a/tsc/internal/contentmapper/hostimpl.go b/tsc/internal/contentmapper/hostimpl.go index 1d7ad788eeb94..98242c17b56ca 100644 --- a/tsc/internal/contentmapper/hostimpl.go +++ b/tsc/internal/contentmapper/hostimpl.go @@ -31,44 +31,6 @@ const initializeTimeoutSeconds = 5 const initializeTimeout = initializeTimeoutSeconds * time.Second -var ( - _ json.MarshalerTo = MappedDiagnosticDirective{} - _ json.UnmarshalerFrom = (*MappedDiagnosticDirective)(nil) -) - -func (d MappedDiagnosticDirective) MarshalJSONTo(enc *json.Encoder) error { - tuple := []any{d.OriginalStart, d.OriginalLength, d.VirtualStart, d.VirtualEnd, d.Policy} - if d.UnusedExpectDirectiveIndex != nil { - tuple = append(tuple, *d.UnusedExpectDirectiveIndex) - } - return json.MarshalEncode(enc, tuple) -} - -func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error { - var tuple []json.Value - if err := json.UnmarshalDecode(dec, &tuple); err != nil { - return err - } - if len(tuple) != 5 && len(tuple) != 6 { - return fmt.Errorf("diagnostic directive tuple must contain 5 or 6 elements, got %d", len(tuple)) - } - *d = MappedDiagnosticDirective{} - fields := []any{&d.OriginalStart, &d.OriginalLength, &d.VirtualStart, &d.VirtualEnd, &d.Policy} - for i, field := range fields { - if err := json.Unmarshal(tuple[i], field); err != nil { - return fmt.Errorf("invalid diagnostic directive tuple element %d: %w", i, err) - } - } - if len(tuple) == 6 { - var index int - d.UnusedExpectDirectiveIndex = &index - if err := json.Unmarshal(tuple[5], d.UnusedExpectDirectiveIndex); err != nil { - return fmt.Errorf("invalid diagnostic directive tuple element 5: %w", err) - } - } - return nil -} - // dialFunc establishes a running connection to a mapper. In production it spawns the mapper's process; // tests substitute an in-memory connection. It returns the connection and a closer that tears it down. type dialFunc func(ctx context.Context, mapper *Mapper, diagnosticLocale locale.Locale) (ipc.Conn, io.Closer, PositionEncoding, string, error) diff --git a/tsc/internal/contentmapper/protocol_generated.go b/tsc/internal/contentmapper/protocol_generated.go index caf8a334b724c..021208bd77f33 100644 --- a/tsc/internal/contentmapper/protocol_generated.go +++ b/tsc/internal/contentmapper/protocol_generated.go @@ -2,7 +2,11 @@ package contentmapper -import "github.com/microsoft/TypeScript/tsc/internal/json" +import ( + "fmt" + + "github.com/microsoft/TypeScript/tsc/internal/json" +) // Content mapper protocol method names. const ( @@ -137,6 +141,43 @@ type MappedDiagnosticDirective struct { UnusedExpectDirectiveIndex *int } +var ( + _ json.MarshalerTo = MappedDiagnosticDirective{} + _ json.UnmarshalerFrom = (*MappedDiagnosticDirective)(nil) +) + +func (d MappedDiagnosticDirective) MarshalJSONTo(enc *json.Encoder) error { + tuple := []any{d.OriginalStart, d.OriginalLength, d.VirtualStart, d.VirtualEnd, d.Policy} + if d.UnusedExpectDirectiveIndex != nil { + tuple = append(tuple, *d.UnusedExpectDirectiveIndex) + } + return json.MarshalEncode(enc, tuple) +} + +func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error { + var tuple []json.Value + if err := json.UnmarshalDecode(dec, &tuple); err != nil { + return err + } + if len(tuple) != 5 && len(tuple) != 6 { + return fmt.Errorf("diagnostic directive tuple must contain 5 or 6 elements, got %d", len(tuple)) + } + *d = MappedDiagnosticDirective{} + fields := []any{&d.OriginalStart, &d.OriginalLength, &d.VirtualStart, &d.VirtualEnd, &d.Policy} + for i, field := range fields { + if err := json.Unmarshal(tuple[i], field); err != nil { + return fmt.Errorf("invalid diagnostic directive tuple element %d: %w", i, err) + } + } + if len(tuple) == 6 { + d.UnusedExpectDirectiveIndex = new(int) + if err := json.Unmarshal(tuple[5], d.UnusedExpectDirectiveIndex); err != nil { + return fmt.Errorf("invalid diagnostic directive tuple element 5: %w", err) + } + } + return nil +} + type SupplementalOutput struct { MappedOutput } From 140b661b49d4170a5d624a43549eb6da906829b2 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 18 Nov 2026 21:07:57 +0000 Subject: [PATCH 3/5] use schema as base for span map types too --- Herebyfile.mjs | 5 +- packages/typescript/enums/spanMapFeature.d.ts | 44 ++--- packages/typescript/enums/spanMapFeature.js | 2 +- .../typescript/enums/spanMapFidelity.d.ts | 2 +- packages/typescript/enums/spanMapFidelity.js | 2 +- packages/typescript/enums/spanMapKind.d.ts | 2 +- packages/typescript/enums/spanMapKind.js | 2 +- .../schemas/contentmapper.schema.json | 134 ++++++++++++- packages/typescript/src/ast/spanMap.ts | 30 +-- .../src/ast/spanMapTypes.generated.ts | 31 +++ tools/scripts/tsc/generate-contentmapper.ts | 184 +++++++++++++++--- tools/scripts/tsc/generate-enums.ts | 21 +- tsc/internal/contentmapper/host_test.go | 83 ++++++-- tsc/internal/contentmapper/hostimpl.go | 2 +- .../contentmapper/protocol_generated.go | 5 +- tsc/internal/spanmap/spanmap.go | 105 ++-------- tsc/internal/spanmap/spanmap_test.go | 40 ++++ tsc/internal/spanmap/types_generated.go | 87 +++++++++ .../testutil/contentmappertest/component.go | 8 +- .../testutil/contentmappertest/duplicate.go | 45 ++--- .../testutil/contentmappertest/editing.go | 39 ++-- .../testutil/contentmappertest/hoisting.go | 8 +- .../testutil/contentmappertest/lisp.go | 9 +- .../testutil/contentmappertest/protocol.go | 9 +- .../supplemental_diagnostics.go | 9 +- .../contentmappertest/synthesizing.go | 7 +- .../contentmappertest/transforming.go | 8 +- 27 files changed, 630 insertions(+), 293 deletions(-) create mode 100644 packages/typescript/src/ast/spanMapTypes.generated.ts create mode 100644 tsc/internal/spanmap/types_generated.go diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 04f1e51cc3656..6c9dd00176fca 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -320,6 +320,8 @@ export const cleanBuilt = task({ const goGenerateActions = []; async function runGenerateGo() { + // Some Go generators load packages that depend on the generated content mapper types. + await runGenerateContentMapper(); for (const generate of goGenerateActions) { await generate(); } @@ -685,7 +687,7 @@ async function runGenerateContentMapper() { export const generateContentMapper = task({ name: "generate:contentmapper", - description: "Generates Go content mapper protocol declarations from the JSON schema.", + description: "Generates content mapper protocol and Go/TypeScript span map types from the JSON schema.", outputs: contentMapperOutputs, run: runGenerateContentMapper, }); @@ -796,7 +798,6 @@ async function runGenerate() { await runWithConcurrencyLimit([runGenerateAST, runGenerateLSP], 2); await runGenerateGo(); }, - runGenerateContentMapper, runGenerateSync, async () => { await runGenerateExtension(); diff --git a/packages/typescript/enums/spanMapFeature.d.ts b/packages/typescript/enums/spanMapFeature.d.ts index d474f9cf6dc8c..712cf63c0ed9f 100644 --- a/packages/typescript/enums/spanMapFeature.d.ts +++ b/packages/typescript/enums/spanMapFeature.d.ts @@ -1,26 +1,26 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export declare enum SpanMapFeature { - Hover = 1 << 0, - SignatureHelp = 1 << 1, - Completion = 1 << 2, - Definition = 1 << 3, - TypeDefinition = 1 << 4, - Implementation = 1 << 5, - References = 1 << 6, - DocumentHighlights = 1 << 7, - Rename = 1 << 8, - CallHierarchy = 1 << 9, - CodeActions = 1 << 10, - Formatting = 1 << 11, - InlayHints = 1 << 12, - SemanticTokens = 1 << 13, - FoldingRanges = 1 << 14, - SelectionRanges = 1 << 15, - LinkedEditing = 1 << 16, - AutoInsert = 1 << 17, - DocumentSymbols = 1 << 18, - CodeLens = 1 << 19, + Hover = 1, + SignatureHelp = 2, + Completion = 4, + Definition = 8, + TypeDefinition = 16, + Implementation = 32, + References = 64, + DocumentHighlights = 128, + Rename = 256, + CallHierarchy = 512, + CodeActions = 1024, + Formatting = 2048, + InlayHints = 4096, + SemanticTokens = 8192, + FoldingRanges = 16384, + SelectionRanges = 32768, + LinkedEditing = 65536, + AutoInsert = 131072, + DocumentSymbols = 262144, + CodeLens = 524288, None = 0, - All = (CodeLens << 1) - 1, + All = 1048575, } diff --git a/packages/typescript/enums/spanMapFeature.js b/packages/typescript/enums/spanMapFeature.js index 6402af72d5799..b118a676d62e1 100644 --- a/packages/typescript/enums/spanMapFeature.js +++ b/packages/typescript/enums/spanMapFeature.js @@ -1,4 +1,4 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export var SpanMapFeature; (function (SpanMapFeature) { SpanMapFeature[SpanMapFeature["Hover"] = 1] = "Hover"; diff --git a/packages/typescript/enums/spanMapFidelity.d.ts b/packages/typescript/enums/spanMapFidelity.d.ts index ab38c97ee9cbc..5c3b2f0a59b1e 100644 --- a/packages/typescript/enums/spanMapFidelity.d.ts +++ b/packages/typescript/enums/spanMapFidelity.d.ts @@ -1,4 +1,4 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export declare enum SpanMapFidelity { Exact = 0, diff --git a/packages/typescript/enums/spanMapFidelity.js b/packages/typescript/enums/spanMapFidelity.js index efc070da1202c..4b7e74f7f424a 100644 --- a/packages/typescript/enums/spanMapFidelity.js +++ b/packages/typescript/enums/spanMapFidelity.js @@ -1,4 +1,4 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export var SpanMapFidelity; (function (SpanMapFidelity) { SpanMapFidelity[SpanMapFidelity["Exact"] = 0] = "Exact"; diff --git a/packages/typescript/enums/spanMapKind.d.ts b/packages/typescript/enums/spanMapKind.d.ts index d7376853bd9e1..829d002134efe 100644 --- a/packages/typescript/enums/spanMapKind.d.ts +++ b/packages/typescript/enums/spanMapKind.d.ts @@ -1,4 +1,4 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export declare enum SpanMapKind { Verbatim = 0, diff --git a/packages/typescript/enums/spanMapKind.js b/packages/typescript/enums/spanMapKind.js index c078ca744230c..e6202ab031e8c 100644 --- a/packages/typescript/enums/spanMapKind.js +++ b/packages/typescript/enums/spanMapKind.js @@ -1,4 +1,4 @@ -// Code generated by tools/scripts/tsc/generate-enums.ts from tsc/internal/spanmap/spanmap.go. DO NOT EDIT. +// Code generated by tools/scripts/tsc/generate-enums.ts from packages/typescript/schemas/contentmapper.schema.json. DO NOT EDIT. export var SpanMapKind; (function (SpanMapKind) { SpanMapKind[SpanMapKind["Verbatim"] = 0] = "Verbatim"; diff --git a/packages/typescript/schemas/contentmapper.schema.json b/packages/typescript/schemas/contentmapper.schema.json index 2873f203fff6b..f1752c38808d2 100644 --- a/packages/typescript/schemas/contentmapper.schema.json +++ b/packages/typescript/schemas/contentmapper.schema.json @@ -204,43 +204,165 @@ }, "required": ["text", "extension"] }, + "SpanMapKind": { + "type": "integer", + "description": "Relationship between positions in a virtual span and its original span.", + "oneOf": [ + { + "const": 0, + "title": "Verbatim", + "description": "Length-preserving segment whose interior positions map one-to-one." + }, + { + "const": 1, + "title": "Atom", + "description": "Segment mapped as a whole; interior positions clamp to its endpoints." + }, + { + "const": 2, + "title": "Alias", + "description": "Atom geometry whose virtual and original texts name the same logical entity." + } + ] + }, + "SpanMapFidelity": { + "type": "integer", + "description": "Faithfulness of a mapped span to the original.", + "oneOf": [ + { + "const": 0, + "title": "Exact", + "description": "Span entirely within a single verbatim segment, mapped precisely." + }, + { + "const": 1, + "title": "Atom", + "description": "Span within a single atom segment, mapped to that atom's span." + }, + { + "const": 2, + "title": "Approximate", + "description": "Span crossing segment boundaries, with mapped and clamped endpoints." + }, + { + "const": 3, + "title": "None", + "description": "Synthesized span with no original counterpart." + } + ] + }, + "SpanMapFeature": { + "type": "integer", + "description": "Language-service feature bitmask. Diagnostics and exact edit mapping do not use feature filtering. Named flags may be combined.", + "anyOf": [ + { "const": 1, "title": "Hover" }, + { "const": 2, "title": "SignatureHelp" }, + { "const": 4, "title": "Completion" }, + { "const": 8, "title": "Definition" }, + { "const": 16, "title": "TypeDefinition" }, + { "const": 32, "title": "Implementation" }, + { "const": 64, "title": "References" }, + { "const": 128, "title": "DocumentHighlights" }, + { "const": 256, "title": "Rename" }, + { "const": 512, "title": "CallHierarchy" }, + { "const": 1024, "title": "CodeActions" }, + { "const": 2048, "title": "Formatting" }, + { "const": 4096, "title": "InlayHints" }, + { "const": 8192, "title": "SemanticTokens" }, + { "const": 16384, "title": "FoldingRanges" }, + { "const": 32768, "title": "SelectionRanges" }, + { "const": 65536, "title": "LinkedEditing" }, + { "const": 131072, "title": "AutoInsert" }, + { "const": 262144, "title": "DocumentSymbols" }, + { "const": 524288, "title": "CodeLens" }, + { "const": 0, "title": "None" }, + { "const": 1048575, "title": "All" }, + { "minimum": 0, "maximum": 1048575 } + ] + }, + "SpanMapOffset": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647 + }, + "SpanMapTextRange": { + "type": "object", + "properties": { + "pos": { "$ref": "#/definitions/SpanMapOffset" }, + "end": { "$ref": "#/definitions/SpanMapOffset" } + }, + "required": ["pos", "end"] + }, + "SpanMapSourceSegment": { + "type": "object", + "description": "Mapping from a half-open virtual range to a half-open original range. Features controls language-service participation; diagnostics and exact edit mapping deliberately bypass it.", + "properties": { + "virtualStart": { "$ref": "#/definitions/SpanMapOffset" }, + "virtualEnd": { "$ref": "#/definitions/SpanMapOffset" }, + "originalStart": { "$ref": "#/definitions/SpanMapOffset" }, + "originalEnd": { "$ref": "#/definitions/SpanMapOffset" }, + "kind": { "$ref": "#/definitions/SpanMapKind" }, + "features": { "$ref": "#/definitions/SpanMapFeature" } + }, + "required": ["virtualStart", "virtualEnd", "originalStart", "originalEnd", "kind"] + }, + "SpanMapPosition": { + "type": "object", + "description": "Virtual projection of an original position and its mapping fidelity.", + "properties": { + "position": { "$ref": "#/definitions/SpanMapOffset" }, + "fidelity": { "$ref": "#/definitions/SpanMapFidelity" } + }, + "required": ["position", "fidelity"] + }, + "SpanMapRange": { + "type": "object", + "description": "Virtual projection of an original range and its mapping fidelity.", + "properties": { + "range": { "$ref": "#/definitions/SpanMapTextRange" }, + "fidelity": { "$ref": "#/definitions/SpanMapFidelity" } + }, + "required": ["range", "fidelity"] + }, "SpanMapSegment": { "type": "array", "description": "[virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text.", "items": [ { "type": "integer", + "title": "virtualStart", "minimum": 0, "maximum": 2147483647, "description": "Virtual start offset." }, { "type": "integer", + "title": "virtualLength", "minimum": 0, "maximum": 2147483647, "description": "Virtual span length." }, { "type": "integer", + "title": "originalStart", "minimum": 0, "maximum": 2147483647, "description": "Original start offset." }, { "type": "integer", + "title": "originalLength", "minimum": 0, "maximum": 2147483647, "description": "Original span length." }, { - "type": "integer", - "enum": [0, 1, 2], - "description": "Mapping kind: 0 is verbatim, 1 is atom, and 2 is alias." + "$ref": "#/definitions/SpanMapKind", + "title": "kind" }, { - "type": "integer", - "minimum": 0, - "maximum": 1048575, + "$ref": "#/definitions/SpanMapFeature", + "title": "features", "description": "Language-service feature bitmask. Omitted means all features (1048575); 0 disables all features. Does not suppress diagnostics." } ], diff --git a/packages/typescript/src/ast/spanMap.ts b/packages/typescript/src/ast/spanMap.ts index fe78c495ab8e4..c83e7ba4af02e 100644 --- a/packages/typescript/src/ast/spanMap.ts +++ b/packages/typescript/src/ast/spanMap.ts @@ -2,20 +2,14 @@ import { SpanMapFeature } from "../../enums/spanMapFeature.js"; import { SpanMapFidelity } from "../../enums/spanMapFidelity.js"; import { SpanMapKind } from "../../enums/spanMapKind.js"; import type { ReadonlyTextRange } from "./ast.ts"; +import type { + MappedPosition, + MappedRange, + SpanMapSegment, +} from "./spanMapTypes.generated.ts"; export { SpanMapFeature, SpanMapFidelity, SpanMapKind }; - -// Keep this in sync with spanmap.go - -/** Maps one half-open virtual range to one half-open original range. */ -export interface SpanMapSegment { - readonly virtualStart: number; - readonly virtualEnd: number; - readonly originalStart: number; - readonly originalEnd: number; - readonly kind: SpanMapKind; - readonly features?: SpanMapFeature; -} +export type { MappedPosition, MappedRange, SpanMapSegment, SpanMapSegmentTuple } from "./spanMapTypes.generated.ts"; /** Internal segment representation after omitted features have been normalized to `All`. */ type NormalizedSpanMapSegment = SpanMapSegment & { readonly features: SpanMapFeature; }; @@ -27,18 +21,6 @@ interface OriginalIndex { readonly maxEnds: readonly number[]; } -/** One virtual projection of an original position and its mapping fidelity. */ -export interface MappedPosition { - readonly position: number; - readonly fidelity: SpanMapFidelity; -} - -/** One virtual projection of an original range and its mapping fidelity. */ -export interface MappedRange { - readonly range: ReadonlyTextRange; - readonly fidelity: SpanMapFidelity; -} - /** Provides bidirectional span-aware mapping between virtual and original text. */ export class SpanMap { readonly segments: readonly NormalizedSpanMapSegment[]; diff --git a/packages/typescript/src/ast/spanMapTypes.generated.ts b/packages/typescript/src/ast/spanMapTypes.generated.ts new file mode 100644 index 0000000000000..6dc1a11ae938e --- /dev/null +++ b/packages/typescript/src/ast/spanMapTypes.generated.ts @@ -0,0 +1,31 @@ +// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT. + +import type { SpanMapFeature } from "../../enums/spanMapFeature.js"; +import type { SpanMapFidelity } from "../../enums/spanMapFidelity.js"; +import type { SpanMapKind } from "../../enums/spanMapKind.js"; +import type { ReadonlyTextRange } from "./ast.ts"; + +/** [virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text. */ +export type SpanMapSegmentTuple = [virtualStart: number, virtualLength: number, originalStart: number, originalLength: number, kind: SpanMapKind, features?: SpanMapFeature]; + +/** Mapping from a half-open virtual range to a half-open original range. Features controls language-service participation; diagnostics and exact edit mapping deliberately bypass it. */ +export interface SpanMapSegment { + readonly virtualStart: number; + readonly virtualEnd: number; + readonly originalStart: number; + readonly originalEnd: number; + readonly kind: SpanMapKind; + readonly features?: SpanMapFeature | undefined; +} + +/** Virtual projection of an original position and its mapping fidelity. */ +export interface MappedPosition { + readonly position: number; + readonly fidelity: SpanMapFidelity; +} + +/** Virtual projection of an original range and its mapping fidelity. */ +export interface MappedRange { + readonly range: ReadonlyTextRange; + readonly fidelity: SpanMapFidelity; +} diff --git a/tools/scripts/tsc/generate-contentmapper.ts b/tools/scripts/tsc/generate-contentmapper.ts index 889063ede43c9..9a3d20ea183cb 100644 --- a/tools/scripts/tsc/generate-contentmapper.ts +++ b/tools/scripts/tsc/generate-contentmapper.ts @@ -1,5 +1,5 @@ /** - * Generates the Go content mapper protocol declarations from the JSON schema. + * Generates content mapper protocol and span map types from the JSON schema. * Usage: npx hereby generate:contentmapper [--force] */ @@ -22,7 +22,9 @@ interface Schema { required?: string[]; items?: Schema | Schema[]; anyOf?: Schema[]; + oneOf?: Schema[]; allOf?: Schema[]; + const?: number; enum?: (string | number)[]; minimum?: number; maximum?: number; @@ -36,8 +38,145 @@ export interface SchemaDocument { "x-methods": Record; } -const schemaPath = path.join(repoRoot, "packages/typescript/schemas/contentmapper.schema.json"); -export const outputs = ["tsc/internal/contentmapper/protocol_generated.go"] as const; +export const schemaFile = "packages/typescript/schemas/contentmapper.schema.json"; +const schemaPath = path.join(repoRoot, schemaFile); +export const outputs = [ + "tsc/internal/contentmapper/protocol_generated.go", + "tsc/internal/spanmap/types_generated.go", + "packages/typescript/src/ast/spanMapTypes.generated.ts", +] as const; + +const spanMapEnums = { + SpanMapKind: "Kind", + SpanMapFidelity: "Fidelity", + SpanMapFeature: "Feature", +} as const; + +const spanMapObjects = { + SpanMapSourceSegment: { go: "Segment", ts: "SpanMapSegment" }, + SpanMapPosition: { go: "MappedPosition", ts: "MappedPosition" }, + SpanMapRange: { go: "MappedSpan", ts: "MappedRange" }, +} as const; + +const spanMapReferences: Record = { + ...Object.fromEntries(Object.entries(spanMapEnums).map(([name, go]) => [name, { go, ts: name }])), + ...spanMapObjects, + SpanMapOffset: { go: "core.TextPos", ts: "number" }, + SpanMapTextRange: { go: "core.TextRange", ts: "ReadonlyTextRange" }, +}; + +const generatedHeader = "// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT."; + +export function readSchema(): SchemaDocument { + return JSON.parse(fs.readFileSync(schemaPath, "utf8")); +} + +export function spanMapEnumMembers(document: SchemaDocument, name: string): { name: string; value: string; description: string | undefined; }[] { + const schema = document.definitions[name]; + assert(schema?.type === "integer", `Unsupported ${name} enum type`); + const variants = schema.oneOf ?? schema.anyOf; + assert(variants?.length, `Missing ${name} enum members`); + const names = new Set(); + const values = new Set(); + const members = variants.flatMap(member => { + if (member.const === undefined) { + assert( + schema.anyOf && !member.title + && member.minimum !== undefined && Number.isInteger(member.minimum) && member.minimum >= 0 + && member.maximum !== undefined && Number.isInteger(member.maximum) && member.maximum <= 2147483647 + && member.minimum <= member.maximum, + `Unsupported ${name} enum variant`, + ); + return []; + } + assert(member.title, `Missing ${name} enum member title`); + goName(member.title); + assert(!names.has(member.title), `Duplicate ${name} enum member title: ${member.title}`); + assert(!values.has(member.const), `Duplicate ${name} enum member value: ${member.const}`); + assert(Number.isInteger(member.const) && member.const >= -2147483648 && member.const <= 2147483647, `Unsupported ${name} enum value`); + names.add(member.title); + values.add(member.const); + return [{ name: member.title, value: String(member.const), description: member.description }]; + }); + assert(members.length, `Missing ${name} enum members`); + return members; +} + +function spanMapTuple(document: SchemaDocument): Schema & { items: Schema[]; minItems: number; maxItems: number; } { + const schema = document.definitions.SpanMapSegment; + assert(schema.type === "array" && Array.isArray(schema.items), "Unsupported SpanMapSegment tuple"); + assert(schema.minItems === 5 && schema.maxItems === 6 && schema.items.length === 6, "Unsupported SpanMapSegment tuple length"); + assert( + schema.items.every((item, index) => + item.title && (index < 4 + ? item.type === "integer" && item.minimum !== undefined && item.minimum >= -2147483648 && item.maximum !== undefined && item.maximum <= 2147483647 + : item.$ref === `#/definitions/${index === 4 ? "SpanMapKind" : "SpanMapFeature"}`) + ), + "Unsupported SpanMapSegment tuple items", + ); + return { ...schema, items: schema.items, minItems: schema.minItems, maxItems: schema.maxItems }; +} + +function spanMapType(schema: Schema, document: SchemaDocument, language: "go" | "ts"): string { + assert(schema.$ref, "Missing span map property reference"); + const name = referenceName(schema.$ref, document.definitions); + const type = spanMapReferences[name]; + assert(type, `Unsupported span map reference: ${name}`); + return type[language]; +} + +export function generateSpanMapGo(document: SchemaDocument): string { + const lines = [generatedHeader, "", "package spanmap", "", 'import "github.com/microsoft/TypeScript/tsc/internal/core"', ""]; + for (const [name, type] of Object.entries(spanMapEnums)) { + lines.push(...typeDescription(type, document.definitions[name].description), `type ${type} int32`, "", "const ("); + for (const member of spanMapEnumMembers(document, name)) { + lines.push(...typeDescription(`${type}${member.name}`, member.description).map(line => `\t${line}`)); + lines.push(`\t${type}${member.name} ${type} = ${member.value}`); + } + lines.push(")", ""); + } + const tuple = spanMapTuple(document); + lines.push(...typeDescription("SegmentTuple", tuple.description), "type SegmentTuple []int32", ""); + for (const [name, types] of Object.entries(spanMapObjects)) { + const schema = document.definitions[name]; + assert(schema.type === "object" && schema.properties, `Unsupported ${name} object`); + lines.push(...typeDescription(types.go, schema.description), `type ${types.go} struct {`); + for (const [property, value] of Object.entries(schema.properties)) { + const field = name === "SpanMapRange" && property === "range" ? "Span" : goName(property); + lines.push(`\t${field} ${spanMapType(value, document, "go")}`); + } + lines.push("}", ""); + } + return lines.join("\n"); +} + +export function generateSpanMapTS(document: SchemaDocument): string { + const lines = [ + generatedHeader, + "", + ...Object.keys(spanMapEnums).sort().map(name => `import type { ${name} } from "../../enums/${name[0].toLowerCase() + name.slice(1)}.js";`), + 'import type { ReadonlyTextRange } from "./ast.ts";', + "", + ]; + const tuple = spanMapTuple(document); + const items = tuple.items.map((item, index) => { + const type = item.$ref ? spanMapType(item, document, "ts") : "number"; + return `${item.title}${index >= tuple.minItems ? "?" : ""}: ${type}`; + }); + lines.push(`/** ${tuple.description} */`, `export type SpanMapSegmentTuple = [${items.join(", ")}];`, ""); + for (const [name, types] of Object.entries(spanMapObjects)) { + const schema = document.definitions[name]; + assert(schema.type === "object" && schema.properties, `Unsupported ${name} object`); + const required = new Set(schema.required); + lines.push(`/** ${schema.description} */`, `export interface ${types.ts} {`); + for (const [property, value] of Object.entries(schema.properties)) { + const optional = !required.has(property); + lines.push(` readonly ${property}${optional ? "?" : ""}: ${spanMapType(value, document, "ts")}${optional ? " | undefined" : ""};`); + } + lines.push("}", ""); + } + return lines.join("\n"); +} const enumNames: Record> = { PositionEncoding: { "utf-8": "UTF8", "utf-16": "UTF16" }, @@ -112,13 +251,14 @@ export function generateContentMapper(document: SchemaDocument): string { const methods = document["x-methods"]; assert(methods && typeof methods === "object" && Object.keys(methods).length > 0, "Missing content mapper methods"); const lines = [ - "// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT.", + generatedHeader, "", "package contentmapper", "", "import (", '\t"fmt"', '\t"github.com/microsoft/TypeScript/tsc/internal/json"', + '\t"github.com/microsoft/TypeScript/tsc/internal/spanmap"', ")", "", "// Content mapper protocol method names.", @@ -148,11 +288,6 @@ export function generateContentMapper(document: SchemaDocument): string { for (const [property, value] of Object.entries(schema.properties)) { const field = goName(property); let type = goType(value, definitions); - // Span maps are decoded by spanmap.Unmarshal, which consumes the entire raw JSON array. - if (name === "MappedOutput" && property === "mappings") { - assert(value.type === "array" && !Array.isArray(value.items) && value.items?.$ref === "#/definitions/SpanMapSegment", "Unsupported MappedOutput.mappings"); - type = "json.Value"; - } if (!required.has(property) && value.$ref && definitions[referenceName(value.$ref, definitions)].type === "object") { type = `*${type}`; } @@ -164,6 +299,7 @@ export function generateContentMapper(document: SchemaDocument): string { } for (const [name, schema] of Object.entries(definitions)) { + if (Object.hasOwn(spanMapReferences, name)) continue; goName(name); lines.push(...typeDescription(name, schema.description)); if (schema.$ref) { @@ -201,17 +337,8 @@ export function generateContentMapper(document: SchemaDocument): string { else if (Array.isArray(schema.items)) { assert(schema.type === "array" && schema.minItems === 5 && schema.maxItems === 6 && schema.items.length === 6, `Unsupported ${name} tuple`); if (name === "SpanMapSegment") { - assert(schema.description?.startsWith("[virtualStart, virtualLength, originalStart, originalLength, kind, features?]"), `Unsupported ${name} tuple order`); - assert( - schema.items.every(item => - item.type === "integer" - && (item.enum - ? item.enum.every(value => typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647) - : item.minimum !== undefined && item.minimum >= -2147483648 && item.maximum !== undefined && item.maximum <= 2147483647) - ), - `Unsupported ${name} tuple items`, - ); - lines.push(`type ${name} []int32`); + spanMapTuple(document); + lines.push(`type ${name} = spanmap.SegmentTuple`); } else if (schema.items.every(item => item.title)) { const names = schema.items.map(item => goName(item.title!)); @@ -279,13 +406,16 @@ export function generateContentMapper(document: SchemaDocument): string { } export default function generate(force = false): void { - const output = new GeneratedFile(path.join(repoRoot, outputs[0]), [import.meta.filename, schemaPath]); - if (output.isCurrent(force)) return; - const document: SchemaDocument = JSON.parse(fs.readFileSync(schemaPath, "utf8")); - output.write(generateContentMapper(document)); - formatFilesSync([output.fileName]); - output.markCurrent(); - console.log(`Wrote ${output.fileName}`); + const document = readSchema(); + const generators = [generateContentMapper, generateSpanMapGo, generateSpanMapTS]; + for (const [index, file] of outputs.entries()) { + const output = new GeneratedFile(path.join(repoRoot, file), [import.meta.filename, schemaPath]); + if (output.isCurrent(force)) continue; + output.write(generators[index](document)); + formatFilesSync([output.fileName]); + output.markCurrent(); + console.log(`Wrote ${output.fileName}`); + } } if (process.argv[1] === fileURLToPath(import.meta.url)) { diff --git a/tools/scripts/tsc/generate-enums.ts b/tools/scripts/tsc/generate-enums.ts index b8ff0c9d85e96..9cfce6b7fe8bc 100644 --- a/tools/scripts/tsc/generate-enums.ts +++ b/tools/scripts/tsc/generate-enums.ts @@ -10,6 +10,11 @@ import { repoRoot as ROOT, run, } from "../gen/utils.mts"; +import generateContentMapper, { + readSchema, + schemaFile, + spanMapEnumMembers, +} from "./generate-contentmapper.ts"; import generateOptions from "./generate-options.ts"; import { options } from "./options.ts"; import { api } from "./schema.ts"; @@ -68,9 +73,18 @@ export const enumDefs = [ { name: "CaseSensitivity", goPrefix: "Case", goFile: "tsc/internal/tspath/path.go", outDir: "packages/typescript/enums" }, { name: "TokenFlags", goPrefix: "TokenFlags", goFile: "tsc/internal/ast/tokenflags.go", outDir: "packages/typescript/enums" }, { name: "DiagnosticDirectivePolicy", goPrefix: "MappedDiagnosticDirectivePolicy", goFile: "tsc/internal/ast/ast.go", outDir: "packages/typescript/enums" }, - { name: "SpanMapKind", goPrefix: "Kind", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/enums" }, - { name: "SpanMapFidelity", goPrefix: "Fidelity", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/enums" }, - { name: "SpanMapFeature", goPrefix: "Feature", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/enums" }, + ...(["SpanMapKind", "SpanMapFidelity", "SpanMapFeature"] as const).map(name => ({ + name, + goPrefix: name.slice("SpanMap".length), + goFile: "tsc/internal/spanmap/types_generated.go", + outDir: "packages/typescript/enums", + metadata: { + file: schemaFile, + get members() { + return spanMapEnumMembers(readSchema(), name); + }, + }, + })), { name: "NodeBuilderFlags", goPrefix: "Flags", goFile: "tsc/internal/nodebuilder/types.go", outDir: "packages/typescript/enums" }, { name: "CompletionItemKind", goPrefix: "CompletionItemKind", goFile: "tsc/internal/lsp/lsproto/lsp_generated.go", outDir: "packages/typescript/enums" }, { name: "EmitOnly", goPrefix: "Emit", goFile: "tsc/internal/compiler/emitter.go", outDir: "packages/typescript/enums", excludeMembers: ["OnlyBuilderSignature"] }, @@ -486,6 +500,7 @@ async function evaluateEnumMembers(enumSource: string, enumName: string): Promis } export default async function generateEnums(force = false) { + generateContentMapper(); await generateOptions(force); const inputs = [ import.meta.filename, diff --git a/tsc/internal/contentmapper/host_test.go b/tsc/internal/contentmapper/host_test.go index 5cbcaa5e64c8f..b119279eb1c8e 100644 --- a/tsc/internal/contentmapper/host_test.go +++ b/tsc/internal/contentmapper/host_test.go @@ -27,6 +27,42 @@ import ( // fakeMapper is an in-process mapper that transforms content verbatim and reports one diagnostic. type fakeMapper struct{} +func TestMappedOutputMappingsJSON(t *testing.T) { + t.Parallel() + + output := contentmapper.MappedOutput{ + Text: "abcde", + Extension: ".ts", + Mappings: []contentmapper.SpanMapSegment{ + {0, 3, 10, 3, int32(spanmap.KindVerbatim)}, + {3, 2, 20, 2, int32(spanmap.KindAlias), int32(spanmap.FeatureNone)}, + }, + } + data, err := json.Marshal(output) + assert.NilError(t, err) + assert.Equal(t, string(data), `{"text":"abcde","extension":".ts","mappings":[[0,3,10,3,0],[3,2,20,2,2,0]]}`) + var decoded contentmapper.MappedOutput + assert.NilError(t, json.Unmarshal(data, &decoded)) + assert.DeepEqual(t, decoded, output) + + for _, data := range []string{ + `{"text":"","extension":".ts"}`, + `{"text":"","extension":".ts","mappings":null}`, + `{"text":"","extension":".ts","mappings":[]}`, + } { + var decoded contentmapper.MappedOutput + assert.NilError(t, json.Unmarshal([]byte(data), &decoded)) + assert.Equal(t, len(decoded.Mappings), 0) + } + for _, data := range []string{ + `{"mappings":[[0,1,0,1,"verbatim"]]}`, + `{"mappings":[[0,2147483648,0,1,0]]}`, + } { + var decoded contentmapper.MappedOutput + assert.Assert(t, json.Unmarshal([]byte(data), &decoded) != nil) + } +} + func TestEmptyOutputExtensionsOverrideSurvivesSerialization(t *testing.T) { t.Parallel() definition := contentmapper.Definition{Package: "mapper", Extensions: []string{".vue"}, OutputExtensions: map[string]string{}} @@ -72,16 +108,13 @@ func (fakeMapper) HandleRequest(ctx context.Context, method string, params json. if err := json.Unmarshal(params, &p); err != nil { return nil, err } - mappings, err := spanmap.New([]spanmap.Segment{{ + mappings := spanmap.New([]spanmap.Segment{{ VirtualEnd: core.TextPos(len(p.Content)), OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, - }}).Marshal() - if err != nil { - return nil, err - } + }}).Tuples() return contentmapper.TransformResult{ - Text: p.Content, Extension: ".ts", Mappings: json.Value(mappings), + Text: p.Content, Extension: ".ts", Mappings: mappings, Diagnostics: []contentmapper.Diagnostic{{ MessageText: "boom", Start: 0, @@ -136,12 +169,9 @@ func (m unicodeMapper) HandleRequest(ctx context.Context, method string, params default: return contentmapper.TransformResult{Text: p.Content, Extension: ".ts"}, nil } - mappings, err := json.Marshal([][5]int{ - {0, emojiLength, 0, emojiLength, int(spanmap.KindVerbatim)}, - {emojiLength, textLength - emojiLength, emojiLength, textLength - emojiLength, int(spanmap.KindVerbatim)}, - }) - if err != nil { - return nil, err + mappings := []contentmapper.SpanMapSegment{ + {0, int32(emojiLength), 0, int32(emojiLength), int32(spanmap.KindVerbatim)}, + {int32(emojiLength), int32(textLength - emojiLength), int32(emojiLength), int32(textLength - emojiLength), int32(spanmap.KindVerbatim)}, } return contentmapper.TransformResult{ Text: p.Content, @@ -710,6 +740,35 @@ func TestRunnerTransformInvalidSupplementalDiagnosticDirective(t *testing.T) { assert.Equal(t, directiveError.SupplementalIndex, 1) } +func TestRunnerTransformSpanMapTuples(t *testing.T) { + t.Parallel() + + for _, supplemental := range []bool{false, true} { + t.Run(fmt.Sprintf("supplemental=%t", supplemental), func(t *testing.T) { + t.Parallel() + output := contentmapper.MappedOutput{ + Text: "abcde", + Extension: ".ts", + Mappings: []contentmapper.SpanMapSegment{{0, 1, 0, 1}}, + } + host := contentmapper.NewHost(t.Context(), &fakeSpawner{handler: responseMapper{response: func(p contentmapper.TransformParams) any { + canonical := contentmapper.MappedOutput{Text: "abcde", Extension: ".ts"} + if supplemental { + return contentmapper.TransformResult{ + MappedOutput: canonical, + Supplemental: []contentmapper.SupplementalOutput{{MappedOutput: output}}, + } + } + return contentmapper.TransformResult{MappedOutput: output} + }}}, locale.Default) + defer host.Close() + mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}} + _, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: "abcde"}) + assert.ErrorContains(t, err, "span map segment 0: expected 5 or 6 values, got 4") + }) + } +} + func TestRunnerRejectsInvalidVirtualExtension(t *testing.T) { t.Parallel() for _, supplemental := range []bool{false, true} { diff --git a/tsc/internal/contentmapper/hostimpl.go b/tsc/internal/contentmapper/hostimpl.go index 98242c17b56ca..69efdbe552298 100644 --- a/tsc/internal/contentmapper/hostimpl.go +++ b/tsc/internal/contentmapper/hostimpl.go @@ -1007,7 +1007,7 @@ func decodeMappedOutput(output MappedOutput, originalText string, positionEncodi // synthesized output (no segment corresponds to the original), so decode to an empty map rather than // nil, which would mean "not content-mapped". if len(output.Mappings) > 0 { - mappings, unmarshalErr := spanmap.Unmarshal(output.Mappings) + mappings, unmarshalErr := spanmap.FromTuples(output.Mappings) if unmarshalErr != nil { return MappedResult{}, nil, unmarshalErr } diff --git a/tsc/internal/contentmapper/protocol_generated.go b/tsc/internal/contentmapper/protocol_generated.go index 021208bd77f33..a0ad957c608f1 100644 --- a/tsc/internal/contentmapper/protocol_generated.go +++ b/tsc/internal/contentmapper/protocol_generated.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/microsoft/TypeScript/tsc/internal/json" + "github.com/microsoft/TypeScript/tsc/internal/spanmap" ) // Content mapper protocol method names. @@ -93,14 +94,14 @@ type MappedOutput struct { // Extension is the extension determining the virtual source file's syntax. Extension string `json:"extension"` // Mappings lists the span map tuples in the selected position encoding. Absent or empty mappings describe fully synthesized output. - Mappings json.Value `json:"mappings,omitempty"` + Mappings []SpanMapSegment `json:"mappings,omitempty"` // DiagnosticDirectives contains the shared unused-expect diagnostics and compact diagnostic directive tuples. DiagnosticDirectives *DiagnosticDirectives `json:"diagnosticDirectives,omitempty"` } // SpanMapSegment is encoded as [virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments // must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text. -type SpanMapSegment []int32 +type SpanMapSegment = spanmap.SegmentTuple // DiagnosticDirectivePolicy describes the diagnostic directive policy: 0 ignores diagnostics; 1 expects a diagnostic. type DiagnosticDirectivePolicy uint8 diff --git a/tsc/internal/spanmap/spanmap.go b/tsc/internal/spanmap/spanmap.go index 465fa24b386ec..edaa6e11ca619 100644 --- a/tsc/internal/spanmap/spanmap.go +++ b/tsc/internal/spanmap/spanmap.go @@ -6,8 +6,6 @@ // offsets (core.TextPos), matching the compiler's TextRange model. package spanmap -// Keep this in sync with spanMap.ts - import ( "fmt" "slices" @@ -18,69 +16,8 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/json" ) -// Kind describes how positions inside a segment relate the virtual span to the original span. -type Kind int32 - -const ( - // KindVerbatim segments are length-preserving: the virtual and original spans have the same - // length and interior positions map 1:1 (OriginalPos = pos - VirtualStart + OriginalStart). A virtual span - // fully within a verbatim segment maps to an exact original span. - KindVerbatim Kind = iota - // KindAtom segments map a virtual span to an original span as a whole; interior positions are not - // interpolatable (the lengths may differ), so positions within clamp to the segment's endpoints. - // Used for renamed identifiers or short expressions. - KindAtom - // KindAlias has atom geometry, but additionally asserts that the virtual and original texts are - // names for the same logical entity. Diagnostic presentation may substitute the original name. - KindAlias -) - -// Feature selects which language-service operations may use a segment. Diagnostics are intentionally not -// represented: diagnostics on virtual text may not opt out of reporting. Text edits additionally require exact -// verbatim geometry regardless of feature participation. -type Feature int32 - -const ( - FeatureHover Feature = 1 << iota - FeatureSignatureHelp - FeatureCompletion - FeatureDefinition - FeatureTypeDefinition - FeatureImplementation - FeatureReferences - FeatureDocumentHighlights - FeatureRename - FeatureCallHierarchy - FeatureCodeActions - FeatureFormatting - FeatureInlayHints - FeatureSemanticTokens - FeatureFoldingRanges - FeatureSelectionRanges - FeatureLinkedEditing - FeatureAutoInsert - FeatureDocumentSymbols - FeatureCodeLens - FeatureNone Feature = 0 - FeatureAll Feature = (FeatureCodeLens << 1) - 1 -) - const featureMask = FeatureAll -// Fidelity describes how faithfully a mapped span reflects the original. -type Fidelity int32 - -const ( - // FidelityExact means the span fell entirely within a single verbatim segment and maps precisely. - FidelityExact Fidelity = iota - // FidelityAtom means the span fell within a single atom segment and maps to that atom's span. - FidelityAtom - // FidelityApproximate means the span crossed segment boundaries; its endpoints were mapped and clamped. - FidelityApproximate - // FidelityNone means the span had no original counterpart (it was entirely synthesized). - FidelityNone -) - // IsExact reports whether the mapping was fully faithful — the input fell within a single verbatim span — // so the result maps 1:1 and can host a text edit written back to the original. func (f Fidelity) IsExact() bool { @@ -99,30 +36,6 @@ func (f Fidelity) IsNone() bool { return f == FidelityNone } -// Segment maps the half-open virtual range [VirtualStart, VirtualEnd) to the half-open original range -// [OriginalStart, OriginalEnd). Features controls language-service participation; diagnostics and exact edit mapping -// deliberately bypass it. -type Segment struct { - VirtualStart core.TextPos - VirtualEnd core.TextPos - OriginalStart core.TextPos - OriginalEnd core.TextPos - Kind Kind - Features Feature -} - -// MappedPosition is one virtual projection of an original position and its mapping fidelity. -type MappedPosition struct { - Position core.TextPos - Fidelity Fidelity -} - -// MappedSpan is one virtual projection of an original range and its mapping fidelity. -type MappedSpan struct { - Span core.TextRange - Fidelity Fidelity -} - // SpanMap is a sparse, ordered set of segments over a content mapper's virtual text. Segments do not // need to cover the whole text: any virtual position not inside a segment is synthesized (it has no // original counterpart). An empty SpanMap therefore describes fully synthesized virtual text. @@ -774,10 +687,15 @@ func clamp(v, lo, hi core.TextPos) core.TextPos { // Five-element tuples omit features and are normalized to FeatureAll; six-element tuples preserve the // explicit feature mask, including FeatureNone. func Unmarshal(data []byte) (*SpanMap, error) { - var tuples [][]int32 + var tuples []SegmentTuple if err := json.Unmarshal(data, &tuples); err != nil { return nil, err } + return FromTuples(tuples) +} + +// FromTuples decodes span map tuples, defaulting omitted features to FeatureAll. +func FromTuples(tuples []SegmentTuple) (*SpanMap, error) { segments := make([]Segment, len(tuples)) for i, t := range tuples { if len(t) != 5 && len(t) != 6 { @@ -801,9 +719,14 @@ func Unmarshal(data []byte) (*SpanMap, error) { // Marshal encodes a SpanMap into the JSON tuple form. FeatureAll uses the backward-compatible five-element // tuple; every other feature mask is emitted as a sixth element. func (m *SpanMap) Marshal() ([]byte, error) { - tuples := make([][]int32, len(m.segments)) + return json.Marshal(m.Tuples()) +} + +// Tuples encodes segments as wire tuples, omitting the feature mask only for FeatureAll. +func (m *SpanMap) Tuples() []SegmentTuple { + tuples := make([]SegmentTuple, len(m.segments)) for i, s := range m.segments { - tuples[i] = []int32{ + tuples[i] = SegmentTuple{ int32(s.VirtualStart), int32(s.VirtualEnd - s.VirtualStart), int32(s.OriginalStart), @@ -814,5 +737,5 @@ func (m *SpanMap) Marshal() ([]byte, error) { tuples[i] = append(tuples[i], int32(s.Features)) } } - return json.Marshal(tuples) + return tuples } diff --git a/tsc/internal/spanmap/spanmap_test.go b/tsc/internal/spanmap/spanmap_test.go index f4902ca11214a..7020815d3a04f 100644 --- a/tsc/internal/spanmap/spanmap_test.go +++ b/tsc/internal/spanmap/spanmap_test.go @@ -591,6 +591,46 @@ func TestMarshalRoundTrip(t *testing.T) { } } +func TestSegmentTuples(t *testing.T) { + t.Parallel() + + tuples := []spanmap.SegmentTuple{ + {0, 3, 10, 3, int32(spanmap.KindVerbatim)}, + {3, 2, 20, 4, int32(spanmap.KindAlias), int32(spanmap.FeatureNone)}, + {5, 2, 30, 2, int32(spanmap.KindAtom), int32(spanmap.FeatureHover | spanmap.FeatureRename)}, + } + m, err := spanmap.FromTuples(tuples) + assert.NilError(t, err) + assert.Equal(t, m.Segments()[0].Features, spanmap.FeatureAll) + assert.Equal(t, m.Segments()[1].Features, spanmap.FeatureNone) + assert.Equal(t, m.Segments()[1].VirtualEnd, core.TextPos(5)) + assert.Equal(t, m.Segments()[1].OriginalEnd, core.TextPos(24)) + assert.DeepEqual(t, m.Tuples(), tuples) + encoded, err := m.Marshal() + assert.NilError(t, err) + decoded, err := spanmap.Unmarshal(encoded) + assert.NilError(t, err) + assert.DeepEqual(t, decoded.Tuples(), tuples) +} + +func TestInvalidSegmentTupleLengths(t *testing.T) { + t.Parallel() + + for _, tuple := range []spanmap.SegmentTuple{nil, {}, {0, 1, 0, 1}, {0, 1, 0, 1, 0, 0, 0}} { + m, err := spanmap.FromTuples([]spanmap.SegmentTuple{{0, 1, 0, 1, 0}, tuple}) + assert.Assert(t, m == nil) + assert.ErrorContains(t, err, "span map segment 1: expected 5 or 6 values") + } + for _, tuples := range [][]spanmap.SegmentTuple{nil, {}} { + m, err := spanmap.FromTuples(tuples) + assert.NilError(t, err) + assert.Equal(t, len(m.Segments()), 0) + encoded, err := m.Marshal() + assert.NilError(t, err) + assert.Equal(t, string(encoded), "[]") + } +} + func TestValidate(t *testing.T) { t.Parallel() diff --git a/tsc/internal/spanmap/types_generated.go b/tsc/internal/spanmap/types_generated.go new file mode 100644 index 0000000000000..1ba923881941c --- /dev/null +++ b/tsc/internal/spanmap/types_generated.go @@ -0,0 +1,87 @@ +// Code generated by tools/scripts/tsc/generate-contentmapper.ts. DO NOT EDIT. + +package spanmap + +import "github.com/microsoft/TypeScript/tsc/internal/core" + +// Kind describes the relationship between positions in a virtual span and its original span. +type Kind int32 + +const ( + // KindVerbatim describes the length-preserving segment whose interior positions map one-to-one. + KindVerbatim Kind = 0 + // KindAtom describes the segment mapped as a whole; interior positions clamp to its endpoints. + KindAtom Kind = 1 + // KindAlias describes the atom geometry whose virtual and original texts name the same logical entity. + KindAlias Kind = 2 +) + +// Fidelity describes the faithfulness of a mapped span to the original. +type Fidelity int32 + +const ( + // FidelityExact describes the span entirely within a single verbatim segment, mapped precisely. + FidelityExact Fidelity = 0 + // FidelityAtom describes the span within a single atom segment, mapped to that atom's span. + FidelityAtom Fidelity = 1 + // FidelityApproximate describes the span crossing segment boundaries, with mapped and clamped endpoints. + FidelityApproximate Fidelity = 2 + // FidelityNone describes the synthesized span with no original counterpart. + FidelityNone Fidelity = 3 +) + +// Feature describes the language-service feature bitmask. Diagnostics and exact edit mapping do not use feature +// filtering. Named flags may be combined. +type Feature int32 + +const ( + FeatureHover Feature = 1 + FeatureSignatureHelp Feature = 2 + FeatureCompletion Feature = 4 + FeatureDefinition Feature = 8 + FeatureTypeDefinition Feature = 16 + FeatureImplementation Feature = 32 + FeatureReferences Feature = 64 + FeatureDocumentHighlights Feature = 128 + FeatureRename Feature = 256 + FeatureCallHierarchy Feature = 512 + FeatureCodeActions Feature = 1024 + FeatureFormatting Feature = 2048 + FeatureInlayHints Feature = 4096 + FeatureSemanticTokens Feature = 8192 + FeatureFoldingRanges Feature = 16384 + FeatureSelectionRanges Feature = 32768 + FeatureLinkedEditing Feature = 65536 + FeatureAutoInsert Feature = 131072 + FeatureDocumentSymbols Feature = 262144 + FeatureCodeLens Feature = 524288 + FeatureNone Feature = 0 + FeatureAll Feature = 1048575 +) + +// SegmentTuple is encoded as [virtualStart, virtualLength, originalStart, originalLength, kind, features?]. Segments +// must be ordered and disjoint in virtual space and within both texts. Verbatim segments must contain identical text. +type SegmentTuple []int32 + +// Segment describes the mapping from a half-open virtual range to a half-open original range. Features controls +// language-service participation; diagnostics and exact edit mapping deliberately bypass it. +type Segment struct { + VirtualStart core.TextPos + VirtualEnd core.TextPos + OriginalStart core.TextPos + OriginalEnd core.TextPos + Kind Kind + Features Feature +} + +// MappedPosition describes the virtual projection of an original position and its mapping fidelity. +type MappedPosition struct { + Position core.TextPos + Fidelity Fidelity +} + +// MappedSpan describes the virtual projection of an original range and its mapping fidelity. +type MappedSpan struct { + Span core.TextRange + Fidelity Fidelity +} diff --git a/tsc/internal/testutil/contentmappertest/component.go b/tsc/internal/testutil/contentmappertest/component.go index 57ed38a5bccaf..0d9680da7faea 100644 --- a/tsc/internal/testutil/contentmappertest/component.go +++ b/tsc/internal/testutil/contentmappertest/component.go @@ -33,7 +33,7 @@ func (componentHandler) HandleRequest(ctx context.Context, method string, params } } -func transformComponent(content string) (string, json.Value, error) { +func transformComponent(content string) (string, []contentmapper.SpanMapSegment, error) { var virtual strings.Builder var segments []spanmap.Segment @@ -117,11 +117,7 @@ func transformComponent(content string) (string, json.Value, error) { } writeAnchored("export default {};\n", 0, spanmap.FeatureDefinition|spanmap.FeatureReferences) - mappings, err := spanmap.New(segments).Marshal() - if err != nil { - return "", nil, err - } - return virtual.String(), json.Value(mappings), nil + return virtual.String(), spanmap.New(segments).Tuples(), nil } func componentNameRange(content string) (start, end int, ok bool) { diff --git a/tsc/internal/testutil/contentmappertest/duplicate.go b/tsc/internal/testutil/contentmappertest/duplicate.go index 005fcf4e73cff..b81eff0722769 100644 --- a/tsc/internal/testutil/contentmappertest/duplicate.go +++ b/tsc/internal/testutil/contentmappertest/duplicate.go @@ -26,55 +26,43 @@ func (duplicateHandler) HandleRequest(ctx context.Context, method string, params virtual := "// " + p.Content + "\nconst " + p.Content + " = 1;\n" first := len("// ") second := first + len(p.Content) + len("\nconst ") - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: core.TextPos(first), VirtualEnd: core.TextPos(first + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureHover}, {VirtualStart: core.TextPos(second), VirtualEnd: core.TextPos(second + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureHover}, - }).Marshal() - if err != nil { - return nil, err - } - return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }).Tuples() + return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: mappings}, nil } if strings.Contains(p.FileName, "hover-concat") { virtual := "namespace A { export const " + p.Content + " = 1; }\nnamespace B { export const " + p.Content + " = \"text\"; }\n" first := strings.Index(virtual, p.Content) second := strings.LastIndex(virtual, p.Content) - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: core.TextPos(first), VirtualEnd: core.TextPos(first + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureHover}, {VirtualStart: core.TextPos(second), VirtualEnd: core.TextPos(second + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureHover}, - }).Marshal() - if err != nil { - return nil, err - } - return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }).Tuples() + return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: mappings}, nil } if strings.Contains(p.FileName, "signature-fallback") { virtual := "// " + p.Content + "\nfunction use(value: number): void {}\n" + p.Content + ";\n" first := len("// ") second := strings.LastIndex(virtual, p.Content) - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: core.TextPos(first), VirtualEnd: core.TextPos(first + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureSignatureHelp}, {VirtualStart: core.TextPos(second), VirtualEnd: core.TextPos(second + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureSignatureHelp}, - }).Marshal() - if err != nil { - return nil, err - } - return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }).Tuples() + return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: mappings}, nil } if strings.Contains(p.FileName, "rename-conflict") { virtual := "export const " + p.Content + " = 1;\nconst object = { " + p.Content + " };\n" + p.Content + ";\n" first := strings.Index(virtual, p.Content) second := strings.Index(virtual[first+len(p.Content):], p.Content) + first + len(p.Content) third := strings.Index(virtual[second+len(p.Content):], p.Content) + second + len(p.Content) - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: core.TextPos(first), VirtualEnd: core.TextPos(first + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureRename}, {VirtualStart: core.TextPos(second), VirtualEnd: core.TextPos(second + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureRename}, {VirtualStart: core.TextPos(third), VirtualEnd: core.TextPos(third + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureRename}, - }).Marshal() - if err != nil { - return nil, err - } - return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }).Tuples() + return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: mappings}, nil } virtual := "export const " + p.Content + " = 1;\n" + p.Content + ";\n" first := len("export const ") @@ -86,14 +74,11 @@ func (duplicateHandler) HandleRequest(ctx context.Context, method string, params semanticFeatures = spanmap.FeatureNone navigationFeatures = spanmap.FeatureNone } - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: core.TextPos(first), VirtualEnd: core.TextPos(first + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: semanticFeatures}, {VirtualStart: core.TextPos(second), VirtualEnd: core.TextPos(second + len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: navigationFeatures}, - }).Marshal() - if err != nil { - return nil, err - } - return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }).Tuples() + return contentmapper.TransformResult{Text: virtual, Extension: ".ts", Mappings: mappings}, nil default: return nil, fmt.Errorf("contentmappertest: unexpected method %q", method) } diff --git a/tsc/internal/testutil/contentmappertest/editing.go b/tsc/internal/testutil/contentmappertest/editing.go index d295837a46bbe..c39d87ee1d663 100644 --- a/tsc/internal/testutil/contentmappertest/editing.go +++ b/tsc/internal/testutil/contentmappertest/editing.go @@ -80,55 +80,43 @@ func (prefixedSupplementalHandler) HandleRequest(ctx context.Context, method str Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll, }} - canonicalMappings, err := spanmap.New([]spanmap.Segment{{ + canonicalMappings := spanmap.New([]spanmap.Segment{{ VirtualStart: 0, VirtualEnd: core.TextPos(thirdStart), OriginalStart: 0, OriginalEnd: core.TextPos(thirdStart), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll, - }}).Marshal() - if err != nil { - return nil, err - } - mappings, err := spanmap.New(segments).Marshal() - if err != nil { - return nil, err - } + }}).Tuples() + mappings := spanmap.New(segments).Tuples() return contentmapper.TransformResult{ - Text: p.Content[:thirdStart], Extension: ".ts", Mappings: json.Value(canonicalMappings), + Text: p.Content[:thirdStart], Extension: ".ts", Mappings: canonicalMappings, Supplemental: []contentmapper.SupplementalOutput{{ Text: supplementalText, Extension: ".ts", - Mappings: json.Value(mappings), + Mappings: mappings, }}, }, nil } - mappings, err := spanmap.New(segments).Marshal() - if err != nil { - return nil, err - } + mappings := spanmap.New(segments).Tuples() canonical := contentmapper.MappedOutput{Text: "export {};", Extension: ".ts"} if strings.Contains(p.FileName, "folding-duplicate") || strings.Contains(p.FileName, "codelens-disabled") || strings.Contains(p.FileName, "codelens-duplicate") { - canonicalMappings, err := spanmap.New([]spanmap.Segment{{ + canonicalMappings := spanmap.New([]spanmap.Segment{{ VirtualStart: 0, VirtualEnd: core.TextPos(len(p.Content)), OriginalStart: 0, OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll, - }}).Marshal() - if err != nil { - return nil, err - } - canonical = contentmapper.MappedOutput{Text: p.Content, Extension: ".ts", Mappings: json.Value(canonicalMappings)} + }}).Tuples() + canonical = contentmapper.MappedOutput{Text: p.Content, Extension: ".ts", Mappings: canonicalMappings} } return contentmapper.TransformResult{ MappedOutput: canonical, Supplemental: []contentmapper.SupplementalOutput{{ Text: supplementalText, Extension: ".ts", - Mappings: json.Value(mappings), + Mappings: mappings, }}, }, nil default: @@ -143,10 +131,7 @@ func (unmappedFoldingHandler) HandleRequest(ctx context.Context, method string, case contentmapper.MethodInitialize: return initializeResult("mapper"), nil case contentmapper.MethodTransform: - mappings, err := spanmap.New(nil).Marshal() - if err != nil { - return nil, err - } + mappings := spanmap.New(nil).Tuples() return contentmapper.TransformResult{ Text: `import "a"; import "b"; @@ -155,7 +140,7 @@ import "b"; */ export {};`, Extension: ".ts", - Mappings: json.Value(mappings), + Mappings: mappings, }, nil default: return nil, fmt.Errorf("contentmappertest: unexpected method %q", method) diff --git a/tsc/internal/testutil/contentmappertest/hoisting.go b/tsc/internal/testutil/contentmappertest/hoisting.go index 04f47456fd2cb..4a6b03671c946 100644 --- a/tsc/internal/testutil/contentmappertest/hoisting.go +++ b/tsc/internal/testutil/contentmappertest/hoisting.go @@ -48,7 +48,7 @@ func (hoistingHandler) HandleRequest(ctx context.Context, method string, params // that are contiguous in the original but disjoint in the virtual text, so the original position at a // splice point (importsStart) lies on the boundary of two verbatim segments and projects to two distinct // exact virtual positions. -func transformHoisting(content string) (string, json.Value, error) { +func transformHoisting(content string) (string, []contentmapper.SpanMapSegment, error) { var virtual strings.Builder var segments []spanmap.Segment @@ -78,11 +78,7 @@ func transformHoisting(content string) (string, json.Value, error) { writeMapped(importsEnd, scriptEnd) virtual.WriteString("\n;\nreturn { props: {} as Record }}\n") - mappings, err := spanmap.New(segments).Marshal() - if err != nil { - return "", nil, err - } - return virtual.String(), json.Value(mappings), nil + return virtual.String(), spanmap.New(segments).Tuples(), nil } func scriptRange(content string) (start, end int, err error) { diff --git a/tsc/internal/testutil/contentmappertest/lisp.go b/tsc/internal/testutil/contentmappertest/lisp.go index 74bb3c3427f6f..5226db5fdae38 100644 --- a/tsc/internal/testutil/contentmappertest/lisp.go +++ b/tsc/internal/testutil/contentmappertest/lisp.go @@ -24,19 +24,16 @@ func (lispHandler) HandleRequest(ctx context.Context, method string, params json if strings.TrimSuffix(p.Content, "\n") != `(+ 1 2 "oops")` { return nil, fmt.Errorf("contentmappertest: unsupported Lisp expression %q", p.Content) } - mappings, err := spanmap.New([]spanmap.Segment{ + mappings := spanmap.New([]spanmap.Segment{ {VirtualStart: 0, VirtualEnd: 3, OriginalStart: 1, OriginalEnd: 2, Kind: spanmap.KindAlias, Features: spanmap.FeatureAll}, {VirtualStart: 4, VirtualEnd: 5, OriginalStart: 3, OriginalEnd: 4, Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll}, {VirtualStart: 7, VirtualEnd: 8, OriginalStart: 5, OriginalEnd: 6, Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll}, {VirtualStart: 10, VirtualEnd: 16, OriginalStart: 7, OriginalEnd: 13, Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll}, - }).Marshal() - if err != nil { - return nil, err - } + }).Tuples() return contentmapper.TransformResult{ Text: `add(1, 2, "oops");`, Extension: ".ts", - Mappings: json.Value(mappings), + Mappings: mappings, }, nil default: return nil, fmt.Errorf("contentmappertest: unexpected method %q", method) diff --git a/tsc/internal/testutil/contentmappertest/protocol.go b/tsc/internal/testutil/contentmappertest/protocol.go index acff7f602f83a..55e2063c6f7e6 100644 --- a/tsc/internal/testutil/contentmappertest/protocol.go +++ b/tsc/internal/testutil/contentmappertest/protocol.go @@ -25,16 +25,13 @@ func initializeResult(source string) contentmapper.InitializeResult { } func identityMappedOutput(content string) (contentmapper.MappedOutput, error) { - mappings, err := spanmap.New([]spanmap.Segment{{ + mappings := spanmap.New([]spanmap.Segment{{ VirtualEnd: core.TextPos(len(content)), OriginalEnd: core.TextPos(len(content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll, - }}).Marshal() - if err != nil { - return contentmapper.MappedOutput{}, err - } - return contentmapper.MappedOutput{Text: content, Extension: ".ts", Mappings: json.Value(mappings)}, nil + }}).Tuples() + return contentmapper.MappedOutput{Text: content, Extension: ".ts", Mappings: mappings}, nil } type staticProjectHandler struct{ ipc.Handler } diff --git a/tsc/internal/testutil/contentmappertest/supplemental_diagnostics.go b/tsc/internal/testutil/contentmappertest/supplemental_diagnostics.go index 43dcc8af625d1..d28c174815133 100644 --- a/tsc/internal/testutil/contentmappertest/supplemental_diagnostics.go +++ b/tsc/internal/testutil/contentmappertest/supplemental_diagnostics.go @@ -22,19 +22,16 @@ func (supplementalDiagnosticsHandler) HandleRequest(ctx context.Context, method return nil, err } const prefix = "missingSupplementalGlobal;\n" - mappings, err := spanmap.New([]spanmap.Segment{{ + mappings := spanmap.New([]spanmap.Segment{{ VirtualStart: core.TextPos(len(prefix)), VirtualEnd: core.TextPos(len(prefix) + len(p.Content)), OriginalEnd: core.TextPos(len(p.Content)), Kind: spanmap.KindVerbatim, Features: spanmap.FeatureAll, - }}).Marshal() - if err != nil { - return nil, err - } + }}).Tuples() return contentmapper.TransformResult{ Text: "export {};", Extension: ".ts", - Supplemental: []contentmapper.SupplementalOutput{{Text: prefix + p.Content, Extension: ".ts", Mappings: json.Value(mappings)}}, + Supplemental: []contentmapper.SupplementalOutput{{Text: prefix + p.Content, Extension: ".ts", Mappings: mappings}}, }, nil default: return nil, fmt.Errorf("contentmappertest: unexpected method %q", method) diff --git a/tsc/internal/testutil/contentmappertest/synthesizing.go b/tsc/internal/testutil/contentmappertest/synthesizing.go index de35db3ddef0e..42095860279a3 100644 --- a/tsc/internal/testutil/contentmappertest/synthesizing.go +++ b/tsc/internal/testutil/contentmappertest/synthesizing.go @@ -22,14 +22,11 @@ func (synthesizingHandler) HandleRequest(ctx context.Context, method string, par if err := json.Unmarshal(params, &p); err != nil { return nil, err } - mappings, err := spanmap.New(nil).Marshal() - if err != nil { - return nil, err - } + mappings := spanmap.New(nil).Tuples() return contentmapper.TransformResult{ Text: synthesizedOutput, Extension: ".ts", - Mappings: json.Value(mappings), + Mappings: mappings, }, nil default: return nil, fmt.Errorf("contentmappertest: unexpected method %q", method) diff --git a/tsc/internal/testutil/contentmappertest/transforming.go b/tsc/internal/testutil/contentmappertest/transforming.go index 42ba711ea76a5..f9f4da0bf089d 100644 --- a/tsc/internal/testutil/contentmappertest/transforming.go +++ b/tsc/internal/testutil/contentmappertest/transforming.go @@ -88,7 +88,7 @@ func mappedExtension(content string) string { return ".ts" } -func transform(content string, options *collections.OrderedMap[string, json.Value]) (string, json.Value, []contentmapper.Diagnostic, *contentmapper.DiagnosticDirectives, error) { +func transform(content string, options *collections.OrderedMap[string, json.Value]) (string, []contentmapper.SpanMapSegment, []contentmapper.Diagnostic, *contentmapper.DiagnosticDirectives, error) { var virtual strings.Builder var segments []spanmap.Segment var diagnostics []contentmapper.Diagnostic @@ -159,11 +159,7 @@ func transform(content string, options *collections.OrderedMap[string, json.Valu } spanMap := spanmap.New(segments) - mappings, err := spanMap.Marshal() - if err != nil { - return "", nil, nil, nil, err - } - return virtual.String(), json.Value(mappings), diagnostics, diagnosticDirectives(content, spanMap), nil + return virtual.String(), spanMap.Tuples(), diagnostics, diagnosticDirectives(content, spanMap), nil } func diagnosticDirectives(content string, mappings *spanmap.SpanMap) *contentmapper.DiagnosticDirectives { From 9ef4cdd598325fc4e62946571e5629529d0caf6d Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Thu, 19 Nov 2026 15:42:05 +0000 Subject: [PATCH 4/5] code review --- Herebyfile.mjs | 2 +- packages/typescript/package.json | 1 + .../schemas/contentmapper.schema.json | 4 ++-- tools/scripts/tsc/generate-contentmapper.ts | 19 ++++++++++++++----- .../contentmapper/protocol_generated.go | 2 +- 5 files changed, 19 insertions(+), 9 deletions(-) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 6c9dd00176fca..f83ca9f452435 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -2909,7 +2909,7 @@ async function testTypeScriptPackage(platforms) { packed[0].files.some(file => file.path === "dist/wasm/index.js"), "Main package is missing the WASM host entrypoint", ); - for (const name of ["tsconfig", "jsconfig"]) { + for (const name of ["tsconfig", "jsconfig", "contentmapper"]) { const schemaPath = `schemas/${name}.schema.json`; assert(packed[0].files.some(file => file.path === schemaPath), `Package is missing ${schemaPath}`); assert.deepEqual( diff --git a/packages/typescript/package.json b/packages/typescript/package.json index ac4b5207cbcf6..2a375beedce6f 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -40,6 +40,7 @@ "./package.json": "./package.json", "./schemas/tsconfig.schema.json": "./schemas/tsconfig.schema.json", "./schemas/jsconfig.schema.json": "./schemas/jsconfig.schema.json", + "./schemas/contentmapper.schema.json": "./schemas/contentmapper.schema.json", ".": "./lib/version.cjs", "./vscode": { "@typescript/source": "./src/vscode/extensionApi.ts", diff --git a/packages/typescript/schemas/contentmapper.schema.json b/packages/typescript/schemas/contentmapper.schema.json index f1752c38808d2..c66eb3c516e69 100644 --- a/packages/typescript/schemas/contentmapper.schema.json +++ b/packages/typescript/schemas/contentmapper.schema.json @@ -192,11 +192,11 @@ "description": "Extension determining the virtual source file's syntax." }, "mappings": { - "type": "array", + "type": ["array", "null"], "items": { "$ref": "#/definitions/SpanMapSegment" }, - "description": "Span map tuples in the selected position encoding. Absent or empty mappings describe fully synthesized output." + "description": "Span map tuples in the selected position encoding. Absent, null, or empty mappings describe fully synthesized output." }, "diagnosticDirectives": { "$ref": "#/definitions/DiagnosticDirectives" diff --git a/tools/scripts/tsc/generate-contentmapper.ts b/tools/scripts/tsc/generate-contentmapper.ts index 9a3d20ea183cb..7d2e6110bdbb8 100644 --- a/tools/scripts/tsc/generate-contentmapper.ts +++ b/tools/scripts/tsc/generate-contentmapper.ts @@ -16,7 +16,7 @@ import { interface Schema { $ref?: string; - type?: string; + type?: string | string[]; description?: string; properties?: Record; required?: string[]; @@ -194,10 +194,18 @@ function goName(name: string): string { return name[0].toUpperCase() + name.slice(1); } +function schemaType(schema: Schema): string | undefined { + const type = schema.type; + if (!Array.isArray(type)) return type; + assert(type.length === 2 && type.includes("array") && type.includes("null"), `Unsupported schema type: ${type.join(", ")}`); + return "array"; +} + function goType(schema: Schema, definitions: Record): string { if (schema.$ref) return referenceName(schema.$ref, definitions); - if (schema.anyOf || (!schema.type && !schema.allOf)) return "json.Value"; - switch (schema.type) { + const type = schemaType(schema); + if (schema.anyOf || (!type && !schema.allOf)) return "json.Value"; + switch (type) { case "string": return "string"; case "integer": @@ -206,7 +214,7 @@ function goType(schema: Schema, definitions: Record): string { assert(schema.items && !Array.isArray(schema.items), "Unsupported array items"); return `[]${goType(schema.items, definitions)}`; default: - throw new Error(`Unsupported schema type: ${schema.type}`); + throw new Error(`Unsupported schema type: ${type}`); } } @@ -224,7 +232,8 @@ function fieldDescription(name: string, schema: Schema, definitions: Record Date: Thu, 19 Nov 2026 16:23:25 +0000 Subject: [PATCH 5/5] CR: watch content mapper schema file --- Herebyfile.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index f83ca9f452435..4fd9348279da3 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -872,6 +872,7 @@ export const buildWatch = task({ "tools/gen-proto", "tools/gen-preferences", "tools/userPreferences.schema.json", + "packages/typescript/schemas/contentmapper.schema.json", "packages/typescript/src/api/async", "packages/typescript/test/async", "packages/vscode-typescript/src",