diff --git a/packages/typescript/schemas/contentmapper.schema.json b/packages/typescript/schemas/contentmapper.schema.json index c66eb3c516e69..91614d49a3599 100644 --- a/packages/typescript/schemas/contentmapper.schema.json +++ b/packages/typescript/schemas/contentmapper.schema.json @@ -410,51 +410,96 @@ "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.", "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." - }, + "description": "[originalStart, originalLength, virtualStart, virtualEnd, 0, ...diagnosticCodes] or [originalStart, originalLength, virtualStart, virtualEnd, 1, unusedExpectDirectiveIndex?].", + "oneOf": [ { - "$ref": "#/definitions/DiagnosticDirectivePolicy", - "title": "policy" + "type": "array", + "description": "Ignore directive suppressing TypeScript diagnostics in the virtual range. An invalid original range is ignored. When diagnostic codes are given, only matching diagnostics are suppressed.", + "items": [ + { + "type": "integer", + "title": "originalStart", + "description": "Original start offset." + }, + { + "type": "integer", + "title": "originalLength", + "description": "Original span length." + }, + { + "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." + }, + { + "type": "integer", + "const": 0, + "title": "policy", + "description": "Ignore directive policy." + } + ], + "additionalItems": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "title": "diagnosticCode", + "description": "TypeScript diagnostic code to ignore." + }, + "minItems": 5 }, { - "type": "integer", - "minimum": 0, - "title": "unusedExpectDirectiveIndex", - "description": "Index into unusedExpectDirectiveDiagnostics, used by expect directives." + "type": "array", + "description": "Expect directive suppressing TypeScript diagnostics in the virtual range. It requires a valid original range and reports an unused-expect diagnostic there when no diagnostic is suppressed.", + "items": [ + { + "type": "integer", + "title": "originalStart", + "minimum": 0, + "description": "Original start offset." + }, + { + "type": "integer", + "title": "originalLength", + "minimum": 0, + "description": "Original span length." + }, + { + "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." + }, + { + "type": "integer", + "const": 1, + "title": "policy", + "description": "Expect directive policy." + }, + { + "type": "integer", + "minimum": 0, + "title": "unusedExpectDirectiveIndex", + "description": "Index into unusedExpectDirectiveDiagnostics. An omitted index selects the only shared unused-expect diagnostic and requires exactly one such diagnostic." + } + ], + "minItems": 5, + "maxItems": 6 } - ], - "minItems": 5, - "maxItems": 6, - "if": { - "items": [{}, {}, {}, {}, { "const": 1 }] - }, - "then": { - "items": [{ "minimum": 0 }, { "minimum": 0 }] - } + ] }, "SupplementalOutput": { "$ref": "#/definitions/MappedOutput" diff --git a/packages/typescript/src/api/node/msgpack.ts b/packages/typescript/src/api/node/msgpack.ts index b5da5f0e1890b..89307d7700365 100644 --- a/packages/typescript/src/api/node/msgpack.ts +++ b/packages/typescript/src/api/node/msgpack.ts @@ -175,6 +175,106 @@ export class MsgpackReader { throw new Error(`Expected array header, got 0x${byte.toString(16)}`); } + skipValue(): void { + let remaining = 1; + while (remaining > 0) { + this.skipBytes(1); + const byte = this.buf[this.pos - 1]; + remaining--; + if (byte <= 0x7f || byte >= 0xe0 || byte === 0xc0 || byte === 0xc2 || byte === 0xc3) continue; + if ((byte & 0xe0) === 0xa0) { + this.skipBytes(byte & 0x1f); + } + else if ((byte & 0xf0) === 0x90) { + remaining += byte & 0x0f; + } + else if ((byte & 0xf0) === 0x80) { + remaining += (byte & 0x0f) * 2; + } + else { + switch (byte) { + case 0xcc: + case 0xd0: + this.skipBytes(1); + break; + case 0xcd: + case 0xd1: + case 0xd4: + this.skipBytes(2); + break; + case 0xce: + case 0xd2: + case 0xca: + this.skipBytes(4); + break; + case 0xcf: + case 0xd3: + case 0xcb: + this.skipBytes(8); + break; + case 0xd5: + this.skipBytes(3); + break; + case 0xd6: + this.skipBytes(5); + break; + case 0xd7: + this.skipBytes(9); + break; + case 0xd8: + this.skipBytes(17); + break; + case 0xc4: + case 0xd9: + this.skipBytes(this.readLength(1)); + break; + case 0xc5: + case 0xda: + this.skipBytes(this.readLength(2)); + break; + case 0xc6: + case 0xdb: + this.skipBytes(this.readLength(4)); + break; + case 0xc7: + this.skipBytes(this.readLength(1) + 1); + break; + case 0xc8: + this.skipBytes(this.readLength(2) + 1); + break; + case 0xc9: + this.skipBytes(this.readLength(4) + 1); + break; + case 0xdc: + remaining += this.readLength(2); + break; + case 0xdd: + remaining += this.readLength(4); + break; + case 0xde: + remaining += this.readLength(2) * 2; + break; + case 0xdf: + remaining += this.readLength(4) * 2; + break; + default: + throw new Error(`Invalid MessagePack prefix 0x${byte.toString(16)}`); + } + } + } + } + + private skipBytes(length: number): void { + if (length > this.buf.length - this.pos) throw new Error("Unexpected end of MessagePack data"); + this.pos += length; + } + + private readLength(bytes: 1 | 2 | 4): number { + const offset = this.pos; + this.skipBytes(bytes); + return bytes === 1 ? this.buf[offset] : bytes === 2 ? this.view.getUint16(offset, false) : this.view.getUint32(offset, false); + } + readUint(): number { const byte = this.buf[this.pos++]; if (byte <= 0x7f) return byte; diff --git a/packages/typescript/src/api/node/node.ts b/packages/typescript/src/api/node/node.ts index 77f2c9366fcd8..372440b915109 100644 --- a/packages/typescript/src/api/node/node.ts +++ b/packages/typescript/src/api/node/node.ts @@ -397,16 +397,24 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { const count = reader.readArrayHeader(); const directives = Array(count); for (let i = 0; i < count; i++) { - if (reader.readArrayHeader() !== 6) throw new Error("Invalid diagnostic directive"); + const tupleLength = reader.readArrayHeader(); + if (tupleLength < 7) throw new Error("Invalid diagnostic directive"); const originalStart = reader.readUint(); const originalLength = reader.readUint(); const virtualStart = reader.readUint(); const virtualLength = reader.readUint(); + const policy = reader.readUint(); + const unusedCode = reader.readUint(); + const codeCount = reader.readArrayHeader(); + const diagnosticCodes = Array(codeCount); + for (let j = 0; j < codeCount; j++) diagnosticCodes[j] = reader.readUint(); + for (let j = 7; j < tupleLength; j++) reader.skipValue(); directives[i] = { originalRange: { pos: originalStart, end: originalStart + originalLength }, virtualRange: { pos: virtualStart, end: virtualStart + virtualLength }, - policy: reader.readUint(), - unusedCode: reader.readUint(), + policy, + unusedCode, + diagnosticCodes, }; } return this._cachedDiagnosticDirectives = directives; diff --git a/packages/typescript/src/api/node/protocol.ts b/packages/typescript/src/api/node/protocol.ts index bf01e29560665..29bb072c5edf2 100644 --- a/packages/typescript/src/api/node/protocol.ts +++ b/packages/typescript/src/api/node/protocol.ts @@ -1,4 +1,4 @@ -export const PROTOCOL_VERSION = 9; +export const PROTOCOL_VERSION = 10; export const HEADER_OFFSET_METADATA = 0; export const HEADER_OFFSET_HASH_LO0 = 4; diff --git a/packages/typescript/src/ast/ast.ts b/packages/typescript/src/ast/ast.ts index 18867bd9e13c9..7f587085ef92f 100644 --- a/packages/typescript/src/ast/ast.ts +++ b/packages/typescript/src/ast/ast.ts @@ -176,6 +176,8 @@ export interface MappedDiagnosticDirective { readonly virtualRange: ReadonlyTextRange; readonly policy: DiagnosticDirectivePolicy; readonly unusedCode: number; + /** For ignore directives, an empty list selects all diagnostic codes. */ + readonly diagnosticCodes: readonly number[]; } export interface SourceFile extends Node { diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 582672974ff4f..d0a7f17f0539b 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -3111,7 +3111,7 @@ export const other: { value: string } = box;`, } }); - test("getSourceFile includes supplemental files without physical files", { + test("getSourceFile exposes mapped directives and supplemental files", { skip: process.env.TS_API_TEST_WASM ? "WASM cannot spawn external content mapper processes" : false, }, async t => { const directory = mkdtempSync(join(tmpdir(), "ts-project-membership-")); @@ -3127,6 +3127,10 @@ export const other: { value: string } = box;`, connection.onRequest("transform", ({ content }) => ({ text: "export {};", extension: ".ts", + diagnosticDirectives: { + unusedExpectDirectiveDiagnostics: [], + directives: [[0, 0, 0, 10, 0, 2353, 2322]], + }, supplemental: [{ text: content, extension: ".ts" }], })); connection.listen(); @@ -3153,6 +3157,16 @@ export const other: { value: string } = box;`, await using api = new API({ cwd: directory, runExternalCode: true }); const snapshot = await api.createSnapshot({ openProjects: [configFileName] }); const program = snapshot.getConfiguredProject(configFileName)!.program; + const mappedFileName = toRootedFilePath(join(directory, "app.box"), undefined); + const mappedFile = await program.getSourceFile(mappedFileName); + assert.ok(mappedFile); + assert.deepEqual(mappedFile.diagnosticDirectives, [{ + originalRange: { pos: 0, end: 0 }, + virtualRange: { pos: 0, end: 10 }, + policy: 0, + unusedCode: 0, + diagnosticCodes: [2353, 2322], + }]); const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), undefined); assert.equal(existsSync(supplementalFileName), false); assert.ok(await program.getSourceFile(supplementalFileName)); diff --git a/packages/typescript/test/encoder.test.ts b/packages/typescript/test/encoder.test.ts index 395024ab9a96d..062b406179abd 100644 --- a/packages/typescript/test/encoder.test.ts +++ b/packages/typescript/test/encoder.test.ts @@ -41,13 +41,16 @@ import { encodeSourceFile, uint8ArrayToBase64, } from "../src/api/node/encoder.ts"; +import { MsgpackWriter } from "../src/api/node/msgpack.ts"; import { RemoteNode, RemoteNodeList, RemoteSourceFile, } from "../src/api/node/node.ts"; import { + HEADER_OFFSET_EXTENDED_DATA, HEADER_OFFSET_NODES, + HEADER_OFFSET_STRUCTURED_DATA, HEADER_SIZE, NODE_LEN, NODE_OFFSET_DATA, @@ -116,6 +119,38 @@ describe("Encoder", { concurrency }, () => { assert.strictEqual(decoded.canonicalSourceFileName, undefined); }); + test("skips unknown trailing diagnostic directive fields", () => { + const writer = new MsgpackWriter(); + writer.writeArrayHeader(1); // one directive + writer.writeArrayHeader(8); // seven known fields plus one from a future protocol + for (const value of [0, 1, 2, 3, 0, 0]) writer.writeUint(value); // ranges [0, 1) and [2, 5), ignore policy, no unused code + writer.writeArrayHeader(1); // diagnostic codes + writer.writeUint(2322); + writer.writeBool(true); // unknown field + const directives = writer.finish(); + + // Splice the directives in as structured data, just before the node table. + const encoded = encodeSourceFile(makeSF("text", "/component.vue.ts", [])); + const nodesOffset = new DataView(encoded.buffer, encoded.byteOffset).getUint32(HEADER_OFFSET_NODES, true); + const withDirectives = new Uint8Array(encoded.length + directives.length); + withDirectives.set(encoded.subarray(0, nodesOffset)); + withDirectives.set(directives, nodesOffset); + withDirectives.set(encoded.subarray(nodesOffset), nodesOffset + directives.length); + const view = new DataView(withDirectives.buffer); + view.setUint32(HEADER_OFFSET_STRUCTURED_DATA, nodesOffset, true); + view.setUint32(HEADER_OFFSET_NODES, nodesOffset + directives.length, true); + // The source file's extended data points at the directives (offset 0 within structured data). + view.setUint32(view.getUint32(HEADER_OFFSET_EXTENDED_DATA, true) + 72, 0, true); + + assert.deepStrictEqual(decode(withDirectives).diagnosticDirectives, [{ + originalRange: { pos: 0, end: 1 }, + virtualRange: { pos: 2, end: 5 }, + policy: 0, + unusedCode: 0, + diagnosticCodes: [2322], + }]); + }); + test("keeps adjacent surrogate string-table entries separate", () => { const high = String.fromCharCode(0xD800); const low = String.fromCharCode(0xDC00); diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index caeabc14aa17e..a4aac92b6e421 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -2927,7 +2927,7 @@ export const other: { value: string } = box;`, } }); - test("getSourceFile includes supplemental files without physical files", { + test("getSourceFile exposes mapped directives and supplemental files", { skip: process.env.TS_API_TEST_WASM ? "WASM cannot spawn external content mapper processes" : false, }, t => { const directory = mkdtempSync(join(tmpdir(), "ts-project-membership-")); @@ -2943,6 +2943,10 @@ export const other: { value: string } = box;`, connection.onRequest("transform", ({ content }) => ({ text: "export {};", extension: ".ts", + diagnosticDirectives: { + unusedExpectDirectiveDiagnostics: [], + directives: [[0, 0, 0, 10, 0, 2353, 2322]], + }, supplemental: [{ text: content, extension: ".ts" }], })); connection.listen(); @@ -2969,6 +2973,16 @@ export const other: { value: string } = box;`, using api = new API({ cwd: directory, runExternalCode: true }); const snapshot = api.createSnapshot({ openProjects: [configFileName] }); const program = snapshot.getConfiguredProject(configFileName)!.program; + const mappedFileName = toRootedFilePath(join(directory, "app.box"), undefined); + const mappedFile = program.getSourceFile(mappedFileName); + assert.ok(mappedFile); + assert.deepEqual(mappedFile.diagnosticDirectives, [{ + originalRange: { pos: 0, end: 0 }, + virtualRange: { pos: 0, end: 10 }, + policy: 0, + unusedCode: 0, + diagnosticCodes: [2353, 2322], + }]); const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), undefined); assert.equal(existsSync(supplementalFileName), false); assert.ok(program.getSourceFile(supplementalFileName)); diff --git a/tools/scripts/tsc/generate-contentmapper.ts b/tools/scripts/tsc/generate-contentmapper.ts index 7d2e6110bdbb8..f0b5bdcc7a87c 100644 --- a/tools/scripts/tsc/generate-contentmapper.ts +++ b/tools/scripts/tsc/generate-contentmapper.ts @@ -21,6 +21,7 @@ interface Schema { properties?: Record; required?: string[]; items?: Schema | Schema[]; + additionalItems?: Schema | boolean; anyOf?: Schema[]; oneOf?: Schema[]; allOf?: Schema[]; @@ -237,10 +238,62 @@ function fieldDescription(name: string, schema: Schema, definitions: Record(); + for (const variant of schema.oneOf) { + const items = variant.items; + if (!Array.isArray(items)) throw new Error("Unsupported MappedDiagnosticDirective policy variant"); + assert( + variant.type === "array" && items.length >= 5 + && variant.minItems === 5 && items[4].title === "policy" + && (items[4].const === 0 || items[4].const === 1), + "Unsupported MappedDiagnosticDirective policy variant", + ); + assert(!variants.has(items[4].const), "Duplicate MappedDiagnosticDirective policy variant"); + variants.set(items[4].const, variant); + } + const ignore = variants.get(0); + const expect = variants.get(1); + assert(ignore && expect, "MappedDiagnosticDirective must define ignore and expect variants"); + assert( + typeof ignore.additionalItems === "object" && ignore.additionalItems.type === "integer" + && ignore.additionalItems.minimum === 1 && ignore.additionalItems.maximum === 2147483647 + && ignore.maxItems === undefined, + "Unsupported MappedDiagnosticDirective ignore variant", + ); + const expectItems = expect.items; + const expectMaxItems = expect.maxItems; + if (!Array.isArray(expectItems)) throw new Error("Unsupported MappedDiagnosticDirective expect variant"); + assert( + expectItems.length === 6 && expectItems[5].title === "unusedExpectDirectiveIndex" + && expectItems[5].type === "integer" && expectItems[5].minimum === 0 + && expectMaxItems === 6, + "Unsupported MappedDiagnosticDirective expect variant", + ); + for (const variant of [ignore, expect]) { + const items = variant.items; + assert(Array.isArray(items), "Unsupported MappedDiagnosticDirective tuple items"); + assert( + items.slice(0, 4).every((item, index) => + item.title === ["originalStart", "originalLength", "virtualStart", "virtualEnd"][index] + && item.type === "integer" + && item.description === expectItems[index].description + ), + "MappedDiagnosticDirective policy variants must share range fields", + ); + assert(variant.description, "Missing MappedDiagnosticDirective policy variant description"); + } + return { ignore, expect, expectMaxItems }; +} + 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)}`}`; + return commentLines(`${name} ${normalized.startsWith("[") ? `is encoded as ${normalized}` : `describes ${nounPhrase(normalized)}`}`); +} + +function commentLines(description: string): string[] { const lines: string[] = []; let line = "//"; for (const word of description.split(" ")) { @@ -343,68 +396,105 @@ export function generateContentMapper(document: SchemaDocument): string { 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") { - 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!)); - 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()) { - 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( - "}", - "", - "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 if (name === "MappedDiagnosticDirective" && schema.oneOf) { + const { ignore, expect, expectMaxItems } = mappedDiagnosticDirectiveVariants(schema); + assert(schema.title, "Missing MappedDiagnosticDirective title"); + const ignoreItems = ignore.items as Schema[]; + const expectItems = expect.items as Schema[]; + const policyNames = enumNames.DiagnosticDirectivePolicy; + const ignorePolicy = `DiagnosticDirectivePolicy${policyNames[String(ignoreItems[4].const)]}`; + const expectPolicy = `DiagnosticDirectivePolicy${policyNames[String(expectItems[4].const)]}`; + const fields = expectItems.slice(0, 4); + assert( + fields.every((field, index) => field.title === ["originalStart", "originalLength", "virtualStart", "virtualEnd"][index]), + "Unsupported MappedDiagnosticDirective fields", + ); + for (const [policy, variant] of [[ignorePolicy, ignore], [expectPolicy, expect]] as const) { + const description = variant.description!.trim().replace(/\s+/g, " "); + lines.push("//", ...commentLines(`${policy} encodes ${/^[aeiou]/i.test(description) ? "an" : "a"} ${nounPhrase(description).replace(/^the /, "")}`)); } - else { - throw new Error(`Unsupported ${name} tuple`); + lines.push("type MappedDiagnosticDirective struct {"); + for (const field of fields) { + const name = goName(field.title!); + lines.push(...fieldDescription(name, field, definitions).map(line => `\t${line}`)); + lines.push(`\t${name} ${goType(field, definitions)}`); } + lines.push( + "\t// Policy is the diagnostic directive policy: 0 ignores diagnostics; 1 expects a diagnostic.", + "\tPolicy DiagnosticDirectivePolicy", + "\t// UnusedExpectDirectiveIndex selects the unused diagnostic for an expect directive.", + "\tUnusedExpectDirectiveIndex *int", + "\t// DiagnosticCodes selects TypeScript diagnostic codes for an ignore directive; empty selects all codes.", + "\tDiagnosticCodes []int32", + "}", + "", + "var (", + "\t_ json.MarshalerTo = MappedDiagnosticDirective{}", + "\t_ json.UnmarshalerFrom = (*MappedDiagnosticDirective)(nil)", + ")", + "", + "func (d MappedDiagnosticDirective) MarshalJSONTo(enc *json.Encoder) error {", + "\ttuple := []any{d.OriginalStart, d.OriginalLength, d.VirtualStart, d.VirtualEnd, d.Policy}", + `\tswitch d.Policy {`, + `\tcase ${ignorePolicy}:`, + "\t\tfor _, code := range d.DiagnosticCodes {", + "\t\t\ttuple = append(tuple, code)", + "\t\t}", + `\tcase ${expectPolicy}:`, + "\t\tif d.UnusedExpectDirectiveIndex != nil {", + "\t\t\ttuple = append(tuple, *d.UnusedExpectDirectiveIndex)", + "\t\t}", + "\t}", + "\treturn json.MarshalEncode(enc, tuple)", + "}", + "", + "func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error {", + "\tvar tuple []json.Value", + "\tif err := json.UnmarshalDecode(dec, &tuple); err != nil {", + "\t\treturn err", + "\t}", + `\tif len(tuple) < ${ignore.minItems} {`, + `\t\treturn fmt.Errorf("diagnostic directive tuple must contain at least ${ignore.minItems} elements, got %d", len(tuple))`, + "\t}", + "\t*d = MappedDiagnosticDirective{}", + "\tfields := []any{&d.OriginalStart, &d.OriginalLength, &d.VirtualStart, &d.VirtualEnd, &d.Policy}", + "\tfor i, field := range fields {", + "\t\tif err := json.Unmarshal(tuple[i], field); err != nil {", + '\t\t\treturn fmt.Errorf("invalid diagnostic directive tuple element %d: %w", i, err)', + "\t\t}", + "\t}", + "\tswitch d.Policy {", + `\tcase ${ignorePolicy}:`, + `\t\tif len(tuple) > ${ignore.minItems} {`, + `\t\t\td.DiagnosticCodes = make([]int32, len(tuple)-${ignore.minItems})`, + "\t\t\tfor i := range d.DiagnosticCodes {", + `\t\t\t\tif err := json.Unmarshal(tuple[i+${ignore.minItems}], &d.DiagnosticCodes[i]); err != nil {`, + `\t\t\t\t\treturn fmt.Errorf("invalid diagnostic directive tuple element %d: %w", i+${ignore.minItems}, err)`, + "\t\t\t\t}", + "\t\t\t}", + "\t\t}", + `\tcase ${expectPolicy}:`, + `\t\tif len(tuple) > ${expectMaxItems} {`, + `\t\t\treturn fmt.Errorf("expect diagnostic directive tuple must contain at most ${expectMaxItems} elements, got %d", len(tuple))`, + "\t\t}", + `\t\tif len(tuple) == ${expectMaxItems} {`, + "\t\t\td.UnusedExpectDirectiveIndex = new(int)", + `\t\t\tif err := json.Unmarshal(tuple[${expectMaxItems - 1}], d.UnusedExpectDirectiveIndex); err != nil {`, + `\t\t\t\treturn fmt.Errorf("invalid diagnostic directive tuple element ${expectMaxItems - 1}: %w", err)`, + "\t\t\t}", + "\t\t}", + "\tdefault:", + "\t\tif len(tuple) > 5 {", + '\t\t\treturn fmt.Errorf("invalid diagnostic directive policy %d with additional tuple elements", d.Policy)', + "\t\t}", + "\t}", + "\treturn nil", + "}", + ); + } + else if (name === "SpanMapSegment") { + spanMapTuple(document); + lines.push(`type ${name} = spanmap.SegmentTuple`); } else { throw new Error(`Unsupported definition: ${name}`); diff --git a/tsc/internal/api/encoder/encoder.go b/tsc/internal/api/encoder/encoder.go index 39367ebc9fae8..a1a7d922a6d7f 100644 --- a/tsc/internal/api/encoder/encoder.go +++ b/tsc/internal/api/encoder/encoder.go @@ -68,7 +68,7 @@ const ( ) const ( - ProtocolVersion uint8 = 9 + ProtocolVersion uint8 = 10 ) // Source File Binary Format @@ -183,7 +183,7 @@ const ( // // Diagnostic directives are msgpack arrays of normalized tuples in UTF-16 coordinates: // -// [originalStart: uint, originalLength: uint, virtualStart: uint, virtualLength: uint, policy: uint, unusedCode: uint] +// [originalStart: uint, originalLength: uint, virtualStart: uint, virtualLength: uint, policy: uint, unusedCode: uint, diagnosticCodes: uint[]] // // An offset of 0xFFFFFFFF indicates no data (empty array). // @@ -850,7 +850,7 @@ func encodeDiagnosticDirectives(directives []ast.MappedDiagnosticDirective, virt offset := uint32(len(*buf)) *buf = msgpackWriteArrayHeader(*buf, len(directives)) for _, directive := range directives { - *buf = msgpackWriteArrayHeader(*buf, 6) + *buf = msgpackWriteArrayHeader(*buf, 7) originalStart := originalPositions.UTF8ToUTF16(directive.OriginalRange.Pos()) originalEnd := originalPositions.UTF8ToUTF16(directive.OriginalRange.End()) virtualStart := virtualPositions.UTF8ToUTF16(directive.VirtualRange.Pos()) @@ -861,6 +861,10 @@ func encodeDiagnosticDirectives(directives []ast.MappedDiagnosticDirective, virt *buf = msgpackWriteUint(*buf, uint32(virtualEnd-virtualStart)) *buf = msgpackWriteUint(*buf, uint32(directive.Policy)) *buf = msgpackWriteUint(*buf, uint32(directive.UnusedCode)) + *buf = msgpackWriteArrayHeader(*buf, len(directive.DiagnosticCodes)) + for _, code := range directive.DiagnosticCodes { + *buf = msgpackWriteUint(*buf, uint32(code)) + } } return offset } diff --git a/tsc/internal/api/encoder/encoder_test.go b/tsc/internal/api/encoder/encoder_test.go index 2652a44212051..1e97b88feba80 100644 --- a/tsc/internal/api/encoder/encoder_test.go +++ b/tsc/internal/api/encoder/encoder_test.go @@ -39,8 +39,8 @@ func TestEncodeSourceFile(t *testing.T) { func TestEncodeContentMapperSourceFileMetadata(t *testing.T) { t.Parallel() - if encoder.ProtocolVersion != 9 { - t.Fatalf("protocol version = %d, want 9", encoder.ProtocolVersion) + if encoder.ProtocolVersion != 10 { + t.Fatalf("protocol version = %d, want 10", encoder.ProtocolVersion) } sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{ FileName: "/component.vue", @@ -75,13 +75,14 @@ func TestEncodeContentMapperSourceFileMetadata(t *testing.T) { assert.Equal(t, encodedString(buf, virtualFileNameIndex), "/component.vue.ts") structuredDataOffset := readUint32(buf, encoder.HeaderOffsetStructuredData) directiveOffset := structuredDataOffset + diagnosticDirectivesOffset - assert.DeepEqual(t, buf[directiveOffset:directiveOffset+10], []byte{ + assert.DeepEqual(t, buf[directiveOffset:directiveOffset+11], []byte{ 0x91, // one directive - 0x96, // six-element tuple + 0x97, // seven-element tuple 2, 1, // original range [2, 3) in UTF-16 2, 7, // virtual range [2, 9) in UTF-16 1, // expect policy 0xcd, 10, 18, // unused diagnostic code 2578 + 0x90, // no diagnostic codes }) } diff --git a/tsc/internal/ast/ast.go b/tsc/internal/ast/ast.go index 2b1cff046e6d9..fa18cde63bace 100644 --- a/tsc/internal/ast/ast.go +++ b/tsc/internal/ast/ast.go @@ -2543,10 +2543,12 @@ const ( ) type MappedDiagnosticDirective struct { - OriginalRange core.TextRange - VirtualRange core.TextRange - Policy MappedDiagnosticDirectivePolicy - UnusedCode int32 + OriginalRange core.TextRange + VirtualRange core.TextRange + Policy MappedDiagnosticDirectivePolicy + UnusedCode int32 + // DiagnosticCodes restricts an ignore directive; an empty slice matches all codes. + DiagnosticCodes []int32 UnusedMessageText string Source string } diff --git a/tsc/internal/compiler/fileloader.go b/tsc/internal/compiler/fileloader.go index 901ecd67b0ef5..d586c3a7e423f 100644 --- a/tsc/internal/compiler/fileloader.go +++ b/tsc/internal/compiler/fileloader.go @@ -516,6 +516,8 @@ func contentMapperTransformDiagnostic(file *ast.SourceFile, label string, err er detail = ast.NewCompilerDiagnostic(diagnostics.Diagnostic_directive_0_returned_by_the_content_mapper_must_specify_unusedExpectDirectiveIndex_when_there_is_not_exactly_one_unusedExpectDirectiveDiagnostics_entry, directiveError.Index) case contentmapper.DiagnosticDirectiveErrorKindInvalidUnusedDiagnosticIndex: detail = ast.NewCompilerDiagnostic(diagnostics.Diagnostic_directive_0_returned_by_the_content_mapper_has_an_invalid_unusedExpectDirectiveIndex, directiveError.Index) + case contentmapper.DiagnosticDirectiveErrorKindInvalidDiagnosticCode: + detail = ast.NewCompilerDiagnostic(diagnostics.Diagnostic_directive_0_returned_by_the_content_mapper_has_a_diagnostic_code_selector_that_must_be_positive, directiveError.Index) case contentmapper.DiagnosticDirectiveErrorKindOverlap: detail = ast.NewCompilerDiagnostic(diagnostics.The_content_mapper_returned_diagnostic_directives_with_overlapping_virtual_ranges) } diff --git a/tsc/internal/compiler/program.go b/tsc/internal/compiler/program.go index 30dc482904816..1bb52de223a00 100644 --- a/tsc/internal/compiler/program.go +++ b/tsc/internal/compiler/program.go @@ -1747,7 +1747,8 @@ func applyContentMapperDiagnosticDirectives(sourceFile *ast.SourceFile, diags [] return false } for i, directive := range directives { - if diag.Pos() >= directive.VirtualRange.Pos() && diag.Pos() < directive.VirtualRange.End() { + if diag.Pos() >= directive.VirtualRange.Pos() && diag.Pos() < directive.VirtualRange.End() && + (len(directive.DiagnosticCodes) == 0 || slices.Contains(directive.DiagnosticCodes, diag.Code())) { used[i] = true return true } diff --git a/tsc/internal/contentmapper/host.go b/tsc/internal/contentmapper/host.go index 36875da96e65b..75fc592f766b4 100644 --- a/tsc/internal/contentmapper/host.go +++ b/tsc/internal/contentmapper/host.go @@ -49,6 +49,7 @@ const ( DiagnosticDirectiveErrorKindExpectMissingUnusedDiagnostic DiagnosticDirectiveErrorKindInvalidUnusedDiagnosticIndex DiagnosticDirectiveErrorKindOverlap + DiagnosticDirectiveErrorKindInvalidDiagnosticCode ) // DiagnosticDirectiveError reports an invalid diagnostic directive in a transform response. diff --git a/tsc/internal/contentmapper/host_test.go b/tsc/internal/contentmapper/host_test.go index b119279eb1c8e..85e7463ac9e50 100644 --- a/tsc/internal/contentmapper/host_test.go +++ b/tsc/internal/contentmapper/host_test.go @@ -656,7 +656,7 @@ func TestMappedDiagnosticDirectiveJSON(t *testing.T) { for _, data := range []string{ `[0,0,0,0]`, - `[0,0,0,0,0,1,2]`, + `[0,0,0,0,1,1,2]`, } { var directive contentmapper.MappedDiagnosticDirective assert.ErrorContains(t, json.Unmarshal([]byte(data), &directive), "diagnostic directive tuple") diff --git a/tsc/internal/contentmapper/hostimpl.go b/tsc/internal/contentmapper/hostimpl.go index 69efdbe552298..7e7631c3bcf65 100644 --- a/tsc/internal/contentmapper/hostimpl.go +++ b/tsc/internal/contentmapper/hostimpl.go @@ -1042,7 +1042,13 @@ func normalizeDiagnosticDirectives(diagnosticDirectives *DiagnosticDirectives, v normalized := ast.MappedDiagnosticDirective{Source: diagnosticSource} switch directive.Policy { case DiagnosticDirectivePolicyIgnore: + for _, code := range directive.DiagnosticCodes { + if code <= 0 { + return nil, directiveError(DiagnosticDirectiveErrorKindInvalidDiagnosticCode) + } + } normalized.Policy = ast.MappedDiagnosticDirectivePolicyIgnore + normalized.DiagnosticCodes = directive.DiagnosticCodes case DiagnosticDirectivePolicyExpect: unusedDiagnosticIndex := 0 if directive.UnusedExpectDirectiveIndex != nil { diff --git a/tsc/internal/contentmapper/protocol_generated.go b/tsc/internal/contentmapper/protocol_generated.go index c3b5fde918910..1b06dcbdc09ba 100644 --- a/tsc/internal/contentmapper/protocol_generated.go +++ b/tsc/internal/contentmapper/protocol_generated.go @@ -124,13 +124,18 @@ type DiagnosticDirectives struct { 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. +// MappedDiagnosticDirective is encoded as [originalStart, originalLength, virtualStart, virtualEnd, 0, +// ...diagnosticCodes] or [originalStart, originalLength, virtualStart, virtualEnd, 1, unusedExpectDirectiveIndex?]. +// +// DiagnosticDirectivePolicyIgnore encodes an ignore directive suppressing TypeScript diagnostics in the virtual range. +// An invalid original range is ignored. When diagnostic codes are given, only matching diagnostics are suppressed. +// +// DiagnosticDirectivePolicyExpect encodes an expect directive suppressing TypeScript diagnostics in the virtual range. +// It requires a valid original range and reports an unused-expect diagnostic there when no diagnostic is suppressed. type MappedDiagnosticDirective struct { - // OriginalStart is the original start offset. It is ignored for ignore directives if the original range is invalid. + // OriginalStart is the original start offset. OriginalStart int - // OriginalLength is the original span length. It is ignored for ignore directives if the original range is invalid. + // OriginalLength is the original span length. OriginalLength int // VirtualStart is the inclusive virtual start offset. VirtualStart int @@ -138,8 +143,10 @@ type MappedDiagnosticDirective struct { 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 selects the unused diagnostic for an expect directive. UnusedExpectDirectiveIndex *int + // DiagnosticCodes selects TypeScript diagnostic codes for an ignore directive; empty selects all codes. + DiagnosticCodes []int32 } var ( @@ -149,8 +156,15 @@ var ( 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) + switch d.Policy { + case DiagnosticDirectivePolicyIgnore: + for _, code := range d.DiagnosticCodes { + tuple = append(tuple, code) + } + case DiagnosticDirectivePolicyExpect: + if d.UnusedExpectDirectiveIndex != nil { + tuple = append(tuple, *d.UnusedExpectDirectiveIndex) + } } return json.MarshalEncode(enc, tuple) } @@ -160,8 +174,8 @@ func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error { 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)) + if len(tuple) < 5 { + return fmt.Errorf("diagnostic directive tuple must contain at least 5 elements, got %d", len(tuple)) } *d = MappedDiagnosticDirective{} fields := []any{&d.OriginalStart, &d.OriginalLength, &d.VirtualStart, &d.VirtualEnd, &d.Policy} @@ -170,10 +184,29 @@ func (d *MappedDiagnosticDirective) UnmarshalJSONFrom(dec *json.Decoder) error { 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) + switch d.Policy { + case DiagnosticDirectivePolicyIgnore: + if len(tuple) > 5 { + d.DiagnosticCodes = make([]int32, len(tuple)-5) + for i := range d.DiagnosticCodes { + if err := json.Unmarshal(tuple[i+5], &d.DiagnosticCodes[i]); err != nil { + return fmt.Errorf("invalid diagnostic directive tuple element %d: %w", i+5, err) + } + } + } + case DiagnosticDirectivePolicyExpect: + if len(tuple) > 6 { + return fmt.Errorf("expect diagnostic directive tuple must contain at most 6 elements, got %d", len(tuple)) + } + 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) + } + } + default: + if len(tuple) > 5 { + return fmt.Errorf("invalid diagnostic directive policy %d with additional tuple elements", d.Policy) } } return nil diff --git a/tsc/internal/diagnostics/diagnosticMessages.generated.json b/tsc/internal/diagnostics/diagnosticMessages.generated.json index e4fde50233eba..1d15592c866b2 100644 --- a/tsc/internal/diagnostics/diagnosticMessages.generated.json +++ b/tsc/internal/diagnostics/diagnosticMessages.generated.json @@ -1976,6 +1976,7 @@ "This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s__18139": "This relative import path is unsafe to rewrite because it appears not to match the content mapper's 'include', but does after resolution with 'rootDirs' and 'moduleSuffixes'.", "File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_content_mapper_s_include_18140": "File '{0}' has a registered content mapper extension but does not match any content mapper's 'include'.", "Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest_18141": "Content mapper '{0}' must specify 'extensions' in tsconfig or its package manifest.", + "Diagnostic_directive_0_returned_by_the_content_mapper_has_a_diagnostic_code_selector_that_must_be_po_18142": "Diagnostic directive {0} returned by the content mapper has a diagnostic code selector that must be positive.", "nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010": "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`.", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "File is a CommonJS module; it may be converted to an ES module.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "This constructor function may be converted to a class declaration.", diff --git a/tsc/internal/diagnostics/diagnosticMessages.json b/tsc/internal/diagnostics/diagnosticMessages.json index ce11be7a85936..dfded39493642 100644 --- a/tsc/internal/diagnostics/diagnosticMessages.json +++ b/tsc/internal/diagnostics/diagnosticMessages.json @@ -8972,6 +8972,10 @@ "category": "Error", "code": 18141 }, + "Diagnostic directive {0} returned by the content mapper has a diagnostic code selector that must be positive.": { + "category": "Message", + "code": 18142 + }, "Content mapper '{0}' is also registered for the extension '{1}', but has a conflicting 'outputExtensions' mapping. Each registration for this extension must produce the same output file name.": { "category": "Error", "code": 18127 diff --git a/tsc/internal/diagnostics/diagnostics_generated.go b/tsc/internal/diagnostics/diagnostics_generated.go index 274c98c35703a..85dbd72f3bea7 100644 --- a/tsc/internal/diagnostics/diagnostics_generated.go +++ b/tsc/internal/diagnostics/diagnostics_generated.go @@ -3956,6 +3956,8 @@ var File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_cont var Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest = &Message{code: 18141, category: CategoryError, key: "Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest_18141", text: "Content mapper '{0}' must specify 'extensions' in tsconfig or its package manifest."} +var Diagnostic_directive_0_returned_by_the_content_mapper_has_a_diagnostic_code_selector_that_must_be_positive = &Message{code: 18142, category: CategoryMessage, key: "Diagnostic_directive_0_returned_by_the_content_mapper_has_a_diagnostic_code_selector_that_must_be_po_18142", text: "Diagnostic directive {0} returned by the content mapper has a diagnostic code selector that must be positive."} + var X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler = &Message{code: 69010, category: CategoryMessage, key: "nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010", text: "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`."} var File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module = &Message{code: 80001, category: CategorySuggestion, key: "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", text: "File is a CommonJS module; it may be converted to an ES module."} @@ -6474,6 +6476,7 @@ var allMessages = [...]**Message{ &This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s_include_but_does_after_resolution_with_rootDirs_and_moduleSuffixes, &File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_content_mapper_s_include, &Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest, + &Diagnostic_directive_0_returned_by_the_content_mapper_has_a_diagnostic_code_selector_that_must_be_positive, &X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler, &File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module, &This_constructor_function_may_be_converted_to_a_class_declaration, diff --git a/tsc/internal/testutil/contentmappertest/transforming.go b/tsc/internal/testutil/contentmappertest/transforming.go index f9f4da0bf089d..b7a66776c047d 100644 --- a/tsc/internal/testutil/contentmappertest/transforming.go +++ b/tsc/internal/testutil/contentmappertest/transforming.go @@ -3,6 +3,7 @@ package contentmappertest import ( "context" "fmt" + "strconv" "strings" "sync" @@ -187,6 +188,8 @@ func diagnosticDirectives(content string, mappings *spanmap.SpanMap) *contentmap []contentmapper.MappedDiagnosticDirective{{Policy: contentmapper.DiagnosticDirectivePolicyExpect, UnusedExpectDirectiveIndex: &index}}, contentmapper.UnusedExpectDirectiveDiagnostic{}, ) + case "invalid-diagnostic-code": + return wrap([]contentmapper.MappedDiagnosticDirective{{Policy: contentmapper.DiagnosticDirectivePolicyIgnore, DiagnosticCodes: []int32{0}}}) case "overlap": return wrap([]contentmapper.MappedDiagnosticDirective{ {VirtualEnd: 2, Policy: contentmapper.DiagnosticDirectivePolicyIgnore}, @@ -210,10 +213,18 @@ func diagnosticDirectives(content string, mappings *spanmap.SpanMap) *contentmap var policy contentmapper.DiagnosticDirectivePolicy hasPolicy := false unusedDiagnosticIndex := -1 + var diagnosticCodes []int32 switch { - case trimmed == ignorePrefix: + case trimmed == ignorePrefix || strings.HasPrefix(trimmed, ignorePrefix+" "): policy = contentmapper.DiagnosticDirectivePolicyIgnore hasPolicy = true + for field := range strings.FieldsSeq(strings.TrimPrefix(trimmed, ignorePrefix)) { + code, err := strconv.ParseInt(field, 10, 32) + if err != nil { + panic(err) + } + diagnosticCodes = append(diagnosticCodes, int32(code)) + } case strings.HasPrefix(trimmed, expectPrefix+":"): policy = contentmapper.DiagnosticDirectivePolicyExpect hasPolicy = true @@ -232,11 +243,12 @@ func diagnosticDirectives(content string, mappings *spanmap.SpanMap) *contentmap virtualSpans := mappings.OriginalToVirtualSpans(core.NewTextRange(affectedStart, affectedStart+affectedLength), spanmap.FeatureAll) if len(virtualSpans) == 1 { directive := contentmapper.MappedDiagnosticDirective{ - OriginalStart: lineStart, - OriginalLength: lineEnd - lineStart, - VirtualStart: virtualSpans[0].Span.Pos(), - VirtualEnd: virtualSpans[0].Span.End(), - Policy: policy, + OriginalStart: lineStart, + OriginalLength: lineEnd - lineStart, + VirtualStart: virtualSpans[0].Span.Pos(), + VirtualEnd: virtualSpans[0].Span.End(), + Policy: policy, + DiagnosticCodes: diagnosticCodes, } if unusedDiagnosticIndex >= 0 { directive.UnusedExpectDirectiveIndex = &unusedDiagnosticIndex diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperDiagnosticDirectiveCodes.contentmapper b/tsc/testdata/baselines/reference/compiler/contentMapperDiagnosticDirectiveCodes.contentmapper new file mode 100644 index 0000000000000..8cabac47981e7 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/contentMapperDiagnosticDirectiveCodes.contentmapper @@ -0,0 +1,21 @@ +//// [/widget.box] (ScriptKind: ScriptKindTS, ContentMapper: [.box]) +--- Original --- +// @box-ignore 2304 +const one: number = [missingName]; + +// @box-ignore 2304 2322 +const both: number = [missingName]; +--- Transformed --- +const __VERSION = "1.0.0"; +// @box-ignore 2304 +const one: number = [missingName]; + +// @box-ignore 2304 2322 +const both: number = [missingName]; + +=== Diagnostics === + +/widget.box:2:7 - error TS2322: Type 'any[]' is not assignable to type 'number'. + +2 const one: number = [missingName]; + ~~~ diff --git a/tsc/testdata/baselines/reference/compiler/contentMapperInvalidDiagnosticDirectives.contentmapper b/tsc/testdata/baselines/reference/compiler/contentMapperInvalidDiagnosticDirectives.contentmapper index 180f687f380ae..469f23a3624f1 100644 --- a/tsc/testdata/baselines/reference/compiler/contentMapperInvalidDiagnosticDirectives.contentmapper +++ b/tsc/testdata/baselines/reference/compiler/contentMapperInvalidDiagnosticDirectives.contentmapper @@ -23,6 +23,11 @@ // @box-invalid-directive: overlap --- Transformed --- +//// [/invalidDiagnosticCode.invalidcode] (ScriptKind: ScriptKindTS, ContentMapper: [.invalidcode]) +--- Original --- +// @box-invalid-directive: invalid-diagnostic-code +--- Transformed --- + === Diagnostics === /expectWithoutUnusedDiagnostic.expectmissing:1:1 - error TS18069: The content mapper 'mapper' failed to transform this file. @@ -31,6 +36,12 @@ 1 ~ +/invalidDiagnosticCode.invalidcode:1:1 - error TS18069: The content mapper 'mapper' failed to transform this file. + Diagnostic directive 0 returned by the content mapper has a diagnostic code selector that must be positive. + +1 + ~ + /invalidPolicy.invalidpolicy:1:1 - error TS18069: The content mapper 'mapper' failed to transform this file. The content mapper returned a diagnostic directive with invalid policy '2'. diff --git a/tsc/testdata/tests/cases/compiler/contentMapperDiagnosticDirectiveCodes.ts b/tsc/testdata/tests/cases/compiler/contentMapperDiagnosticDirectiveCodes.ts new file mode 100644 index 0000000000000..c5d9261f9d7e7 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/contentMapperDiagnosticDirectiveCodes.ts @@ -0,0 +1,29 @@ +// @runExternalCode: true +// @noTypesAndSymbols: true + +// @Filename: /tsconfig.json +{ + "compilerOptions": { + "target": "es2020", + "module": "esnext", + "moduleResolution": "bundler", + "strict": true + }, + "contentMappers": [ + { "package": "mapper", "extensions": [".box"] } + ] +} + +// @Filename: /node_modules/mapper/package.json +{ + "name": "mapper", + "version": "1.0.0", + "typescript": { "contentMapper": { "exec": ["compiler-test-mapper"], "compilerOptions": ["target", "jsx"] } } +} + +// @Filename: /widget.box +// @box-ignore 2304 +const one: number = [missingName]; + +// @box-ignore 2304 2322 +const both: number = [missingName]; diff --git a/tsc/testdata/tests/cases/compiler/contentMapperInvalidDiagnosticDirectives.ts b/tsc/testdata/tests/cases/compiler/contentMapperInvalidDiagnosticDirectives.ts index a32c1023f36ca..84ab3add31a03 100644 --- a/tsc/testdata/tests/cases/compiler/contentMapperInvalidDiagnosticDirectives.ts +++ b/tsc/testdata/tests/cases/compiler/contentMapperInvalidDiagnosticDirectives.ts @@ -14,7 +14,8 @@ { "package": "mapper", "extensions": [".invalidpolicy"] }, { "package": "mapper", "extensions": [".expectmissing"] }, { "package": "mapper", "extensions": [".invalidunusedindex"] }, - { "package": "mapper", "extensions": [".overlap"] } + { "package": "mapper", "extensions": [".overlap"] }, + { "package": "mapper", "extensions": [".invalidcode"] } ] } @@ -41,4 +42,7 @@ // @box-invalid-directive: invalid-unused-diagnostic-index // @Filename: /overlap.overlap -// @box-invalid-directive: overlap \ No newline at end of file +// @box-invalid-directive: overlap + +// @Filename: /invalidDiagnosticCode.invalidcode +// @box-invalid-directive: invalid-diagnostic-code \ No newline at end of file