diff --git a/language-server/src/evaluation/Annotation.ts b/language-server/src/evaluation/Annotation.ts index 3bd18f51..781fef06 100644 --- a/language-server/src/evaluation/Annotation.ts +++ b/language-server/src/evaluation/Annotation.ts @@ -28,15 +28,27 @@ export class BaseAnnotation { // uses this to ignore values that aren't valid against that keyword's schema. // Undefined if the keyword isn't present or its value isn't valid. protected unknownKeyword(keyword: string, schemaUri: string, ast: AST) { - const value = this.keywords[`https://json-schema.org/keyword/unknown#${keyword}`] as Json | undefined; - if (value !== undefined && !interpret({ schemaUri, ast }, Instance.fromJs(value)).valid) { - return; + let validated = validatedUnknownKeywords.get(this.keywords); + if (!validated) { + validated = new Map(); + validatedUnknownKeywords.set(this.keywords, validated); } - return value; + if (!validated.has(keyword)) { + const value = this.keywords[`https://json-schema.org/keyword/unknown#${keyword}`] as Json | undefined; + const isValid = value === undefined || interpret({ schemaUri, ast }, Instance.fromJs(value)).valid; + validated.set(keyword, isValid ? value : undefined); + } + + return validated.get(keyword); } } +// An accessor can be called for every completion at a location, and +// Annotation objects are created every time annotations are read, so the +// validated value of an unknown keyword is kept per record +const validatedUnknownKeywords = new WeakMap>(); + // The annotations one schema contributed to an instance location, with the // accessors of every vocabulary. A vocabulary's mixin overrides the accessors of // the ones it's applied to, so their order matters. diff --git a/language-server/src/evaluation/JsonValueSet.test.ts b/language-server/src/evaluation/JsonValueSet.test.ts index f218c646..fc683dd3 100644 --- a/language-server/src/evaluation/JsonValueSet.test.ts +++ b/language-server/src/evaluation/JsonValueSet.test.ts @@ -27,6 +27,15 @@ describe("JsonValueSet annotations", () => { expect(annotationsOf(set, "red")).toEqual([a]); }); + test("getAnnotations includes a location annotation that's also a member annotation once", () => { + const set = values("red") + .annotate(a) + .intersect(alternative(values("red"), a)) + .intersect(alternative(values("red"), b)); + + expect(set.getAnnotations(JSON.stringify("red"))).toEqual([a, b]); + }); + test("withMemberAnnotations annotates a type", () => { const set = alternative(strings(), a); diff --git a/language-server/src/evaluation/JsonValueSet.ts b/language-server/src/evaluation/JsonValueSet.ts index 3637a14f..9b40e36f 100644 --- a/language-server/src/evaluation/JsonValueSet.ts +++ b/language-server/src/evaluation/JsonValueSet.ts @@ -188,6 +188,14 @@ export class JsonValueSet { return bucket && admits(bucket, value) ? annotationsOf(bucket, value) : []; } + // All the annotations that apply to a member of the set, both the location + // annotations and the member's own. A schema that applies both ways, such + // as one that's referenced unconditionally and as an anyOf alternative, is + // included once. + getAnnotations(value: string): AnnotationRecord[] { + return mergeAnnotations(this.annotations, this.getValueAnnotations(value)); + } + clone(): JsonValueSet { const copy = new JsonValueSet(); for (const [type, bucket] of this.buckets) { diff --git a/language-server/src/evaluation/LspEvaluationPlugin.ts b/language-server/src/evaluation/LspEvaluationPlugin.ts index 09553ae8..6e07c3ca 100644 --- a/language-server/src/evaluation/LspEvaluationPlugin.ts +++ b/language-server/src/evaluation/LspEvaluationPlugin.ts @@ -269,6 +269,7 @@ export class LspEvaluationPlugin implements EvaluationPlugin { if (!schemaContext.ownAnnotations) { this.ownAnnotationRecords[instance.pointer] ??= Object.create(null); schemaContext.ownAnnotations = this.ownAnnotationRecords[instance.pointer][schemaContext.schemaLocation!] ??= {}; + addEnumValues(schemaContext.ownAnnotations, context.ast[schemaContext.schemaLocation!] as Node[]); appendAnnotations(schemaContext.schemaAnnotations!, { [instance.pointer]: [{ kind: "location", annotation: schemaContext.ownAnnotations }] }); @@ -386,6 +387,12 @@ export class LspEvaluationPlugin implements EvaluationPlugin { return toAnnotations(this.completions[instanceLocation]?.().getMemberAnnotations() ?? []); } + // All the annotations that apply to a value completion at a location, both + // the location's and the ones that apply because of the value + getCompletionAnnotations(pointer: string, value: string): Annotation[] { + return toAnnotations(this.completions[pointer]?.().getAnnotations(value) ?? []); + } + private getAnnotationsOfKind(instanceLocation: string, kind: RecordedAnnotation["kind"]): AnnotationRecord[] { const annotations: AnnotationRecord[] = []; for (const recorded of this.annotations[instanceLocation]) { @@ -489,6 +496,7 @@ export class LspEvaluationPlugin implements EvaluationPlugin { ownAnnotations.firstAnnotationNode ??= node; } } + addEnumValues(ownAnnotations.annotation, nodes); this.completionAnnotations.set(schemaLocation, ownAnnotations); } @@ -631,6 +639,16 @@ function addKeywordAnnotation(annotation: AnnotationRecord, [keywordId, , keywor return false; } +// The values of enum aren't an annotation, but they're recorded with a +// schema's annotations because enumDescriptions describes them by position. +// They don't create a record on their own. +function addEnumValues(annotation: AnnotationRecord, nodes: Node[]) { + const enumNode = nodes.find(([keywordId]) => keywordId === "https://json-schema.org/keyword/enum"); + if (enumNode) { + annotation[enumNode[0]] = enumNode[2]; + } +} + function toAnnotations(records: AnnotationRecord[]): Annotation[] { return records.map((record) => new Annotation(record)); } diff --git a/language-server/src/evaluation/VscodeAnnotation.ts b/language-server/src/evaluation/VscodeAnnotation.ts index 98628ab0..9c4ff102 100644 --- a/language-server/src/evaluation/VscodeAnnotation.ts +++ b/language-server/src/evaluation/VscodeAnnotation.ts @@ -1,7 +1,7 @@ import "../vocabularies/vscode.ts"; import { compile, getSchema } from "@hyperjump/json-schema/experimental"; -import type { BaseAnnotation, Constructor } from "./Annotation.ts"; +import type { AnnotationRecord, BaseAnnotation, Constructor } from "./Annotation.ts"; // Accessors for the annotations of VS Code's custom keywords. The keywords are // defined in vocabularies/vscode.ts. @@ -75,4 +75,47 @@ export const VscodeAnnotation = >(Base: T) => cl || (this.keywords["https://microsoft.com/keyword/allowsTrailingCommas"] ?? this.unknownKeyword("allowsTrailingCommas", `${metaSchemaUri}#/properties/allowsTrailingCommas`, ast)) === true; } + + // Whether the schema has an enum, whose values could be described + hasEnum(): boolean { + return "https://json-schema.org/keyword/enum" in this.keywords; + } + + // VS Code describes an enum value with the description at the same position + // in enumDescriptions. The value is its canonical JSON, which is how the + // enum values are recorded. A value that isn't in the enum or has no + // description at its position isn't described. + enumDescription(value: string): string | undefined { + const descriptions = (this.keywords["https://microsoft.com/keyword/enumDescriptions"] + ?? this.unknownKeyword("enumDescriptions", `${metaSchemaUri}#/properties/enumDescriptions`, ast)) as string[] | undefined; + return descriptions?.[this.enumIndex(value)]; + } + + markdownEnumDescription(value: string): string | undefined { + const descriptions = (this.keywords["https://microsoft.com/keyword/markdownEnumDescriptions"] + ?? this.unknownKeyword("markdownEnumDescriptions", `${metaSchemaUri}#/properties/markdownEnumDescriptions`, ast)) as string[] | undefined; + return descriptions?.[this.enumIndex(value)]; + } + + // The position of the first occurrence of a value in the enum, or -1 if it + // isn't in the enum, which has no description. The positions are indexed + // once per record because they're looked up for every completion of the + // enum. + private enumIndex(value: string): number { + let positions = enumPositions.get(this.keywords); + if (!positions) { + positions = new Map(); + const enumValues = (this.keywords["https://json-schema.org/keyword/enum"] ?? []) as string[]; + for (const [index, enumValue] of enumValues.entries()) { + if (!positions.has(enumValue)) { + positions.set(enumValue, index); + } + } + enumPositions.set(this.keywords, positions); + } + + return positions.get(value) ?? -1; + } }; + +const enumPositions = new WeakMap>(); diff --git a/language-server/src/features/Hover.test.ts b/language-server/src/features/Hover.test.ts index 494ad803..fa686828 100644 --- a/language-server/src/features/Hover.test.ts +++ b/language-server/src/features/Hover.test.ts @@ -1475,4 +1475,141 @@ _hyperjump-json-language-server_` expect(result).toBeNull(); }); + + describe("enumDescriptions", () => { + const schema = { + properties: { + level: { + title: "Level", + enum: ["debug", "error"], + enumDescriptions: ["Log everything", "Log errors only"] + } + } + }; + + test("hovering an enum value shows the description at its position after the title and description", async () => { + const result = await hover(schema, ` "level": "error"`, { line: 2, character: 13 }); + + expect(result).toEqual({ + contents: { + kind: "markdown", + value: `**Level** + +Log errors only + +--- + +_hyperjump-json-language-server_` + } + }); + }); + + test("hovering the property key doesn't show the description of its value", async () => { + const result = await hover(schema, ` "level": "error"`, { line: 2, character: 4 }); + + expect(result).toEqual(hoverTitles("Level")); + }); + + test("hovering the colon of a property doesn't show the description of its value", async () => { + const result = await hover(schema, ` "level": "error"`, { line: 2, character: 9 }); + + expect(result).toEqual(hoverTitles("Level")); + }); + + test("hovering a value that isn't in the enum shows no description", async () => { + const result = await hover(schema, ` "level": "trace"`, { line: 2, character: 13 }); + + expect(result).toEqual(hoverTitles("Level")); + }); + + test("markdownEnumDescriptions is preferred over enumDescriptions", async () => { + const result = await hover({ + properties: { + level: { + enum: ["debug", "error"], + enumDescriptions: ["Log everything", "Log errors only"], + markdownEnumDescriptions: ["", "Log **errors** only"] + } + } + }, ` "level": "error"`, { line: 2, character: 13 }); + + expect(result).toEqual({ + contents: { + kind: "markdown", + value: `Log **errors** only + +--- + +_hyperjump-json-language-server_` + } + }); + }); + + test("an object value is matched no matter how its keys are ordered", async () => { + const result = await hover({ + properties: { + value: { + enum: [{ 10: 1, b: 2, 9: 3 }], + enumDescriptions: ["The object"] + } + } + }, ` "value": { "b": 2, "9": 3, "10": 1 }`, { line: 2, character: 11 }); + + expect(result).toEqual({ + contents: { + kind: "markdown", + value: `The object + +--- + +_hyperjump-json-language-server_` + } + }); + }); + + test("a number value is matched by its value", async () => { + const result = await hover({ + properties: { + value: { + enum: [1, 2], + enumDescriptions: ["One", "Two"] + } + } + }, ` "value": 2.0`, { line: 2, character: 11 }); + + expect(result).toEqual({ + contents: { + kind: "markdown", + value: `Two + +--- + +_hyperjump-json-language-server_` + } + }); + }); + + test("descriptions that aren't an array of strings are ignored", async () => { + const result = await hover({ + properties: { + level: { + enum: ["debug", "error"], + enumDescriptions: ["Log everything", "Log errors only"], + markdownEnumDescriptions: [42, 42] + } + } + }, ` "level": "error"`, { line: 2, character: 13 }); + + expect(result).toEqual({ + contents: { + kind: "markdown", + value: `Log errors only + +--- + +_hyperjump-json-language-server_` + } + }); + }); + }); }); diff --git a/language-server/src/features/Hover.ts b/language-server/src/features/Hover.ts index 7bd9a679..58418191 100644 --- a/language-server/src/features/Hover.ts +++ b/language-server/src/features/Hover.ts @@ -1,7 +1,7 @@ import { MarkupKind } from "vscode-languageserver"; import { JsonDocuments } from "../services/JsonDocuments.ts"; import { LspEvaluationPlugin } from "../evaluation/LspEvaluationPlugin.ts"; -import { describeAnnotations, joinDocumentation } from "./annotation-documentation.ts"; +import { describeAnnotations, describeEnumValue, joinDocumentation } from "./annotation-documentation.ts"; import type { Server } from "../services/Server.ts"; import type { ServerCapabilities } from "vscode-languageserver"; @@ -34,11 +34,22 @@ export class Hover { // apply because of what it is, after the more general ones. const plugin = LspEvaluationPlugin.from(result); const pointer = jsonDocument.getPointerForNode(node); - const annotations = jsonDocument.isPropertyKey(node) + const isPropertyKey = jsonDocument.isPropertyKey(node); + const annotations = isPropertyKey ? plugin.getLocationAnnotations(pointer) : [...plugin.getLocationAnnotations(pointer), ...plugin.getValueAnnotations(pointer)]; const documentation = describeAnnotations(annotations); + + // A value is also described by the enum descriptions it matches. The + // node of a property, which the cursor is on between its key and + // value, has no value. The canonical JSON of a large object or array + // is slow to build, so it's only built if the value could be an enum + // value. + if (!isPropertyKey && node.type !== "property" && annotations.some((annotation) => annotation.hasEnum())) { + documentation.push(...describeEnumValue(annotations, canonicalJson(jsonDocument.getNodeValue(node)))); + } + if (documentation.length === 0) { return; } @@ -51,3 +62,20 @@ export class Hover { }); } } + +// The same form as the enum values a schema is compiled to: no whitespace and +// keys in sorted order. JSON.stringify can't be used with a replacer that sorts +// keys because it puts integer-like keys first. +const canonicalJson = (value: unknown): string => { + if (Array.isArray(value)) { + return `[${value.map(canonicalJson).join(",")}]`; + } + + if (typeof value === "object" && value !== null) { + const properties = Object.keys(value).sort() + .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as Record)[key])}`); + return `{${properties.join(",")}}`; + } + + return JSON.stringify(value); +}; diff --git a/language-server/src/features/annotation-documentation.ts b/language-server/src/features/annotation-documentation.ts index 9cd74414..a1c5fc9b 100644 --- a/language-server/src/features/annotation-documentation.ts +++ b/language-server/src/features/annotation-documentation.ts @@ -25,6 +25,24 @@ export const describeAnnotations = (annotations: Annotation[]): MarkupContent[] return documentation; }; +// The descriptions of a value, given as its canonical JSON, from every +// annotation whose enum includes it. Prefers markdownEnumDescriptions over +// enumDescriptions. +export const describeEnumValue = (annotations: Annotation[], value: string): MarkupContent[] => { + const documentation: MarkupContent[] = []; + for (const annotation of annotations) { + const markdownDescription = annotation.markdownEnumDescription(value); + const description = annotation.enumDescription(value); + if (markdownDescription) { + documentation.push({ kind: MarkupKind.Markdown, value: markdownDescription }); + } else if (description) { + documentation.push({ kind: MarkupKind.PlainText, value: description }); + } + } + + return documentation; +}; + // Joins documentation into paragraphs. Markdown if any of it is markdown, // otherwise plain text. Plain text is escaped when it's combined with markdown. export const joinDocumentation = (documentation: MarkupContent[]): MarkupContent | undefined => { diff --git a/language-server/src/features/completions/Completions.ts b/language-server/src/features/completions/Completions.ts index 866186b1..45647ef6 100644 --- a/language-server/src/features/completions/Completions.ts +++ b/language-server/src/features/completions/Completions.ts @@ -119,14 +119,15 @@ const getCompletionContext = (jsonDocument: JsonDocument, position: Position): C // Describes a completion with its annotations. It's marked as deprecated if any // of them deprecate it, and its documentation leads with their deprecation -// messages followed by the titles and descriptions. -export const describeCompletion = (completionItem: CompletionItem, annotations: Annotation[]) => { +// messages followed by the titles and descriptions, and then any other +// documentation it's given. +export const describeCompletion = (completionItem: CompletionItem, annotations: Annotation[], otherDocumentation: MarkupContent[] = []) => { const deprecated = annotations.filter((annotation) => annotation.deprecated()); if (deprecated.length > 0) { completionItem.tags = [CompletionItemTag.Deprecated]; } - const documentation = joinDocumentation([...deprecationMessages(deprecated), ...describeAnnotations(annotations)]); + const documentation = joinDocumentation([...deprecationMessages(deprecated), ...describeAnnotations(annotations), ...otherDocumentation]); if (documentation) { completionItem.documentation = documentation; } diff --git a/language-server/src/features/completions/ValueCompletionsProvider.test.ts b/language-server/src/features/completions/ValueCompletionsProvider.test.ts index 8a379cad..9d904a28 100644 --- a/language-server/src/features/completions/ValueCompletionsProvider.test.ts +++ b/language-server/src/features/completions/ValueCompletionsProvider.test.ts @@ -4864,4 +4864,377 @@ describe("Value Completions", () => { expect(completions[1].tags).toBeUndefined(); }); }); + + describe("enumDescriptions", () => { + test("each enum value is documented with the description at its position", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "level": { + "enum": ["debug", "info", "error"], + "enumDescriptions": ["Log everything", "Log informational messages and above", "Log errors only"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "level": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"debug"`, documentation: { kind: MarkupKind.PlainText, value: "Log everything" } }, + { label: `"info"`, documentation: { kind: MarkupKind.PlainText, value: "Log informational messages and above" } }, + { label: `"error"`, documentation: { kind: MarkupKind.PlainText, value: "Log errors only" } } + ]); + }); + + test("a value without a description at its position isn't documented and extra descriptions are ignored", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "short": { + "enum": ["a", "b"], + "enumDescriptions": ["The a"] + }, + "long": { + "enum": ["a"], + "enumDescriptions": ["The a", "The b"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "short": + }`); + const shortUri = await client.openDocument("instance.json"); + + const shortCompletions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri: shortUri }, + position: { line: 2, character: 16 } + }) as CompletionItem[]; + + expect(shortCompletions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } }, + { label: `"b"` } + ]); + expect(shortCompletions[1]).not.toHaveProperty("documentation"); + + await client.writeDocument("long.json", `{ + "$schema": "${fixtureSchemaUri}", + "long": + }`); + const longUri = await client.openDocument("long.json"); + + const longCompletions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri: longUri }, + position: { line: 2, character: 15 } + }); + + expect(longCompletions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } } + ]); + }); + + test("markdownEnumDescriptions is preferred over enumDescriptions", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "enum": ["a", "b"], + "enumDescriptions": ["Plain a", "Plain b"], + "markdownEnumDescriptions": ["_Markdown_ a"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.Markdown, value: "_Markdown_ a" } }, + { label: `"b"`, documentation: { kind: MarkupKind.PlainText, value: "Plain b" } } + ]); + }); + + test("an enum reached through $ref is documented", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { "$ref": "#/$defs/value" } + }, + "$defs": { + "value": { + "enum": ["a"], + "enumDescriptions": ["The a"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } } + ]); + }); + + test("the description follows the title and description of an anyOf alternative", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "anyOf": [ + { "enum": ["a"], "title": "A", "enumDescriptions": ["The a."] }, + { "enum": ["b"] } + ] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }) as CompletionItem[]; + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.Markdown, value: "**A**\n\nThe a\\." } }, + { label: `"b"` } + ]); + expect(completions[1]).not.toHaveProperty("documentation"); + }); + + test("a partially typed value is documented", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "enum": ["a", "b"], + "enumDescriptions": ["The a", "The b"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": "a + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 19 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } }, + { label: `"b"`, documentation: { kind: MarkupKind.PlainText, value: "The b" } } + ]); + }); + + test("descriptions that aren't an array of strings are ignored", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "enum": ["a"], + "enumDescriptions": ["The a"], + "markdownEnumDescriptions": "The **a**" + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } } + ]); + }); + + test("the deprecation message comes before the description", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "enum": ["a", "b"], + "enumDescriptions": ["The a", "The b"], + "anyOf": [ + { "const": "a", "deprecationMessage": "Use b." }, + { "const": "b" } + ] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, tags: [CompletionItemTag.Deprecated], documentation: { kind: MarkupKind.PlainText, value: "Use b.\n\nThe a" } }, + { label: `"b"`, documentation: { kind: MarkupKind.PlainText, value: "The b" } } + ]); + }); + + test("enumDescriptions from a dialect that includes the vscode vocabulary", async () => { + await client.writeDocument("meta-schema.json", `{ + "$id": "https://example.com/dialect/vscode", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://microsoft.com/vocab/vscode": true + }, + "$dynamicAnchor": "meta", + "allOf": [ + { "$ref": "https://json-schema.org/draft/2020-12/schema" }, + { "$ref": "https://microsoft.com/meta/vscode" } + ] + }`); + + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://example.com/dialect/vscode", + "type": "object", + "properties": { + "value": { + "enum": ["a", "b"], + "enumDescriptions": ["The a"], + "markdownEnumDescriptions": ["", "The **b**"] + } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } }, + { label: `"b"`, documentation: { kind: MarkupKind.Markdown, value: "The **b**" } } + ]); + }); + + test("a schema that applies more than once at a location is described once", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "$ref": "#/$defs/value", + "anyOf": [{ "$ref": "#/$defs/value" }, { "type": "number" }] + } + }, + "$defs": { + "value": { "enum": ["a"], "enumDescriptions": ["The a"] } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 16 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } } + ]); + }); + + test("a schema that applies more than once at a location is described once for a partially typed value", async () => { + const fixtureSchemaUri = await client.writeDocument("schema.json", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "value": { + "$ref": "#/$defs/value", + "anyOf": [{ "$ref": "#/$defs/value" }, { "type": "number" }] + } + }, + "$defs": { + "value": { "enum": ["a"], "enumDescriptions": ["The a"] } + } + }`); + + await client.writeDocument("instance.json", `{ + "$schema": "${fixtureSchemaUri}", + "value": "a + }`); + const uri = await client.openDocument("instance.json"); + + const completions = await client.sendRequest(CompletionRequest.type, { + textDocument: { uri }, + position: { line: 2, character: 19 } + }); + + expect(completions).toMatchObject([ + { label: `"a"`, documentation: { kind: MarkupKind.PlainText, value: "The a" } } + ]); + }); + }); }); diff --git a/language-server/src/features/completions/ValueCompletionsProvider.ts b/language-server/src/features/completions/ValueCompletionsProvider.ts index a2b76a25..4c1336cd 100644 --- a/language-server/src/features/completions/ValueCompletionsProvider.ts +++ b/language-server/src/features/completions/ValueCompletionsProvider.ts @@ -1,6 +1,7 @@ import { CompletionItemKind, InsertTextFormat } from "vscode-languageserver"; import { JsonDocument } from "../../models/JsonDocument.ts"; import { LspEvaluationPlugin } from "../../evaluation/LspEvaluationPlugin.ts"; +import { describeEnumValue } from "../annotation-documentation.ts"; import { describeCompletion } from "./Completions.ts"; import type { CompletionContext, CompletionsProvider } from "./Completions.ts"; @@ -48,8 +49,12 @@ export class ValueCompletionsProvider implements CompletionsProvider { }; // A value is described and deprecated only because of what it is, not - // because of its location - describeCompletion(completionItem, completion.annotations); + // because of its location. Its enum description is about what it is + // too, but it's in the schema of its location or of an alternative. + const enumDescriptions = completion.kind === "value" + ? describeEnumValue(plugin.getCompletionAnnotations(context.instanceLocation, completion.value), completion.value) + : []; + describeCompletion(completionItem, completion.annotations, enumDescriptions); completions.push(completionItem); } diff --git a/language-server/src/vocabularies/vscode.ts b/language-server/src/vocabularies/vscode.ts index 1dc3e4b1..10c848e0 100644 --- a/language-server/src/vocabularies/vscode.ts +++ b/language-server/src/vocabularies/vscode.ts @@ -72,6 +72,20 @@ addKeyword({ annotation: (value: unknown) => value }); +addKeyword({ + id: "https://microsoft.com/keyword/enumDescriptions", + compile: (schema) => Browser.value(schema), + interpret: () => true, + annotation: (value: unknown) => value +}); + +addKeyword({ + id: "https://microsoft.com/keyword/markdownEnumDescriptions", + compile: (schema) => Browser.value(schema), + interpret: () => true, + annotation: (value: unknown) => value +}); + defineVocabulary("https://microsoft.com/vocab/vscode", { markdownDescription: "https://microsoft.com/keyword/markdownDescription", defaultSnippets: "https://microsoft.com/keyword/defaultSnippets", @@ -82,7 +96,9 @@ defineVocabulary("https://microsoft.com/vocab/vscode", { doNotSuggest: "https://microsoft.com/keyword/doNotSuggest", allowComments: "https://microsoft.com/keyword/allowComments", allowTrailingCommas: "https://microsoft.com/keyword/allowTrailingCommas", - allowsTrailingCommas: "https://microsoft.com/keyword/allowsTrailingCommas" + allowsTrailingCommas: "https://microsoft.com/keyword/allowsTrailingCommas", + enumDescriptions: "https://microsoft.com/keyword/enumDescriptions", + markdownEnumDescriptions: "https://microsoft.com/keyword/markdownEnumDescriptions" }); registerSchema({ @@ -111,6 +127,8 @@ registerSchema({ doNotSuggest: { type: "boolean" }, allowComments: { type: "boolean" }, allowTrailingCommas: { type: "boolean" }, - allowsTrailingCommas: { type: "boolean" } + allowsTrailingCommas: { type: "boolean" }, + enumDescriptions: { type: "array", items: { type: "string" } }, + markdownEnumDescriptions: { type: "array", items: { type: "string" } } } });