Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions language-server/src/evaluation/Annotation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AnnotationRecord, Map<string, Json | undefined>>();

// 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.
Expand Down
9 changes: 9 additions & 0 deletions language-server/src/evaluation/JsonValueSet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
8 changes: 8 additions & 0 deletions language-server/src/evaluation/JsonValueSet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
18 changes: 18 additions & 0 deletions language-server/src/evaluation/LspEvaluationPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ export class LspEvaluationPlugin implements EvaluationPlugin<LspContext> {
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<unknown>[]);
appendAnnotations(schemaContext.schemaAnnotations!, {
[instance.pointer]: [{ kind: "location", annotation: schemaContext.ownAnnotations }]
});
Expand Down Expand Up @@ -386,6 +387,12 @@ export class LspEvaluationPlugin implements EvaluationPlugin<LspContext> {
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]) {
Expand Down Expand Up @@ -489,6 +496,7 @@ export class LspEvaluationPlugin implements EvaluationPlugin<LspContext> {
ownAnnotations.firstAnnotationNode ??= node;
}
}
addEnumValues(ownAnnotations.annotation, nodes);
this.completionAnnotations.set(schemaLocation, ownAnnotations);
}

Expand Down Expand Up @@ -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<unknown>[]) {
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));
}
Expand Down
45 changes: 44 additions & 1 deletion language-server/src/evaluation/VscodeAnnotation.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -75,4 +75,47 @@ export const VscodeAnnotation = <T extends Constructor<Extended>>(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<AnnotationRecord, Map<string, number>>();
137 changes: 137 additions & 0 deletions language-server/src/features/Hover.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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_`
}
});
});
});
});
32 changes: 30 additions & 2 deletions language-server/src/features/Hover.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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;
}
Expand All @@ -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<string, unknown>)[key])}`);
return `{${properties.join(",")}}`;
}

return JSON.stringify(value);
};
18 changes: 18 additions & 0 deletions language-server/src/features/annotation-documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
Loading
Loading