From ffc1b9c4499db5ad677ce5e381311bfa84fdb19e Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:01:03 +0100 Subject: [PATCH 01/19] add declaration, documentHighlight, prepareRename Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 3 +++ src/cli.ts | 3 +++ src/context.ts | 21 +++++++++++++++++++++ src/harness.ts | 2 ++ src/types.ts | 3 +++ test/context.test.ts | 29 +++++++++++++++++++++++++++++ 6 files changed, 61 insertions(+) diff --git a/README.md b/README.md index 18a3a33..98cebce 100644 --- a/README.md +++ b/README.md @@ -83,9 +83,12 @@ export default async function (ctx: BenchContext) { | `references(path, line, char)` | `textDocument/references` (timed) | | `typeDefinition(path, line, char)` | `textDocument/typeDefinition` (timed) | | `implementation(path, line, char)` | `textDocument/implementation` (timed) | +| `declaration(path, line, char)` | `textDocument/declaration` (timed) | +| `documentHighlight(path, line, char)` | `textDocument/documentHighlight` (timed) | | `documentSymbol(path)` | `textDocument/documentSymbol` (timed) | | `formatting(path)` | `textDocument/formatting` (timed) | | `rename(path, line, char, newName)` | `textDocument/rename` (timed) | +| `prepareRename(path, line, char)` | `textDocument/prepareRename` (timed) | | `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed) | | `signatureHelp(path, line, char)` | `textDocument/signatureHelp` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | diff --git a/src/cli.ts b/src/cli.ts index 460b012..349e68d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -220,9 +220,12 @@ Timed LSP requests (return the raw LSP result, or null on failure) references(path, line, char) textDocument/references (includeDeclaration: true) typeDefinition(path, line, char) textDocument/typeDefinition implementation(path, line, char) textDocument/implementation + declaration(path, line, char) textDocument/declaration + documentHighlight(path, line, char) textDocument/documentHighlight documentSymbol(path) textDocument/documentSymbol formatting(path) textDocument/formatting (tabSize 2, spaces) rename(path, line, char, newName) textDocument/rename + prepareRename(path, line, char) textDocument/prepareRename codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics) signatureHelp(path, line, char) textDocument/signatureHelp diff --git a/src/context.ts b/src/context.ts index 976012c..669e4e6 100644 --- a/src/context.ts +++ b/src/context.ts @@ -174,6 +174,27 @@ export class BenchContextImpl implements BenchContext { }); } + async declaration(relativePath: string, line: number, character: number): Promise { + return this.timedRequest('textDocument/declaration', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + }); + } + + async documentHighlight(relativePath: string, line: number, character: number): Promise { + return this.timedRequest('textDocument/documentHighlight', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + }); + } + + async prepareRename(relativePath: string, line: number, character: number): Promise { + return this.timedRequest('textDocument/prepareRename', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index ee88856..a02260c 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -281,9 +281,11 @@ export class LspHarness { contextSupport: true, }, definition: { dynamicRegistration: true, linkSupport: true }, + declaration: { dynamicRegistration: true, linkSupport: true }, typeDefinition: { dynamicRegistration: true, linkSupport: true }, implementation: { dynamicRegistration: true, linkSupport: true }, references: { dynamicRegistration: true }, + documentHighlight: { dynamicRegistration: true }, documentSymbol: { dynamicRegistration: true, hierarchicalDocumentSymbolSupport: true, diff --git a/src/types.ts b/src/types.ts index 2ff81ac..b20c292 100644 --- a/src/types.ts +++ b/src/types.ts @@ -131,6 +131,9 @@ export interface BenchContext { signatureHelp(relativePath: string, line: number, character: number): Promise; typeDefinition(relativePath: string, line: number, character: number): Promise; implementation(relativePath: string, line: number, character: number): Promise; + declaration(relativePath: string, line: number, character: number): Promise; + documentHighlight(relativePath: string, line: number, character: number): Promise; + prepareRename(relativePath: string, line: number, character: number): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index 2c01743..a6a81d1 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -130,6 +130,35 @@ describe('BenchContextImpl', () => { expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); }); + // position based requests that share the same params shape + const positionRequests = [ + { name: 'declaration', method: 'textDocument/declaration' }, + { name: 'documentHighlight', method: 'textDocument/documentHighlight' }, + { name: 'prepareRename', method: 'textDocument/prepareRename' }, + ] as const; + + for (const { name, method } of positionRequests) { + it(`${name} issues ${method} with the document uri and position and records a timing`, async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx[name]('sample.ts', 0, 6); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe(method); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + position: { line: 0, character: 6 }, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe(method); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + } + it('references includes the declaration in its context', async () => { await ctx.references('sample.ts', 0, 6); const req = harness.requests.find((r) => r.method === 'textDocument/references'); From 289e32acced1305fccf1301c13c671c91bd0d776 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:01:37 +0100 Subject: [PATCH 02/19] add rangeFormatting, onTypeFormatting Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 2 ++ src/cli.ts | 2 ++ src/context.ts | 22 +++++++++++++++++++++- src/harness.ts | 2 ++ src/types.ts | 2 ++ test/context.test.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 73 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 98cebce..adb1fce 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,8 @@ export default async function (ctx: BenchContext) { | `documentHighlight(path, line, char)` | `textDocument/documentHighlight` (timed) | | `documentSymbol(path)` | `textDocument/documentSymbol` (timed) | | `formatting(path)` | `textDocument/formatting` (timed) | +| `rangeFormatting(path, range)` | `textDocument/rangeFormatting` (timed) | +| `onTypeFormatting(path, line, char, ch)` | `textDocument/onTypeFormatting` (timed) | | `rename(path, line, char, newName)` | `textDocument/rename` (timed) | | `prepareRename(path, line, char)` | `textDocument/prepareRename` (timed) | | `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed) | diff --git a/src/cli.ts b/src/cli.ts index 349e68d..4c5b374 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -224,6 +224,8 @@ Timed LSP requests (return the raw LSP result, or null on failure) documentHighlight(path, line, char) textDocument/documentHighlight documentSymbol(path) textDocument/documentSymbol formatting(path) textDocument/formatting (tabSize 2, spaces) + rangeFormatting(path, range) textDocument/rangeFormatting (tabSize 2, spaces) + onTypeFormatting(path, line, char, ch) textDocument/onTypeFormatting (ch is the typed trigger character) rename(path, line, char, newName) textDocument/rename prepareRename(path, line, char) textDocument/prepareRename codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics) diff --git a/src/context.ts b/src/context.ts index 669e4e6..f353755 100644 --- a/src/context.ts +++ b/src/context.ts @@ -124,7 +124,24 @@ export class BenchContextImpl implements BenchContext { async formatting(relativePath: string): Promise { return this.timedRequest('textDocument/formatting', { textDocument: { uri: this.getUri(relativePath) }, - options: { tabSize: 2, insertSpaces: true }, + options: FORMATTING_OPTIONS, + }); + } + + async rangeFormatting(relativePath: string, range: Range): Promise { + return this.timedRequest('textDocument/rangeFormatting', { + textDocument: { uri: this.getUri(relativePath) }, + range: toLspRange(range), + options: FORMATTING_OPTIONS, + }); + } + + async onTypeFormatting(relativePath: string, line: number, character: number, ch: string): Promise { + return this.timedRequest('textDocument/onTypeFormatting', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + ch, + options: FORMATTING_OPTIONS, }); } @@ -292,6 +309,9 @@ export class BenchContextImpl implements BenchContext { // ── Utilities ───────────────────────────────────────────────────────────── +/** formatting options shared by all formatting requests */ +const FORMATTING_OPTIONS = { tabSize: 2, insertSpaces: true }; + function toLspRange(range: Range): { start: { line: number; character: number }; end: { line: number; character: number }; diff --git a/src/harness.ts b/src/harness.ts index a02260c..20036bb 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -294,6 +294,8 @@ export class LspHarness { }, }, formatting: { dynamicRegistration: true }, + rangeFormatting: { dynamicRegistration: true }, + onTypeFormatting: { dynamicRegistration: true }, rename: { dynamicRegistration: true, prepareSupport: true }, codeAction: { dynamicRegistration: true, diff --git a/src/types.ts b/src/types.ts index b20c292..fd0f982 100644 --- a/src/types.ts +++ b/src/types.ts @@ -126,6 +126,8 @@ export interface BenchContext { references(relativePath: string, line: number, character: number): Promise; documentSymbol(relativePath: string): Promise; formatting(relativePath: string): Promise; + rangeFormatting(relativePath: string, range: Range): Promise; + onTypeFormatting(relativePath: string, line: number, character: number, ch: string): Promise; rename(relativePath: string, line: number, character: number, newName: string): Promise; codeAction(relativePath: string, range: Range, diagnosticCodes?: (string | number)[]): Promise; signatureHelp(relativePath: string, line: number, character: number): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index a6a81d1..5f30619 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -159,6 +159,50 @@ describe('BenchContextImpl', () => { }); } + it('rangeFormatting issues textDocument/rangeFormatting with the range and options and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const range = { start: { line: 0, character: 0 }, end: { line: 0, character: 20 } }; + const res = await ctx.rangeFormatting('sample.ts', range); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/rangeFormatting'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + range, + options: { tabSize: 2, insertSpaces: true }, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/rangeFormatting'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('onTypeFormatting issues textDocument/onTypeFormatting with the trigger character and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx.onTypeFormatting('sample.ts', 0, 20, ';'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/onTypeFormatting'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + position: { line: 0, character: 20 }, + ch: ';', + options: { tabSize: 2, insertSpaces: true }, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/onTypeFormatting'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + it('references includes the declaration in its context', async () => { await ctx.references('sample.ts', 0, 6); const req = harness.requests.find((r) => r.method === 'textDocument/references'); From 0f3b6f45025528381099f6ab0fcba99ac0d735f3 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:02:36 +0100 Subject: [PATCH 03/19] add foldingRange, selectionRange, documentLink, codeLens, inlayHint Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 5 +++ src/cli.ts | 5 +++ src/context.ts | 34 ++++++++++++++++++++- src/harness.ts | 5 +++ src/types.ts | 5 +++ test/context.test.ts | 73 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 126 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index adb1fce..832e51d 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,11 @@ export default async function (ctx: BenchContext) { | `prepareRename(path, line, char)` | `textDocument/prepareRename` (timed) | | `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed) | | `signatureHelp(path, line, char)` | `textDocument/signatureHelp` (timed) | +| `foldingRange(path)` | `textDocument/foldingRange` (timed) | +| `selectionRange(path, positions)` | `textDocument/selectionRange` (timed) | +| `documentLink(path)` | `textDocument/documentLink` (timed) | +| `codeLens(path)` | `textDocument/codeLens` (timed) | +| `inlayHint(path, range)` | `textDocument/inlayHint` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | diff --git a/src/cli.ts b/src/cli.ts index 4c5b374..193ce60 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -230,6 +230,11 @@ Timed LSP requests (return the raw LSP result, or null on failure) prepareRename(path, line, char) textDocument/prepareRename codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics) signatureHelp(path, line, char) textDocument/signatureHelp + foldingRange(path) textDocument/foldingRange + selectionRange(path, positions) textDocument/selectionRange (positions is an array of {line,character}) + documentLink(path) textDocument/documentLink + codeLens(path) textDocument/codeLens + inlayHint(path, range) textDocument/inlayHint Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index f353755..076704a 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { type Diagnostic, type LspHarness, pathToUri } from './harness.js'; -import type { BenchContext, EditOperation, Range, RequestTiming } from './types.js'; +import type { BenchContext, EditOperation, Position, Range, RequestTiming } from './types.js'; /** * Concrete implementation of BenchContext. @@ -212,6 +212,38 @@ export class BenchContextImpl implements BenchContext { }); } + async foldingRange(relativePath: string): Promise { + return this.timedRequest('textDocument/foldingRange', { + textDocument: { uri: this.getUri(relativePath) }, + }); + } + + async selectionRange(relativePath: string, positions: Position[]): Promise { + return this.timedRequest('textDocument/selectionRange', { + textDocument: { uri: this.getUri(relativePath) }, + positions: positions.map((p) => ({ line: p.line, character: p.character })), + }); + } + + async documentLink(relativePath: string): Promise { + return this.timedRequest('textDocument/documentLink', { + textDocument: { uri: this.getUri(relativePath) }, + }); + } + + async codeLens(relativePath: string): Promise { + return this.timedRequest('textDocument/codeLens', { + textDocument: { uri: this.getUri(relativePath) }, + }); + } + + async inlayHint(relativePath: string, range: Range): Promise { + return this.timedRequest('textDocument/inlayHint', { + textDocument: { uri: this.getUri(relativePath) }, + range: toLspRange(range), + }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index 20036bb..0d7a876 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -321,6 +321,11 @@ export class LspHarness { parameterInformation: { labelOffsetSupport: true }, }, }, + foldingRange: { dynamicRegistration: true, lineFoldingOnly: false }, + selectionRange: { dynamicRegistration: true }, + documentLink: { dynamicRegistration: true, tooltipSupport: true }, + codeLens: { dynamicRegistration: true }, + inlayHint: { dynamicRegistration: true }, publishDiagnostics: { relatedInformation: true, tagSupport: { valueSet: [1, 2] }, diff --git a/src/types.ts b/src/types.ts index fd0f982..60eb932 100644 --- a/src/types.ts +++ b/src/types.ts @@ -136,6 +136,11 @@ export interface BenchContext { declaration(relativePath: string, line: number, character: number): Promise; documentHighlight(relativePath: string, line: number, character: number): Promise; prepareRename(relativePath: string, line: number, character: number): Promise; + foldingRange(relativePath: string): Promise; + selectionRange(relativePath: string, positions: Position[]): Promise; + documentLink(relativePath: string): Promise; + codeLens(relativePath: string): Promise; + inlayHint(relativePath: string, range: Range): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index 5f30619..80f9819 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -159,6 +159,79 @@ describe('BenchContextImpl', () => { }); } + // document scoped requests that only take a text document identifier + const documentRequests = [ + { name: 'foldingRange', method: 'textDocument/foldingRange' }, + { name: 'documentLink', method: 'textDocument/documentLink' }, + { name: 'codeLens', method: 'textDocument/codeLens' }, + ] as const; + + for (const { name, method } of documentRequests) { + it(`${name} issues ${method} with the document uri and records a timing`, async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx[name]('sample.ts'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe(method); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe(method); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + } + + it('selectionRange issues textDocument/selectionRange with the positions and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const positions = [ + { line: 0, character: 6 }, + { line: 0, character: 18 }, + ]; + const res = await ctx.selectionRange('sample.ts', positions); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/selectionRange'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + positions, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/selectionRange'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('inlayHint issues textDocument/inlayHint with the range and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const range = { start: { line: 0, character: 0 }, end: { line: 1, character: 0 } }; + const res = await ctx.inlayHint('sample.ts', range); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/inlayHint'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + range, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/inlayHint'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + it('rangeFormatting issues textDocument/rangeFormatting with the range and options and records a timing', async () => { await ctx.openDocument('sample.ts'); const range = { start: { line: 0, character: 0 }, end: { line: 0, character: 20 } }; From e20743005097dedfe83b1ed8bf93c9bbc316f75c Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:03:19 +0100 Subject: [PATCH 04/19] add semantic tokens full, range, delta Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 3 +++ src/cli.ts | 3 +++ src/context.ts | 20 +++++++++++++++ src/harness.ts | 47 ++++++++++++++++++++++++++++++++++ src/types.ts | 3 +++ test/context.test.ts | 60 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 136 insertions(+) diff --git a/README.md b/README.md index 832e51d..c319bde 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,9 @@ export default async function (ctx: BenchContext) { | `documentLink(path)` | `textDocument/documentLink` (timed) | | `codeLens(path)` | `textDocument/codeLens` (timed) | | `inlayHint(path, range)` | `textDocument/inlayHint` (timed) | +| `semanticTokensFull(path)` | `textDocument/semanticTokens/full` (timed) | +| `semanticTokensRange(path, range)` | `textDocument/semanticTokens/range` (timed) | +| `semanticTokensDelta(path, previousResultId)` | `textDocument/semanticTokens/full/delta` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | diff --git a/src/cli.ts b/src/cli.ts index 193ce60..c20a1ba 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -235,6 +235,9 @@ Timed LSP requests (return the raw LSP result, or null on failure) documentLink(path) textDocument/documentLink codeLens(path) textDocument/codeLens inlayHint(path, range) textDocument/inlayHint + semanticTokensFull(path) textDocument/semanticTokens/full + semanticTokensRange(path, range) textDocument/semanticTokens/range + semanticTokensDelta(path, prevResultId) textDocument/semanticTokens/full/delta (prevResultId from a prior result) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index 076704a..746de72 100644 --- a/src/context.ts +++ b/src/context.ts @@ -244,6 +244,26 @@ export class BenchContextImpl implements BenchContext { }); } + async semanticTokensFull(relativePath: string): Promise { + return this.timedRequest('textDocument/semanticTokens/full', { + textDocument: { uri: this.getUri(relativePath) }, + }); + } + + async semanticTokensRange(relativePath: string, range: Range): Promise { + return this.timedRequest('textDocument/semanticTokens/range', { + textDocument: { uri: this.getUri(relativePath) }, + range: toLspRange(range), + }); + } + + async semanticTokensDelta(relativePath: string, previousResultId: string): Promise { + return this.timedRequest('textDocument/semanticTokens/full/delta', { + textDocument: { uri: this.getUri(relativePath) }, + previousResultId, + }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index 0d7a876..f4cdba8 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -326,6 +326,53 @@ export class LspHarness { documentLink: { dynamicRegistration: true, tooltipSupport: true }, codeLens: { dynamicRegistration: true }, inlayHint: { dynamicRegistration: true }, + semanticTokens: { + dynamicRegistration: true, + requests: { + range: true, + full: { delta: true }, + }, + tokenTypes: [ + 'namespace', + 'type', + 'class', + 'enum', + 'interface', + 'struct', + 'typeParameter', + 'parameter', + 'variable', + 'property', + 'enumMember', + 'event', + 'function', + 'method', + 'macro', + 'keyword', + 'modifier', + 'comment', + 'string', + 'number', + 'regexp', + 'operator', + 'decorator', + ], + tokenModifiers: [ + 'declaration', + 'definition', + 'readonly', + 'static', + 'deprecated', + 'abstract', + 'async', + 'modification', + 'documentation', + 'defaultLibrary', + ], + formats: ['relative'], + overlappingTokenSupport: false, + multilineTokenSupport: false, + }, publishDiagnostics: { relatedInformation: true, tagSupport: { valueSet: [1, 2] }, diff --git a/src/types.ts b/src/types.ts index 60eb932..c9b56ca 100644 --- a/src/types.ts +++ b/src/types.ts @@ -141,6 +141,9 @@ export interface BenchContext { documentLink(relativePath: string): Promise; codeLens(relativePath: string): Promise; inlayHint(relativePath: string, range: Range): Promise; + semanticTokensFull(relativePath: string): Promise; + semanticTokensRange(relativePath: string, range: Range): Promise; + semanticTokensDelta(relativePath: string, previousResultId: string): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index 80f9819..b136631 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -232,6 +232,66 @@ describe('BenchContextImpl', () => { expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); }); + it('semanticTokensFull issues textDocument/semanticTokens/full for the document and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx.semanticTokensFull('sample.ts'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/semanticTokens/full'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/semanticTokens/full'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('semanticTokensRange issues textDocument/semanticTokens/range with the range and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const range = { start: { line: 0, character: 0 }, end: { line: 1, character: 0 } }; + const res = await ctx.semanticTokensRange('sample.ts', range); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/semanticTokens/range'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + range, + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/semanticTokens/range'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('semanticTokensDelta issues textDocument/semanticTokens/full/delta with the previous result id and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx.semanticTokensDelta('sample.ts', 'result-1'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/semanticTokens/full/delta'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + previousResultId: 'result-1', + }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/semanticTokens/full/delta'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + it('rangeFormatting issues textDocument/rangeFormatting with the range and options and records a timing', async () => { await ctx.openDocument('sample.ts'); const range = { start: { line: 0, character: 0 }, end: { line: 0, character: 20 } }; From c57a28428e95d1f8710078546418f9d178c52596 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:03:55 +0100 Subject: [PATCH 05/19] add workspaceSymbol Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 1 + src/cli.ts | 1 + src/context.ts | 4 ++++ src/harness.ts | 1 + src/types.ts | 1 + test/context.test.ts | 16 ++++++++++++++++ 6 files changed, 24 insertions(+) diff --git a/README.md b/README.md index c319bde..29dce92 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ export default async function (ctx: BenchContext) { | `semanticTokensFull(path)` | `textDocument/semanticTokens/full` (timed) | | `semanticTokensRange(path, range)` | `textDocument/semanticTokens/range` (timed) | | `semanticTokensDelta(path, previousResultId)` | `textDocument/semanticTokens/full/delta` (timed) | +| `workspaceSymbol(query)` | `workspace/symbol` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | diff --git a/src/cli.ts b/src/cli.ts index c20a1ba..4d35daf 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -238,6 +238,7 @@ Timed LSP requests (return the raw LSP result, or null on failure) semanticTokensFull(path) textDocument/semanticTokens/full semanticTokensRange(path, range) textDocument/semanticTokens/range semanticTokensDelta(path, prevResultId) textDocument/semanticTokens/full/delta (prevResultId from a prior result) + workspaceSymbol(query) workspace/symbol (workspace-wide, no document needed) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index 746de72..79bb5e4 100644 --- a/src/context.ts +++ b/src/context.ts @@ -264,6 +264,10 @@ export class BenchContextImpl implements BenchContext { }); } + async workspaceSymbol(query: string): Promise { + return this.timedRequest('workspace/symbol', { query }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index f4cdba8..6daed07 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -255,6 +255,7 @@ export class LspHarness { symbolKind: { valueSet: Array.from({ length: 26 }, (_, i) => i + 1), }, + resolveSupport: { properties: ['location.range'] }, }, }, textDocument: { diff --git a/src/types.ts b/src/types.ts index c9b56ca..091bad2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -144,6 +144,7 @@ export interface BenchContext { semanticTokensFull(relativePath: string): Promise; semanticTokensRange(relativePath: string, range: Range): Promise; semanticTokensDelta(relativePath: string, previousResultId: string): Promise; + workspaceSymbol(query: string): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index b136631..9f5aa65 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -292,6 +292,22 @@ describe('BenchContextImpl', () => { expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); }); + it('workspaceSymbol issues workspace/symbol with the query and records a timing', async () => { + const res = await ctx.workspaceSymbol('Foo'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('workspace/symbol'); + expect(req.params).toEqual({ query: 'Foo' }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('workspace/symbol'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + it('rangeFormatting issues textDocument/rangeFormatting with the range and options and records a timing', async () => { await ctx.openDocument('sample.ts'); const range = { start: { line: 0, character: 0 }, end: { line: 0, character: 20 } }; From 8b3d6885f592d7a6afc8933396ae397ffa20ae1c Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:04:47 +0100 Subject: [PATCH 06/19] add call hierarchy and type hierarchy Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 16 ++++++++++++++++ src/cli.ts | 6 ++++++ src/context.ts | 30 ++++++++++++++++++++++++++++++ src/harness.ts | 2 ++ src/types.ts | 6 ++++++ test/context.test.ts | 35 +++++++++++++++++++++++++++++++++++ 6 files changed, 95 insertions(+) diff --git a/README.md b/README.md index 29dce92..612e862 100644 --- a/README.md +++ b/README.md @@ -102,12 +102,28 @@ export default async function (ctx: BenchContext) { | `semanticTokensRange(path, range)` | `textDocument/semanticTokens/range` (timed) | | `semanticTokensDelta(path, previousResultId)` | `textDocument/semanticTokens/full/delta` (timed) | | `workspaceSymbol(query)` | `workspace/symbol` (timed) | +| `prepareCallHierarchy(path, line, char)` | `textDocument/prepareCallHierarchy` (timed) | +| `callHierarchyIncomingCalls(item)` | `callHierarchy/incomingCalls` (timed) | +| `callHierarchyOutgoingCalls(item)` | `callHierarchy/outgoingCalls` (timed) | +| `prepareTypeHierarchy(path, line, char)` | `textDocument/prepareTypeHierarchy` (timed) | +| `typeHierarchySupertypes(item)` | `typeHierarchy/supertypes` (timed) | +| `typeHierarchySubtypes(item)` | `typeHierarchy/subtypes` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | | `request(method, params, label?)` | Arbitrary timed LSP request | | `notify(method, params)` | Send any LSP notification | +Call and type hierarchy requests take an item returned by the matching prepare call: + +```ts +const items = (await ctx.prepareCallHierarchy("src/index.ts", 10, 5)) as unknown[] | null; +if (items && items.length > 0) { + await ctx.callHierarchyIncomingCalls(items[0]); + await ctx.callHierarchyOutgoingCalls(items[0]); +} +``` + In some cases you may also need to register a language ID for a given extension. That's straightforward to do with `addRegisteredLanguage`, which will then impact all context related actions for documents with a matching extension. diff --git a/src/cli.ts b/src/cli.ts index 4d35daf..daf67c6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -239,6 +239,12 @@ Timed LSP requests (return the raw LSP result, or null on failure) semanticTokensRange(path, range) textDocument/semanticTokens/range semanticTokensDelta(path, prevResultId) textDocument/semanticTokens/full/delta (prevResultId from a prior result) workspaceSymbol(query) workspace/symbol (workspace-wide, no document needed) + prepareCallHierarchy(path, line, char) textDocument/prepareCallHierarchy (returns CallHierarchyItem[]) + callHierarchyIncomingCalls(item) callHierarchy/incomingCalls (item from prepareCallHierarchy) + callHierarchyOutgoingCalls(item) callHierarchy/outgoingCalls (item from prepareCallHierarchy) + prepareTypeHierarchy(path, line, char) textDocument/prepareTypeHierarchy (returns TypeHierarchyItem[]) + typeHierarchySupertypes(item) typeHierarchy/supertypes (item from prepareTypeHierarchy) + typeHierarchySubtypes(item) typeHierarchy/subtypes (item from prepareTypeHierarchy) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index 79bb5e4..934848c 100644 --- a/src/context.ts +++ b/src/context.ts @@ -268,6 +268,36 @@ export class BenchContextImpl implements BenchContext { return this.timedRequest('workspace/symbol', { query }); } + async prepareCallHierarchy(relativePath: string, line: number, character: number): Promise { + return this.timedRequest('textDocument/prepareCallHierarchy', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + }); + } + + async callHierarchyIncomingCalls(item: unknown): Promise { + return this.timedRequest('callHierarchy/incomingCalls', { item }); + } + + async callHierarchyOutgoingCalls(item: unknown): Promise { + return this.timedRequest('callHierarchy/outgoingCalls', { item }); + } + + async prepareTypeHierarchy(relativePath: string, line: number, character: number): Promise { + return this.timedRequest('textDocument/prepareTypeHierarchy', { + textDocument: { uri: this.getUri(relativePath) }, + position: { line, character }, + }); + } + + async typeHierarchySupertypes(item: unknown): Promise { + return this.timedRequest('typeHierarchy/supertypes', { item }); + } + + async typeHierarchySubtypes(item: unknown): Promise { + return this.timedRequest('typeHierarchy/subtypes', { item }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index 6daed07..cb02609 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -327,6 +327,8 @@ export class LspHarness { documentLink: { dynamicRegistration: true, tooltipSupport: true }, codeLens: { dynamicRegistration: true }, inlayHint: { dynamicRegistration: true }, + callHierarchy: { dynamicRegistration: true }, + typeHierarchy: { dynamicRegistration: true }, semanticTokens: { dynamicRegistration: true, requests: { diff --git a/src/types.ts b/src/types.ts index 091bad2..4ce004f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -145,6 +145,12 @@ export interface BenchContext { semanticTokensRange(relativePath: string, range: Range): Promise; semanticTokensDelta(relativePath: string, previousResultId: string): Promise; workspaceSymbol(query: string): Promise; + prepareCallHierarchy(relativePath: string, line: number, character: number): Promise; + callHierarchyIncomingCalls(item: unknown): Promise; + callHierarchyOutgoingCalls(item: unknown): Promise; + prepareTypeHierarchy(relativePath: string, line: number, character: number): Promise; + typeHierarchySupertypes(item: unknown): Promise; + typeHierarchySubtypes(item: unknown): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index 9f5aa65..9d0a4d0 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -135,6 +135,8 @@ describe('BenchContextImpl', () => { { name: 'declaration', method: 'textDocument/declaration' }, { name: 'documentHighlight', method: 'textDocument/documentHighlight' }, { name: 'prepareRename', method: 'textDocument/prepareRename' }, + { name: 'prepareCallHierarchy', method: 'textDocument/prepareCallHierarchy' }, + { name: 'prepareTypeHierarchy', method: 'textDocument/prepareTypeHierarchy' }, ] as const; for (const { name, method } of positionRequests) { @@ -292,6 +294,39 @@ describe('BenchContextImpl', () => { expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); }); + // hierarchy requests that take a raw item from a prior prepare call + const hierarchyItemRequests = [ + { name: 'callHierarchyIncomingCalls', method: 'callHierarchy/incomingCalls' }, + { name: 'callHierarchyOutgoingCalls', method: 'callHierarchy/outgoingCalls' }, + { name: 'typeHierarchySupertypes', method: 'typeHierarchy/supertypes' }, + { name: 'typeHierarchySubtypes', method: 'typeHierarchy/subtypes' }, + ] as const; + + for (const { name, method } of hierarchyItemRequests) { + it(`${name} issues ${method} with the item and records a timing`, async () => { + const item = { + name: 'x', + kind: 13, + uri: 'file:///sample.ts', + range: { start: { line: 0, character: 6 }, end: { line: 0, character: 7 } }, + selectionRange: { start: { line: 0, character: 6 }, end: { line: 0, character: 7 } }, + }; + const res = await ctx[name](item); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe(method); + expect(req.params).toEqual({ item }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe(method); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + } + it('workspaceSymbol issues workspace/symbol with the query and records a timing', async () => { const res = await ctx.workspaceSymbol('Foo'); From d8c1eb1f013eef9700cc0b710f17322cd2cbf4e0 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:05:51 +0100 Subject: [PATCH 07/19] add pull diagnostics and saveDocument Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 5 +++ src/cli.ts | 3 ++ src/context.ts | 24 +++++++++++++++ src/harness.ts | 7 +++++ src/types.ts | 3 ++ test/context.test.ts | 73 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 115 insertions(+) diff --git a/README.md b/README.md index 612e862..486aae9 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ export default async function (ctx: BenchContext) { | --- | --- | | `openDocument(path)` | Send `textDocument/didOpen` | | `closeDocument(path)` | Send `textDocument/didClose` | +| `saveDocument(path)` | Send `textDocument/didSave` (document must be open) | | `hover(path, line, char)` | `textDocument/hover` (timed) | | `completion(path, line, char)` | `textDocument/completion` (timed) | | `definition(path, line, char)` | `textDocument/definition` (timed) | @@ -108,6 +109,8 @@ export default async function (ctx: BenchContext) { | `prepareTypeHierarchy(path, line, char)` | `textDocument/prepareTypeHierarchy` (timed) | | `typeHierarchySupertypes(item)` | `typeHierarchy/supertypes` (timed) | | `typeHierarchySubtypes(item)` | `typeHierarchy/subtypes` (timed) | +| `documentDiagnostic(path, previousResultId?)` | `textDocument/diagnostic` (timed) | +| `workspaceDiagnostic(previousResultIds?)` | `workspace/diagnostic` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | @@ -124,6 +127,8 @@ if (items && items.length > 0) { } ``` +`documentDiagnostic` and `workspaceDiagnostic` only work against servers that expose `diagnosticProvider` in their capabilities. lsbench does not advertise the `textDocument.diagnostic` client capability, since some servers would then stop pushing diagnostics and break `waitForDiagnostics`. + In some cases you may also need to register a language ID for a given extension. That's straightforward to do with `addRegisteredLanguage`, which will then impact all context related actions for documents with a matching extension. diff --git a/src/cli.ts b/src/cli.ts index daf67c6..9d27d10 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -212,6 +212,7 @@ The object passed to your script. Import its type from 'lsbench'. Methods marked Document lifecycle openDocument(path) textDocument/didOpen — must be called before requests on a file closeDocument(path) textDocument/didClose + saveDocument(path) textDocument/didSave (throws if the document is not open) Timed LSP requests (return the raw LSP result, or null on failure) hover(path, line, char) textDocument/hover @@ -245,6 +246,8 @@ Timed LSP requests (return the raw LSP result, or null on failure) prepareTypeHierarchy(path, line, char) textDocument/prepareTypeHierarchy (returns TypeHierarchyItem[]) typeHierarchySupertypes(item) typeHierarchy/supertypes (item from prepareTypeHierarchy) typeHierarchySubtypes(item) typeHierarchy/subtypes (item from prepareTypeHierarchy) + documentDiagnostic(path, prevResultId?) textDocument/diagnostic (needs a server with diagnosticProvider) + workspaceDiagnostic(prevResultIds?) workspace/diagnostic (prevResultIds is [{uri,value}], default []) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index 934848c..3638fe4 100644 --- a/src/context.ts +++ b/src/context.ts @@ -84,6 +84,19 @@ export class BenchContextImpl implements BenchContext { this.log(`Closed ${relativePath}`); } + async saveDocument(relativePath: string): Promise { + const doc = this.openDocuments.get(relativePath); + if (!doc) { + throw new Error(`Document ${relativePath} is not open. Call openDocument() first.`); + } + + this.harness.sendNotification('textDocument/didSave', { + textDocument: { uri: doc.uri }, + }); + + this.log(`Saved ${relativePath}`); + } + // ── Timed LSP requests ────────────────────────────────────────────── async hover(relativePath: string, line: number, character: number): Promise { @@ -298,6 +311,17 @@ export class BenchContextImpl implements BenchContext { return this.timedRequest('typeHierarchy/subtypes', { item }); } + async documentDiagnostic(relativePath: string, previousResultId?: string): Promise { + return this.timedRequest('textDocument/diagnostic', { + textDocument: { uri: this.getUri(relativePath) }, + ...(previousResultId !== undefined ? { previousResultId } : {}), + }); + } + + async workspaceDiagnostic(previousResultIds: { uri: string; value: string }[] = []): Promise { + return this.timedRequest('workspace/diagnostic', { previousResultIds }); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index cb02609..364f357 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -136,6 +136,11 @@ export class LspHarness { return params.items.map(() => ({})); }); + // acknowledge pull diagnostic refresh requests, we never cache pulled results + this.connection.onRequest('workspace/diagnostic/refresh', () => { + return; + }); + // Handle client/registerCapability (dynamic registration) this.connection.onRequest('client/registerCapability', () => { return; // Accept all registrations @@ -376,6 +381,8 @@ export class LspHarness { overlappingTokenSupport: false, multilineTokenSupport: false, }, + // textDocument.diagnostic is intentionally not advertised: some servers switch + // from push to pull diagnostics when it is present, which breaks waitForDiagnostics publishDiagnostics: { relatedInformation: true, tagSupport: { valueSet: [1, 2] }, diff --git a/src/types.ts b/src/types.ts index 4ce004f..b043e5e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -118,6 +118,7 @@ export interface BenchContext { // ── Document lifecycle ────────────────────────────────────────────── openDocument(relativePath: string): Promise; closeDocument(relativePath: string): Promise; + saveDocument(relativePath: string): Promise; // ── Timed LSP requests ────────────────────────────────────────────── hover(relativePath: string, line: number, character: number): Promise; @@ -151,6 +152,8 @@ export interface BenchContext { prepareTypeHierarchy(relativePath: string, line: number, character: number): Promise; typeHierarchySupertypes(item: unknown): Promise; typeHierarchySubtypes(item: unknown): Promise; + documentDiagnostic(relativePath: string, previousResultId?: string): Promise; + workspaceDiagnostic(previousResultIds?: { uri: string; value: string }[]): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test/context.test.ts b/test/context.test.ts index 9d0a4d0..2cab968 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -100,6 +100,24 @@ describe('BenchContextImpl', () => { expect(harness.notifications.some((n) => n.method === 'textDocument/didClose')).toBe(true); }); + it('saveDocument throws when the document is not open', async () => { + await expect(ctx.saveDocument('sample.ts')).rejects.toThrow(/is not open/); + expect(harness.notifications).toHaveLength(0); + }); + + it('saveDocument sends an untimed didSave for an open document', async () => { + await ctx.openDocument('sample.ts'); + await ctx.saveDocument('sample.ts'); + + expect(harness.notifications).toHaveLength(2); + expect(harness.notifications[1]).toEqual({ + method: 'textDocument/didSave', + params: { textDocument: { uri: expect.stringMatching(/sample\.ts$/) } }, + }); + expect(harness.requests).toHaveLength(0); + expect(ctx.collectTimings()).toHaveLength(0); + }); + it('resetDocuments closes every open document and clears state', async () => { await ctx.openDocument('sample.ts'); await ctx.resetDocuments(); @@ -327,6 +345,61 @@ describe('BenchContextImpl', () => { }); } + it('documentDiagnostic issues textDocument/diagnostic without previousResultId when omitted and records a timing', async () => { + await ctx.openDocument('sample.ts'); + const res = await ctx.documentDiagnostic('sample.ts'); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('textDocument/diagnostic'); + expect(req.params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + }); + expect(req.params).not.toHaveProperty('previousResultId'); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/diagnostic'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('documentDiagnostic passes the previous result id when given', async () => { + await ctx.openDocument('sample.ts'); + await ctx.documentDiagnostic('sample.ts', 'result-1'); + + expect(harness.requests).toHaveLength(1); + expect(harness.requests[0].params).toEqual({ + textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, + previousResultId: 'result-1', + }); + }); + + it('workspaceDiagnostic issues workspace/diagnostic with empty previousResultIds by default and records a timing', async () => { + const res = await ctx.workspaceDiagnostic(); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe('workspace/diagnostic'); + expect(req.params).toEqual({ previousResultIds: [] }); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('workspace/diagnostic'); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + + it('workspaceDiagnostic passes the given previousResultIds', async () => { + const previousResultIds = [{ uri: 'file:///sample.ts', value: 'result-1' }]; + await ctx.workspaceDiagnostic(previousResultIds); + + expect(harness.requests).toHaveLength(1); + expect(harness.requests[0].params).toEqual({ previousResultIds }); + }); + it('workspaceSymbol issues workspace/symbol with the query and records a timing', async () => { const res = await ctx.workspaceSymbol('Foo'); From 0e24f6735b3a7ab60bebadfc85019b15cec473a4 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:14:46 +0100 Subject: [PATCH 08/19] fix: addRegisteredLanguage stored extension mapping backwards Co-Authored-By: Claude Opus 5.5 (1M context) --- src/context.ts | 5 +++-- test/context.test.ts | 14 +++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/context.ts b/src/context.ts index 3638fe4..e451a66 100644 --- a/src/context.ts +++ b/src/context.ts @@ -484,11 +484,12 @@ const RegisteredLanguages: Record = { * @param extension That should correlate with the given id (ex. `.ts`, or `.c`, or `.langium`) */ export function addRegisteredLanguage(languageId: string, extension: string) { - extension = extension.trim(); + // normalize to match detectLanguageId, which looks up lowercased extensions + extension = extension.trim().toLowerCase(); if (!extension.startsWith('.')) { extension = '.' + extension; } - RegisteredLanguages[languageId] = extension; + RegisteredLanguages[extension] = languageId; } /** diff --git a/test/context.test.ts b/test/context.test.ts index 2cab968..7e821a8 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -2,7 +2,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import type { Diagnostic, LspHarness } from 'lsbench'; -import { BenchContextImpl } from 'lsbench'; +import { addRegisteredLanguage, BenchContextImpl } from 'lsbench'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; interface SentRequest { @@ -85,6 +85,18 @@ describe('BenchContextImpl', () => { expect(params.textDocument.text).toContain('const x'); }); + it('sends didOpen with the languageId of a registered custom extension', async () => { + // register with mixed case and no leading dot to exercise normalization + addRegisteredLanguage('minilogo', 'LoGo'); + fs.writeFileSync(path.join(tmpDir, 'sample.LOGO'), 'pen down\n', 'utf-8'); + + await ctx.openDocument('sample.LOGO'); + + expect(harness.notifications).toHaveLength(1); + const params = harness.notifications[0].params as { textDocument: { languageId: string } }; + expect(params.textDocument.languageId).toBe('minilogo'); + }); + it('is idempotent — opening the same document twice sends one didOpen', async () => { await ctx.openDocument('sample.ts'); await ctx.openDocument('sample.ts'); From bf9a7baac6931d611e6793719758f5aa9cc16aef Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:15:10 +0100 Subject: [PATCH 09/19] changelog: unreleased LSP command additions Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a908d4f..0f98361 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # CHANGELOG +## Unreleased + +Adds many more LSP requests to `BenchContext`, plus a fix for `addRegisteredLanguage`. + +### New BenchContext methods + +- **Navigation:** `declaration`, `documentHighlight`, `prepareRename` +- **Formatting:** `rangeFormatting`, `onTypeFormatting` +- **Document structure:** `foldingRange`, `selectionRange`, `documentLink`, `codeLens`, `inlayHint` +- **Semantic tokens:** `semanticTokensFull`, `semanticTokensRange`, `semanticTokensDelta` +- **Workspace symbols:** `workspaceSymbol` +- **Call/type hierarchy:** `prepareCallHierarchy`, `callHierarchyIncomingCalls`, `callHierarchyOutgoingCalls`, `prepareTypeHierarchy`, `typeHierarchySupertypes`, `typeHierarchySubtypes` +- **Pull diagnostics:** `documentDiagnostic`, `workspaceDiagnostic`. The `textDocument.diagnostic` client capability is intentionally not advertised, since some servers switch from push to pull diagnostics when it is present, which would break `waitForDiagnostics`. +- **Document lifecycle:** `saveDocument` + +### Fixes + +- `addRegisteredLanguage` stored the extension mapping backwards (language id to extension instead of extension to language id). Extensions are now also lowercased to match `detectLanguageId`. + ## v0.1.0 First release! From 3bf7b46dc165213d1921280a62091390545cf5da Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:19:09 +0100 Subject: [PATCH 10/19] answer server-to-client refresh, progress, showMessageRequest, applyEdit requests Co-Authored-By: Claude Opus 5.5 (1M context) --- src/harness.ts | 28 ++++++++++++++++++++ test/harness.test.ts | 63 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/src/harness.ts b/src/harness.ts index 364f357..8860d29 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -141,11 +141,39 @@ export class LspHarness { return; }); + // acknowledge refresh and progress requests, we hold no cached state to invalidate + const noOpRequests = [ + 'workspace/semanticTokens/refresh', + 'workspace/inlayHint/refresh', + 'workspace/codeLens/refresh', + 'workspace/inlineValue/refresh', + 'window/workDoneProgress/create', + ]; + for (const method of noOpRequests) { + this.connection.onRequest(method, () => null); + } + // Handle client/registerCapability (dynamic registration) this.connection.onRequest('client/registerCapability', () => { return; // Accept all registrations }); + this.connection.onRequest('client/unregisterCapability', () => { + return; + }); + + // no user is present to pick an action, so dismiss the prompt + this.connection.onRequest('window/showMessageRequest', (params: { type: number; message: string }) => { + this.log(`[server msg request] ${params.message}`); + return null; + }); + + // lsbench never mutates the workspace on the server's behalf + this.connection.onRequest('workspace/applyEdit', (params: { label?: string }) => { + this.log(`[server applyEdit] declined${params.label ? `: ${params.label}` : ''}`); + return { applied: false, failureReason: 'lsbench does not apply workspace edits' }; + }); + // Perform LSP initialize const workspaceUri = pathToUri(this.workspaceRoot); diff --git a/test/harness.test.ts b/test/harness.test.ts index 80bc038..f6a9de3 100644 --- a/test/harness.test.ts +++ b/test/harness.test.ts @@ -1,5 +1,5 @@ import * as path from 'node:path'; -import { pathToUri, uriToPath } from 'lsbench'; +import { LspHarness, pathToUri, uriToPath } from 'lsbench'; import { describe, expect, it } from 'vitest'; describe('pathToUri', () => { @@ -30,3 +30,64 @@ describe('pathToUri / uriToPath round-trip', () => { expect(uriToPath(pathToUri(abs))).toBe(abs); }); }); + +/** + * A fake server that, while handling initialize, sends each server-to-client request + * and reports the client's replies back through its capabilities. + */ +const probeServer = ` +import * as rpc from 'vscode-jsonrpc/node'; +const conn = rpc.createMessageConnection( + new rpc.StreamMessageReader(process.stdin), + new rpc.StreamMessageWriter(process.stdout), +); +const probes = JSON.parse(process.argv[1]); +conn.onRequest('initialize', async () => { + const replies = {}; + for (const [method, params] of probes) { + try { + replies[method] = { result: await conn.sendRequest(method, params) }; + } catch (err) { + replies[method] = { error: err.code }; + } + } + return { capabilities: { replies } }; +}); +conn.onRequest('shutdown', () => null); +conn.onNotification('exit', () => process.exit(0)); +conn.listen(); +`; + +describe('LspHarness server-to-client requests', () => { + it('answers requests the advertised client capabilities can trigger', async () => { + const probes: Array<[string, unknown]> = [ + ['workspace/semanticTokens/refresh', null], + ['workspace/inlayHint/refresh', null], + ['workspace/codeLens/refresh', null], + ['workspace/inlineValue/refresh', null], + ['window/workDoneProgress/create', { token: 'tok' }], + ['client/unregisterCapability', { unregisterations: [] }], + ['window/showMessageRequest', { type: 3, message: 'pick one', actions: [{ title: 'ok' }] }], + ['workspace/applyEdit', { edit: { changes: {} } }], + ]; + const harness = new LspHarness( + { + command: process.execPath, + args: ['--input-type=module', '-e', probeServer, JSON.stringify(probes)], + }, + process.cwd(), + ); + try { + await harness.start(); + const replies = harness.capabilities?.replies as Record; + for (const [method] of probes.slice(0, -1)) { + expect(replies[method], method).toEqual({ result: null }); + } + expect(replies['workspace/applyEdit']).toEqual({ + result: { applied: false, failureReason: expect.any(String) }, + }); + } finally { + await harness.stop(); + } + }); +}); From 0228a4f6e83ee1ae954d31cb0a516419dfb18760 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:21:01 +0100 Subject: [PATCH 11/19] integration: cover new methods minilogo supports, skip the rest Co-Authored-By: Claude Opus 5.5 (1M context) --- test-integration/minilogo.test.ts | 154 +++++++++++++++++++++++++++++- 1 file changed, 153 insertions(+), 1 deletion(-) diff --git a/test-integration/minilogo.test.ts b/test-integration/minilogo.test.ts index 1ca7d75..edfcd33 100644 --- a/test-integration/minilogo.test.ts +++ b/test-integration/minilogo.test.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { addRegisteredLanguage, BenchContextImpl, LspHarness, type ServerConfig } from 'lsbench'; +import { addRegisteredLanguage, BenchContextImpl, LspHarness, type RequestTiming, type ServerConfig } from 'lsbench'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { examplesDir, serverEntry } from './minilogo.js'; @@ -13,10 +13,34 @@ import { examplesDir, serverEntry } from './minilogo.js'; // 9: def square(x, y, scale) { <- definition of `square` // 24: square(100,100,300) <- a reference/call to `square` // 33: square(x * 30, ...) <- another reference/call to `square` +// 29: for x = 0 to 10 { <- outer loop, folds to line 34 +// 30: for y = 0 to 10 { <- inner loop, folds to line 33 // register minilogo up-front addRegisteredLanguage('minilogo', '.logo'); +/** a minimal LSP range shape for asserting on results */ +type LspRange = { start: { line: number; character: number }; end: { line: number; character: number } }; + +/** drain recorded timings and return the single entry for `method` */ +function timingFor(ctx: BenchContextImpl, method: string): RequestTiming | undefined { + let found: RequestTiming | undefined; + for (const timing of ctx.collectTimings()) { + if (timing.method === method) { + found = timing; + } + } + return found; +} + +/** assert the last request for `method` was timed and succeeded */ +function expectTimedSuccess(ctx: BenchContextImpl, method: string): void { + const timing = timingFor(ctx, method); + expect(timing, `no timing recorded for ${method}`).toBeTruthy(); + expect(timing?.success, timing?.error).toBe(true); + expect(timing?.duration_ms).toBeGreaterThanOrEqual(0); +} + function serverConfig(): ServerConfig { return { command: 'node', @@ -89,6 +113,134 @@ describe('minilogo language server (integration)', () => { // that the request round-trips successfully (null is an acceptable "no hover") expect(hover === null || typeof hover === 'object').toBe(true); }); + + // ── methods added on this branch ──────────────────────────────────── + + it('highlights `square` at its definition and both call sites', async () => { + ctx.collectTimings(); + const highlights = (await ctx.documentHighlight('test.logo', 9, 6)) as Array<{ range: LspRange }> | null; + expectTimedSuccess(ctx, 'textDocument/documentHighlight'); + + expect(Array.isArray(highlights)).toBe(true); + const starts = (highlights ?? []).map((h) => `${h.range.start.line}:${h.range.start.character}`); + expect(starts).toEqual(expect.arrayContaining(['9:4', '24:0', '33:8'])); + expect(starts).toHaveLength(3); + }); + + it('prepares a rename covering the `square` identifier', async () => { + ctx.collectTimings(); + const result = (await ctx.prepareRename('test.logo', 9, 6)) as LspRange | { range: LspRange } | null; + expectTimedSuccess(ctx, 'textDocument/prepareRename'); + + expect(result).toBeTruthy(); + // servers may return a bare Range or { range, placeholder } + const range = result && 'range' in result ? result.range : (result as LspRange); + expect(range.start).toEqual({ line: 9, character: 4 }); + expect(range.end).toEqual({ line: 9, character: 10 }); + }); + + it('returns folding ranges for the multi-line def, loops, and header comment', async () => { + ctx.collectTimings(); + const ranges = (await ctx.foldingRange('test.logo')) as Array<{ + startLine: number; + endLine: number; + kind?: string; + }> | null; + expectTimedSuccess(ctx, 'textDocument/foldingRange'); + + expect(Array.isArray(ranges)).toBe(true); + expect(ranges?.length).toBeGreaterThan(0); + const spans = (ranges ?? []).map((r) => `${r.startLine}-${r.endLine}`); + // `def square` body spans lines 9..22, folded up to the line before `}` + expect(spans).toContain('9-21'); + expect(spans).toContain('29-34'); + expect(spans).toContain('30-33'); + let comment: { startLine: number; kind?: string } | undefined; + for (const r of ranges ?? []) { + if (r.kind === 'comment') { + comment = r; + } + } + expect(comment?.startLine).toBe(0); + }); + + it('finds `square` via workspace symbols across the examples', async () => { + ctx.collectTimings(); + const symbols = (await ctx.workspaceSymbol('square')) as Array<{ + name: string; + location: { uri: string; range: LspRange }; + }> | null; + expectTimedSuccess(ctx, 'workspace/symbol'); + + expect(Array.isArray(symbols)).toBe(true); + let inTestLogo: { location: { range: LspRange } } | undefined; + for (const symbol of symbols ?? []) { + expect(symbol.name).toBe('square'); + if (symbol.location.uri.endsWith('/test.logo')) { + inTestLogo = symbol; + } + } + expect(inTestLogo?.location.range.start).toEqual({ line: 9, character: 4 }); + }); + + it('sends didSave as an untimed notification and the server stays responsive', async () => { + ctx.collectTimings(); + // minilogo advertises textDocumentSync.save = false, so it ignores didSave; + // this checks the client side: no throw, no timing, and the server still answers + await ctx.saveDocument('test.logo'); + expect(ctx.collectTimings()).toHaveLength(0); + + const highlights = (await ctx.documentHighlight('test.logo', 24, 2)) as unknown[] | null; + expect(highlights).toHaveLength(3); + + await expect(ctx.saveDocument('not-open.logo')).rejects.toThrow(/not open/); + }); + + // the following methods are not advertised by minilogo (Langium 4.3 minilogo only + // registers the providers listed in its initialize result), so they are skipped + // rather than asserting on "Unhandled method" errors + it('does not advertise the providers whose tests are skipped below', () => { + const caps = harness.capabilities as Record | null; + // if any of these start being advertised, un-skip the matching test below + for (const key of [ + 'declarationProvider', + 'documentRangeFormattingProvider', + 'documentOnTypeFormattingProvider', + 'selectionRangeProvider', + 'documentLinkProvider', + 'codeLensProvider', + 'inlayHintProvider', + 'semanticTokensProvider', + 'callHierarchyProvider', + 'typeHierarchyProvider', + 'diagnosticProvider', + ]) { + expect(caps?.[key] ?? false, key).toBeFalsy(); + } + }); + + // missing capability: declarationProvider is false + it.skip('declaration'); + // missing capability: documentRangeFormattingProvider is false + it.skip('rangeFormatting'); + // missing capability: no documentOnTypeFormattingProvider + it.skip('onTypeFormatting'); + // missing capability: no selectionRangeProvider + it.skip('selectionRange'); + // missing capability: no documentLinkProvider + it.skip('documentLink'); + // missing capability: no codeLensProvider + it.skip('codeLens'); + // missing capability: no inlayHintProvider + it.skip('inlayHint'); + // missing capability: no semanticTokensProvider (covers full, range, and delta) + it.skip('semanticTokensFull / semanticTokensRange / semanticTokensDelta'); + // missing capability: no callHierarchyProvider + it.skip('prepareCallHierarchy / callHierarchyIncomingCalls / callHierarchyOutgoingCalls'); + // missing capability: no typeHierarchyProvider + it.skip('prepareTypeHierarchy / typeHierarchySupertypes / typeHierarchySubtypes'); + // missing capability: no diagnosticProvider (minilogo only pushes diagnostics) + it.skip('documentDiagnostic / workspaceDiagnostic'); }); describe('runBenchmark against minilogo (integration)', () => { From 1808905599ac26e1c43e787fd399343a7cb2bc91 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:30:16 +0100 Subject: [PATCH 12/19] integration: add Langium grammar LS suite, fix stop() never force-killing Co-Authored-By: Claude Opus 5.5 (1M context) --- knip.json | 1 + package-lock.json | 187 ++++++- package.json | 4 +- src/harness.ts | 17 +- test-integration/langium-grammar-server.ts | 10 + test-integration/langium-grammar.test.ts | 512 ++++++++++++++++++ .../langium-grammar/shapes.langium | 58 ++ test/harness.test.ts | 38 ++ 8 files changed, 818 insertions(+), 9 deletions(-) create mode 100644 test-integration/langium-grammar-server.ts create mode 100644 test-integration/langium-grammar.test.ts create mode 100644 test-integration/langium-grammar/shapes.langium diff --git a/knip.json b/knip.json index 9b20449..56cef82 100644 --- a/knip.json +++ b/knip.json @@ -1,5 +1,6 @@ { "$schema": "https://unpkg.com/knip@5/schema.json", + "entry": ["test-integration/langium-grammar-server.ts"], "ignore": ["examples/**", "demo/script.ts"], "ignoreBinaries": [], "vitest": { diff --git a/package-lock.json b/package-lock.json index 022ea74..d9f214d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,9 +19,11 @@ "@biomejs/biome": "^2.5.8", "@types/node": "^24.13.3", "knip": "^6.32.1", + "langium": "~4.3.0", "oxlint": "^1.78.0", "typescript": "^5.5.0", - "vitest": "^4.1.10" + "vitest": "^4.1.10", + "vscode-languageserver": "~10.0.1" }, "engines": { "node": ">=24.0.0" @@ -202,6 +204,48 @@ "node": ">=14.21.3" } }, + "node_modules/@chevrotain/cst-dts-gen": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-12.0.0.tgz", + "integrity": "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/gast": "12.0.0", + "@chevrotain/types": "12.0.0" + } + }, + "node_modules/@chevrotain/gast": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-12.0.0.tgz", + "integrity": "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/types": "12.0.0" + } + }, + "node_modules/@chevrotain/regexp-to-ast": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-12.0.0.tgz", + "integrity": "sha512-p+EW9MaJwgaHguhoqwOtx/FwuGr+DnNn857sXWOi/mClXIkPGl3rn7hGNWvo31HA3vyeQxjqe+H36yZJwYU8cA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/types": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-12.0.0.tgz", + "integrity": "sha512-S+04vjFQKeuYw0/eW3U52LkAHQsB1ASxsPGsLPUyQgrZ2iNNibQrsidruDzjEX2JYfespXMG0eZmXlhA6z7nWA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/utils": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz", + "integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@emnapi/core": { "version": "1.11.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", @@ -1749,6 +1793,36 @@ "node": ">=18" } }, + "node_modules/chevrotain": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-12.0.0.tgz", + "integrity": "sha512-csJvb+6kEiQaqo1woTdSAuOWdN0WTLIydkKrBnS+V5gZz0oqBrp4kQ35519QgK6TpBThiG3V1vNSHlIkv4AglQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/cst-dts-gen": "12.0.0", + "@chevrotain/gast": "12.0.0", + "@chevrotain/regexp-to-ast": "12.0.0", + "@chevrotain/types": "12.0.0", + "@chevrotain/utils": "12.0.0" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/chevrotain-allstar": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.4.4.tgz", + "integrity": "sha512-HKjrnG6rGOkaxoOx8B4oKRYoD8Gdt6wCL5ItwAtZPgS5kI6rKyezUyWKCFVr6nLYQXT6/BLVVp5b00xBbnjakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash-es": "^4.18.1" + }, + "peerDependencies": { + "chevrotain": "^12.0.0" + } + }, "node_modules/commander": { "version": "14.0.3", "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", @@ -1923,6 +1997,27 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/langium": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/langium/-/langium-4.3.1.tgz", + "integrity": "sha512-4lmkLHytLXD5pvyL0PKUj1LCNpgzv9s8luH+GbWXHG45QLmO6PlFXrCUghDN5BfcFTlaQyXpXiaSl8A28Xep8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@chevrotain/regexp-to-ast": "~12.0.0", + "chevrotain": "~12.0.0", + "chevrotain-allstar": "~0.4.3", + "vscode-languageserver": "~10.0.1", + "vscode-languageserver-protocol": "~3.18.1", + "vscode-languageserver-textdocument": "~1.0.13", + "vscode-languageserver-types": "~3.18.0", + "vscode-uri": "~3.1.0" + }, + "engines": { + "node": ">=20.10.0", + "npm": ">=10.2.3" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -2196,6 +2291,13 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "dev": true, + "license": "MIT" + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -2784,6 +2886,89 @@ "node": ">=14.0.0" } }, + "node_modules/vscode-languageserver": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-10.0.1.tgz", + "integrity": "sha512-hfERoZvpaHWzQa7t5mMIrHkEOhF7aTs1dpktem0TW/Xs4QZD7NtcHjIq/aE1CZJEj6Rb8LSGUkBhvTRDdpyGig==", + "dev": true, + "license": "MIT", + "dependencies": { + "vscode-languageserver-protocol": "3.18.1" + }, + "bin": { + "installServerIntoExtension": "bin/installServerIntoExtension" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.5.tgz", + "integrity": "sha512-FW4fBMzZ99N8xeob4py0l050wgCoRgTpEq5Xcsb9lM1bc29UKGR/wSV+4knaqFxssFHajy7OzNiKP/m3U1ZEuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "10.0.0", + "vscode-languageserver-types": "3.18.5" + } + }, + "node_modules/vscode-languageserver-protocol/node_modules/vscode-jsonrpc": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.0.tgz", + "integrity": "sha512-USSfxg0vDIpTQqlQBGxF3mBARyoS8cU7LHLpbYNh6dOJt32dlskxPWB0Irrh5TllTmyf7oNLAvqDqzklbwwnpA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz", + "integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.5.tgz", + "integrity": "sha512-kPd6+JQNz3HMJvjKlqUxERSlZHAntl/aGpsk7ImwIh0ewDKDcjgAEyVSYciPiOJD3ftbK9IrfiqUeTZLSbCizw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-languageserver/node_modules/vscode-jsonrpc": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-9.0.0.tgz", + "integrity": "sha512-+VvMmQPJhtvJ+8O+zu2JKIRiLxXF8NW7krWgyMGeOHrp4Cn23T5hc0v2LknNeopDOB70wghHAds7mKtcZ0I4Sg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageserver/node_modules/vscode-languageserver-protocol": { + "version": "3.18.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.1.tgz", + "integrity": "sha512-RTiiVHdpxpYcJVI5sq6S5TLjQ4WDR/rBrIWru+kPXe6sGQ9PFQ3GamrTKLvPqbR4ylr1SoodhmcqbFII0WXVuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "9.0.0", + "vscode-languageserver-types": "3.18.0" + } + }, + "node_modules/vscode-languageserver/node_modules/vscode-languageserver-types": { + "version": "3.18.0", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.0.tgz", + "integrity": "sha512-8TsGPNMIMiiBdkORgRSvLjuiEIiAFtO+KssmYWxQ+uSVvlf7RjK8YKCOjPzZ+YA04jXEV7+7LvkSmHkhpNS99g==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, "node_modules/walk-up-path": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz", diff --git a/package.json b/package.json index 13db405..a4da300 100644 --- a/package.json +++ b/package.json @@ -57,9 +57,11 @@ "@biomejs/biome": "^2.5.8", "@types/node": "^24.13.3", "knip": "^6.32.1", + "langium": "~4.3.0", "oxlint": "^1.78.0", "typescript": "^5.5.0", - "vitest": "^4.1.10" + "vitest": "^4.1.10", + "vscode-languageserver": "~10.0.1" }, "engines": { "node": ">=24.0.0" diff --git a/src/harness.ts b/src/harness.ts index 8860d29..e64eb75 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -217,20 +217,23 @@ export class LspHarness { this.connection.dispose(); this.connection = null; - if (this.process && !this.process.killed) { - this.process.kill('SIGTERM'); - // Give it a moment, then force kill + // `killed` only reports that a signal was sent, so check whether the process + // actually exited; otherwise a server ignoring SIGTERM is never force killed + const child = this.process; + const hasExited = () => child !== null && (child.exitCode !== null || child.signalCode !== null); + if (child && !hasExited()) { await new Promise((resolve) => { + // give it a moment after SIGTERM, then force kill and wait for the exit const timer = setTimeout(() => { - if (this.process && !this.process.killed) { - this.process.kill('SIGKILL'); + if (!hasExited()) { + child.kill('SIGKILL'); } - resolve(); }, 3000); - this.process?.on('exit', () => { + child.once('exit', () => { clearTimeout(timer); resolve(); }); + child.kill('SIGTERM'); }); } this.process = null; diff --git a/test-integration/langium-grammar-server.ts b/test-integration/langium-grammar-server.ts new file mode 100644 index 0000000..d1f24bd --- /dev/null +++ b/test-integration/langium-grammar-server.ts @@ -0,0 +1,10 @@ +import { createLangiumGrammarServices } from 'langium/grammar'; +import { startLanguageServer } from 'langium/lsp'; +import { NodeFileSystem } from 'langium/node'; +import { createConnection, ProposedFeatures } from 'vscode-languageserver/node'; + +// Langium's own grammar language server over stdio, used as a feature-rich +// integration target. node runs this file directly via type stripping. +const connection = createConnection(ProposedFeatures.all); +const { shared } = createLangiumGrammarServices({ connection, ...NodeFileSystem }); +startLanguageServer(shared); diff --git a/test-integration/langium-grammar.test.ts b/test-integration/langium-grammar.test.ts new file mode 100644 index 0000000..b924048 --- /dev/null +++ b/test-integration/langium-grammar.test.ts @@ -0,0 +1,512 @@ +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { addRegisteredLanguage, BenchContextImpl, LspHarness, type RequestTiming } from 'lsbench'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +// End-to-end test against Langium's own grammar language server, which registers +// far more providers than minilogo (formatter, semantic tokens, call and type +// hierarchy, code actions, ...). The server is a tiny entry script that node runs +// directly via type stripping, so no build step is needed. +// +// shapes.langium (0-indexed lines) that we target: +// 0: /* <- header comment, folds to line 2 +// 11: interface Shape extends NamedElement <- `Shape` at 10..15, documented on line 10 +// 19: interface Rectangle extends Shape{ <- deliberately unformatted +// 25: members: @Shape[]; <- a reference to `Shape` at 14..19 +// 36: 'drawing' name=ID elements+=ElementRule*; <- call to `ElementRule` at 32..43 +// 38: ElementRule returns Element: <- calls CircleRule on line 39 +// 41: CircleRule returns Circle: <- calls ID, colorFragment, NUMBER on line 42 +// 44: RectangleRule returns Rectangle : <- deliberately unformatted +// 50: fragment colorFragment: <- lowercase, raises `rule-name-uppercase` + +const here = path.dirname(fileURLToPath(import.meta.url)); +const serverEntry = path.join(here, 'langium-grammar-server.ts'); +const workspaceDir = path.join(here, 'langium-grammar'); +const FILE = 'shapes.langium'; + +// `.langium` is registered by default, this keeps the suite explicit about it +addRegisteredLanguage('langium', '.langium'); + +/** a minimal LSP range shape for asserting on results */ +type LspRange = { start: { line: number; character: number }; end: { line: number; character: number } }; +type TextEdit = { range: LspRange; newText: string }; +type HierarchyItem = { name: string; kind: number; uri: string; range: LspRange; selectionRange: LspRange }; + +/** drain recorded timings and return the last entry for `method` */ +function timingFor(ctx: BenchContextImpl, method: string): RequestTiming | undefined { + let found: RequestTiming | undefined; + for (const timing of ctx.collectTimings()) { + if (timing.method === method) { + found = timing; + } + } + return found; +} + +/** assert the last request for `method` was timed and succeeded */ +function expectTimedSuccess(ctx: BenchContextImpl, method: string): void { + const timing = timingFor(ctx, method); + expect(timing, `no timing recorded for ${method}`).toBeTruthy(); + expect(timing?.success, timing?.error).toBe(true); + expect(timing?.duration_ms).toBeGreaterThanOrEqual(0); +} + +/** `line:character` of a range start, for compact assertions */ +function startOf(range: LspRange): string { + return `${range.start.line}:${range.start.character}`; +} + +describe('langium grammar language server (integration)', () => { + let harness: LspHarness; + let ctx: BenchContextImpl; + let initialDiagnostics: Array<{ message: string; range: LspRange; data?: { code?: string } }>; + + beforeAll(async () => { + harness = new LspHarness( + { command: 'node', args: [serverEntry, '--stdio'] }, + workspaceDir, + Boolean(process.env.LSBENCH_VERBOSE), + ); + await harness.start(); + ctx = new BenchContextImpl(harness, workspaceDir, Boolean(process.env.LSBENCH_VERBOSE)); + + await ctx.openDocument(FILE); + // let the builder run so cross-references resolve before we query + initialDiagnostics = (await ctx.waitForDiagnostics(FILE, 30_000)) as typeof initialDiagnostics; + }); + + afterAll(async () => { + await harness?.stop(); + }); + + it('reports the initialized server capabilities', () => { + const caps = harness.capabilities; + console.log('[langium-grammar] advertised capabilities:\n' + JSON.stringify(caps, null, 2)); + expect(caps).not.toBeNull(); + for (const key of [ + 'completionProvider', + 'definitionProvider', + 'referencesProvider', + 'documentSymbolProvider', + 'documentHighlightProvider', + 'hoverProvider', + 'renameProvider', + 'codeActionProvider', + 'documentFormattingProvider', + 'documentRangeFormattingProvider', + 'foldingRangeProvider', + 'semanticTokensProvider', + 'callHierarchyProvider', + 'typeHierarchyProvider', + 'workspaceSymbolProvider', + ]) { + expect(caps?.[key], key).toBeTruthy(); + } + }); + + it('publishes only the lowercase fragment warning for the fixture', () => { + expect(initialDiagnostics).toHaveLength(1); + const [warning] = initialDiagnostics; + expect(warning.data?.code).toBe('rule-name-uppercase'); + expect(startOf(warning.range)).toBe('50:9'); + }); + + it('produces a document symbol tree rooted at the grammar', async () => { + ctx.collectTimings(); + const symbols = (await ctx.documentSymbol(FILE)) as Array<{ + name: string; + children?: Array<{ name: string }>; + }> | null; + expectTimedSuccess(ctx, 'textDocument/documentSymbol'); + + expect(symbols).toHaveLength(1); + expect(symbols?.[0].name).toBe('Shapes'); + const names = (symbols?.[0].children ?? []).map((s) => s.name); + expect(names).toEqual( + expect.arrayContaining(['NamedElement', 'Shape', 'Element', 'DrawingRule', 'colorFragment', 'ID']), + ); + }); + + it('hovers a `Shape` reference with its doc comment', async () => { + ctx.collectTimings(); + const hover = (await ctx.hover(FILE, 25, 15)) as { contents: { kind: string; value: string } } | null; + expectTimedSuccess(ctx, 'textDocument/hover'); + + expect(hover?.contents.kind).toBe('markdown'); + expect(hover?.contents.value).toContain('A drawable element with an optional color.'); + }); + + it('completes the `ElementRule` call from its prefix', async () => { + ctx.collectTimings(); + // cursor right after the `E` of `ElementRule` on line 36 + const result = (await ctx.completion(FILE, 36, 33)) as { items: Array<{ label: string }> } | null; + expectTimedSuccess(ctx, 'textDocument/completion'); + + const labels = (result?.items ?? []).map((i) => i.label); + expect(labels).toContain('ElementRule'); + }); + + it('resolves go-to-definition from a rule call to the rule', async () => { + type LocationLink = { targetUri: string; targetSelectionRange: LspRange }; + ctx.collectTimings(); + const result = (await ctx.definition(FILE, 36, 35)) as LocationLink[] | null; + expectTimedSuccess(ctx, 'textDocument/definition'); + + expect(result).toHaveLength(1); + expect(result?.[0].targetUri).toContain(FILE); + expect(result?.[0].targetSelectionRange).toEqual({ + start: { line: 38, character: 0 }, + end: { line: 38, character: 11 }, + }); + }); + + it('finds the declaration and every reference to `Shape`', async () => { + ctx.collectTimings(); + const refs = (await ctx.references(FILE, 11, 12)) as Array<{ uri: string; range: LspRange }> | null; + expectTimedSuccess(ctx, 'textDocument/references'); + + const starts = (refs ?? []).map((r) => startOf(r.range)); + expect(starts).toEqual(['11:10', '15:25', '19:30', '25:14', '48:34']); + }); + + it('highlights every occurrence of `Shape`', async () => { + ctx.collectTimings(); + const highlights = (await ctx.documentHighlight(FILE, 25, 15)) as Array<{ range: LspRange }> | null; + expectTimedSuccess(ctx, 'textDocument/documentHighlight'); + + const starts = (highlights ?? []).map((h) => startOf(h.range)); + expect(starts).toEqual(['11:10', '15:25', '19:30', '25:14', '48:34']); + }); + + it('prepares a rename covering the `Shape` identifier', async () => { + ctx.collectTimings(); + const result = (await ctx.prepareRename(FILE, 11, 12)) as LspRange | { range: LspRange } | null; + expectTimedSuccess(ctx, 'textDocument/prepareRename'); + + expect(result).toBeTruthy(); + // servers may return a bare Range or { range, placeholder } + const range = result && 'range' in result ? result.range : (result as LspRange); + expect(range).toEqual({ start: { line: 11, character: 10 }, end: { line: 11, character: 15 } }); + }); + + it('renames `Shape` at its declaration and every reference', async () => { + ctx.collectTimings(); + const result = (await ctx.rename(FILE, 11, 12, 'Figure')) as { + changes: Record; + } | null; + expectTimedSuccess(ctx, 'textDocument/rename'); + + const uris = Object.keys(result?.changes ?? {}); + expect(uris).toHaveLength(1); + expect(uris[0]).toContain(FILE); + const edits = result?.changes[uris[0]] ?? []; + expect(edits.map((e) => startOf(e.range))).toEqual(['11:10', '15:25', '19:30', '25:14', '48:34']); + for (const edit of edits) { + expect(edit.newText).toBe('Figure'); + } + }); + + it('formats the deliberately unformatted lines', async () => { + ctx.collectTimings(); + const edits = (await ctx.formatting(FILE)) as TextEdit[] | null; + expectTimedSuccess(ctx, 'textDocument/formatting'); + + expect(edits?.length).toBeGreaterThan(0); + // collapses the extra spaces in `Rectangle extends` and `RectangleRule returns` + expect(edits).toContainEqual({ + range: { start: { line: 19, character: 19 }, end: { line: 19, character: 22 } }, + newText: ' ', + }); + expect(edits).toContainEqual({ + range: { start: { line: 44, character: 13 }, end: { line: 44, character: 16 } }, + newText: ' ', + }); + }); + + it('formats only within the requested range', async () => { + ctx.collectTimings(); + // the unformatted `interface Rectangle` block + const edits = (await ctx.rangeFormatting(FILE, { + start: { line: 19, character: 0 }, + end: { line: 22, character: 1 }, + })) as TextEdit[] | null; + expectTimedSuccess(ctx, 'textDocument/rangeFormatting'); + + expect(edits?.length).toBeGreaterThan(0); + for (const edit of edits ?? []) { + expect(edit.range.start.line).toBeGreaterThanOrEqual(19); + expect(edit.range.end.line).toBeLessThanOrEqual(22); + } + expect(edits).toContainEqual({ + range: { start: { line: 19, character: 19 }, end: { line: 19, character: 22 } }, + newText: ' ', + }); + }); + + it('answers code actions, and offers a quickfix when given the raw diagnostic', async () => { + const range = initialDiagnostics[0].range; + ctx.collectTimings(); + // Langium carries its issue code in `data.code` rather than `code`, so this + // filter matches nothing and no diagnostics are forwarded to the server + const filtered = await ctx.codeAction(FILE, range, ['rule-name-uppercase']); + expectTimedSuccess(ctx, 'textDocument/codeAction'); + expect(filtered).toEqual([]); + + // sending the published diagnostic through `request` yields the quickfix + const actions = await ctx.request }; + }> | null>( + 'textDocument/codeAction', + { + textDocument: { uri: `file://${path.join(workspaceDir, FILE)}` }, + range, + context: { diagnostics: initialDiagnostics }, + }, + 'quickfix', + ); + const timing = timingFor(ctx, 'textDocument/codeAction'); + expect(timing?.label).toBe('quickfix'); + expect(timing?.success, timing?.error).toBe(true); + + expect(actions).toHaveLength(1); + expect(actions?.[0].kind).toBe('quickfix'); + const edits = Object.values(actions?.[0].edit.changes ?? {})[0]; + expect(edits).toEqual([ + { range: { start: { line: 50, character: 9 }, end: { line: 50, character: 10 } }, newText: 'C' }, + ]); + }); + + it('returns folding ranges for the interfaces and the header comment', async () => { + ctx.collectTimings(); + const ranges = (await ctx.foldingRange(FILE)) as Array<{ + startLine: number; + endLine: number; + kind?: string; + }> | null; + expectTimedSuccess(ctx, 'textDocument/foldingRange'); + + const spans = (ranges ?? []).map((r) => `${r.startLine}-${r.endLine}${r.kind ? `:${r.kind}` : ''}`); + expect(spans).toEqual( + expect.arrayContaining(['0-2:comment', '6-7', '11-12', '15-16', '19-21', '24-25', '30-32']), + ); + }); + + describe('semantic tokens', () => { + /** decode relative token data into `line:char type` entries using the advertised legend */ + function decode(data: number[]): string[] { + const caps = harness.capabilities?.semanticTokensProvider as { legend: { tokenTypes: string[] } }; + const types = caps.legend.tokenTypes; + const tokens: string[] = []; + let line = 0; + let character = 0; + for (let i = 0; i < data.length; i += 5) { + if (data[i] > 0) { + line += data[i]; + character = data[i + 1]; + } else { + character += data[i + 1]; + } + tokens.push(`${line}:${character} ${types[data[i + 3]]}`); + } + return tokens; + } + + it('returns full tokens with a resultId', async () => { + ctx.collectTimings(); + const result = (await ctx.semanticTokensFull(FILE)) as { resultId?: string; data: number[] } | null; + expectTimedSuccess(ctx, 'textDocument/semanticTokens/full'); + + expect(typeof result?.resultId).toBe('string'); + expect(result?.data.length).toBeGreaterThan(0); + expect((result?.data.length ?? 0) % 5).toBe(0); + const tokens = decode(result?.data ?? []); + // `name` property and `string` type in NamedElement, a `Shape` cross-reference type + expect(tokens).toEqual(expect.arrayContaining(['7:4 property', '7:10 type', '25:14 type'])); + }); + + it('returns only the tokens within a range', async () => { + ctx.collectTimings(); + const result = (await ctx.semanticTokensRange(FILE, { + start: { line: 35, character: 0 }, + end: { line: 40, character: 0 }, + })) as { data: number[] } | null; + expectTimedSuccess(ctx, 'textDocument/semanticTokens/range'); + + // `name=` and `elements+=` in the DrawingRule body + expect(decode(result?.data ?? [])).toEqual(['36:14 property', '36:22 property']); + }); + + // missing capability: semanticTokensProvider.full.delta is false + it.skip('semanticTokensDelta (chained from the full resultId)'); + }); + + describe('call hierarchy', () => { + let item: HierarchyItem; + + beforeAll(async () => { + ctx.collectTimings(); + const items = (await ctx.prepareCallHierarchy(FILE, 41, 3)) as HierarchyItem[] | null; + expectTimedSuccess(ctx, 'textDocument/prepareCallHierarchy'); + expect(items).toHaveLength(1); + item = (items ?? [])[0]; + }); + + it('prepares an item for `CircleRule`', () => { + expect(item.name).toBe('CircleRule'); + expect(item.selectionRange).toEqual({ + start: { line: 41, character: 0 }, + end: { line: 41, character: 10 }, + }); + }); + + it('lists `ElementRule` as the incoming caller', async () => { + ctx.collectTimings(); + const calls = (await ctx.callHierarchyIncomingCalls(item)) as Array<{ + from: HierarchyItem; + fromRanges: LspRange[]; + }> | null; + expectTimedSuccess(ctx, 'callHierarchy/incomingCalls'); + + expect(calls).toHaveLength(1); + expect(calls?.[0].from.name).toBe('ElementRule'); + expect(calls?.[0].fromRanges.map(startOf)).toEqual(['39:4']); + }); + + it('lists the terminals and fragment it calls as outgoing', async () => { + ctx.collectTimings(); + const calls = (await ctx.callHierarchyOutgoingCalls(item)) as Array<{ + to: HierarchyItem; + fromRanges: LspRange[]; + }> | null; + expectTimedSuccess(ctx, 'callHierarchy/outgoingCalls'); + + const targets = (calls ?? []).map((c) => c.to.name).sort(); + expect(targets).toEqual(['ID', 'NUMBER', 'colorFragment']); + for (const call of calls ?? []) { + expect(call.fromRanges[0].start.line).toBe(42); + } + }); + }); + + describe('type hierarchy', () => { + let item: HierarchyItem; + + beforeAll(async () => { + ctx.collectTimings(); + const items = (await ctx.prepareTypeHierarchy(FILE, 11, 12)) as HierarchyItem[] | null; + expectTimedSuccess(ctx, 'textDocument/prepareTypeHierarchy'); + expect(items).toHaveLength(1); + item = (items ?? [])[0]; + }); + + it('prepares an item for the `Shape` interface', () => { + expect(item.name).toBe('Shape'); + expect(item.selectionRange).toEqual({ + start: { line: 11, character: 10 }, + end: { line: 11, character: 15 }, + }); + }); + + it('lists `NamedElement` as the supertype', async () => { + ctx.collectTimings(); + const types = (await ctx.typeHierarchySupertypes(item)) as HierarchyItem[] | null; + expectTimedSuccess(ctx, 'typeHierarchy/supertypes'); + + expect((types ?? []).map((t) => t.name)).toEqual(['NamedElement']); + }); + + it('lists `Circle` and `Rectangle` as subtypes', async () => { + ctx.collectTimings(); + const types = (await ctx.typeHierarchySubtypes(item)) as HierarchyItem[] | null; + expectTimedSuccess(ctx, 'typeHierarchy/subtypes'); + + expect((types ?? []).map((t) => t.name).sort()).toEqual(['Circle', 'Rectangle']); + }); + }); + + it('finds the parser rules via workspace symbols', async () => { + ctx.collectTimings(); + const symbols = (await ctx.workspaceSymbol('Rule')) as Array<{ + name: string; + location: { uri: string; range: LspRange }; + }> | null; + expectTimedSuccess(ctx, 'workspace/symbol'); + + const names = (symbols ?? []).map((s) => s.name).sort(); + expect(names).toEqual(['CircleRule', 'DrawingRule', 'ElementRule', 'GroupRule', 'RectangleRule']); + for (const symbol of symbols ?? []) { + expect(symbol.location.uri).toContain(FILE); + } + }); + + it('sends didSave as an untimed notification and the server stays responsive', async () => { + ctx.collectTimings(); + // the grammar server advertises textDocumentSync.save = false, so it ignores didSave; + // this checks the client side: no throw, no timing, and the server still answers + await ctx.saveDocument(FILE); + expect(ctx.collectTimings()).toHaveLength(0); + + const highlights = (await ctx.documentHighlight(FILE, 11, 12)) as unknown[] | null; + expect(highlights).toHaveLength(5); + }); + + // runs last since it changes the open document (reverted at the end) + it('republishes diagnostics after an edit', async () => { + const grammarName = { start: { line: 4, character: 8 }, end: { line: 4, character: 9 } }; + + await ctx.edit(FILE, { range: grammarName, text: 's' }); + const after = (await ctx.waitForDiagnostics(FILE, 30_000)) as typeof initialDiagnostics; + const codes = after.map((d) => d.data?.code).sort(); + expect(codes).toEqual(['grammar-name-uppercase', 'rule-name-uppercase']); + + await ctx.edit(FILE, { range: grammarName, text: 'S' }); + const reverted = (await ctx.waitForDiagnostics(FILE, 30_000)) as typeof initialDiagnostics; + expect(reverted.map((d) => d.data?.code)).toEqual(['rule-name-uppercase']); + }); + + // these methods are not advertised by the grammar server, so they are skipped + // rather than asserting on "Unhandled method" errors or unadvertised handlers + it('does not advertise the providers whose tests are skipped below', () => { + const caps = harness.capabilities as Record | null; + // if any of these start being advertised, un-skip the matching test below + for (const key of [ + 'declarationProvider', + 'typeDefinitionProvider', + 'implementationProvider', + 'signatureHelpProvider', + 'documentOnTypeFormattingProvider', + 'selectionRangeProvider', + 'documentLinkProvider', + 'codeLensProvider', + 'inlayHintProvider', + 'diagnosticProvider', + ]) { + expect(caps?.[key] ?? false, key).toBeFalsy(); + } + const semantic = caps?.semanticTokensProvider as { full?: { delta?: boolean } }; + expect(semantic.full?.delta).toBeFalsy(); + }); + + // missing capability: declarationProvider is false + it.skip('declaration'); + // missing capability: typeDefinitionProvider is false + it.skip('typeDefinition'); + // missing capability: implementationProvider is false + it.skip('implementation'); + // missing capability: no signatureHelpProvider + it.skip('signatureHelp'); + // missing capability: no documentOnTypeFormattingProvider (the formatter answers, but it is not advertised) + it.skip('onTypeFormatting'); + // missing capability: no selectionRangeProvider + it.skip('selectionRange'); + // missing capability: no documentLinkProvider + it.skip('documentLink'); + // missing capability: no codeLensProvider + it.skip('codeLens'); + // missing capability: no inlayHintProvider + it.skip('inlayHint'); + // missing capability: no diagnosticProvider (the grammar server only pushes diagnostics) + it.skip('documentDiagnostic / workspaceDiagnostic'); +}); diff --git a/test-integration/langium-grammar/shapes.langium b/test-integration/langium-grammar/shapes.langium new file mode 100644 index 0000000..b720e78 --- /dev/null +++ b/test-integration/langium-grammar/shapes.langium @@ -0,0 +1,58 @@ +/* + * A small drawing language used as an lsbench integration fixture. + * Some lines below are deliberately unformatted. + */ +grammar Shapes + +interface NamedElement { + name: string; +} + +/** A drawable element with an optional color. */ +interface Shape extends NamedElement { + color?: string; +} + +interface Circle extends Shape { + radius: number; +} + +interface Rectangle extends Shape{ + width: number; + height: number; +} + +interface Group extends NamedElement { + members: @Shape[]; +} + +type Element = Circle | Rectangle | Group; + +interface Drawing { + name: string; + elements: Element[]; +} + +entry DrawingRule returns Drawing: + 'drawing' name=ID elements+=ElementRule*; + +ElementRule returns Element: + CircleRule | RectangleRule | GroupRule; + +CircleRule returns Circle: + 'circle' name=ID colorFragment? 'radius' radius=NUMBER; + +RectangleRule returns Rectangle : + 'rect' name=ID colorFragment? 'size' width=NUMBER 'x' height=NUMBER; + +GroupRule returns Group: + 'group' name=ID '{' members+=[Shape:ID]* '}'; + +fragment colorFragment: + 'color' color=ID; + +hidden terminal WS: /\s+/; +terminal ID: /[_a-zA-Z][\w_]*/; +terminal NUMBER returns number: /[0-9]+/; +hidden terminal ML_COMMENT: /\/\*[\s\S]*?\*\//; +hidden terminal SL_COMMENT: /\/\/[^\n\r]*/; diff --git a/test/harness.test.ts b/test/harness.test.ts index f6a9de3..fa3bc73 100644 --- a/test/harness.test.ts +++ b/test/harness.test.ts @@ -91,3 +91,41 @@ describe('LspHarness server-to-client requests', () => { } }); }); + +/** a fake server that ignores SIGTERM and never exits on its own */ +const stubbornServer = ` +import * as rpc from 'vscode-jsonrpc/node'; +process.on('SIGTERM', () => {}); +const conn = rpc.createMessageConnection( + new rpc.StreamMessageReader(process.stdin), + new rpc.StreamMessageWriter(process.stdout), +); +conn.onRequest('initialize', () => ({ capabilities: { pid: process.pid } })); +conn.onRequest('shutdown', () => null); +conn.listen(); +setInterval(() => {}, 1000); +`; + +describe('LspHarness.stop', () => { + it('force kills a server that ignores SIGTERM', async () => { + const harness = new LspHarness( + { command: process.execPath, args: ['--input-type=module', '-e', stubbornServer] }, + process.cwd(), + ); + await harness.start(); + const pid = harness.capabilities?.pid as number; + await harness.stop(); + + // signal 0 only probes for existence, and throws once the process is gone + let alive = true; + try { + process.kill(pid, 0); + } catch { + alive = false; + } + if (alive) { + process.kill(pid, 'SIGKILL'); + } + expect(alive).toBe(false); + }); +}); From fe8105c0a0c840f7f2178c954acd8d293dd65c94 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 10:52:35 +0100 Subject: [PATCH 13/19] codeAction: also match diagnostic codes carried in data.code Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + README.md | 2 +- src/cli.ts | 2 +- src/context.ts | 24 +++++++++++++++- test-integration/langium-grammar.test.ts | 26 ++++-------------- test/context.test.ts | 35 ++++++++++++++++++++++++ 6 files changed, 66 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f98361..bc8588c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Adds many more LSP requests to `BenchContext`, plus a fix for `addRegisteredLang ### Fixes +- `codeAction` diagnostic code filtering now also matches `data.code`, so quick fixes from servers like Langium that store their issue code in `data` can be triggered. - `addRegisteredLanguage` stored the extension mapping backwards (language id to extension instead of extension to language id). Extensions are now also lowercased to match `detectLanguageId`. ## v0.1.0 diff --git a/README.md b/README.md index 486aae9..3615beb 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ export default async function (ctx: BenchContext) { | `onTypeFormatting(path, line, char, ch)` | `textDocument/onTypeFormatting` (timed) | | `rename(path, line, char, newName)` | `textDocument/rename` (timed) | | `prepareRename(path, line, char)` | `textDocument/prepareRename` (timed) | -| `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed) | +| `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed). `codes` selects cached diagnostics by `code`, falling back to `data.code` (as used by Langium) | | `signatureHelp(path, line, char)` | `textDocument/signatureHelp` (timed) | | `foldingRange(path)` | `textDocument/foldingRange` (timed) | | `selectionRange(path, positions)` | `textDocument/selectionRange` (timed) | diff --git a/src/cli.ts b/src/cli.ts index 9d27d10..f5dff0d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -229,7 +229,7 @@ Timed LSP requests (return the raw LSP result, or null on failure) onTypeFormatting(path, line, char, ch) textDocument/onTypeFormatting (ch is the typed trigger character) rename(path, line, char, newName) textDocument/rename prepareRename(path, line, char) textDocument/prepareRename - codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics) + codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics by code, falling back to data.code) signatureHelp(path, line, char) textDocument/signatureHelp foldingRange(path) textDocument/foldingRange selectionRange(path, positions) textDocument/selectionRange (positions is an array of {line,character}) diff --git a/src/context.ts b/src/context.ts index e451a66..e9d7dcc 100644 --- a/src/context.ts +++ b/src/context.ts @@ -173,7 +173,7 @@ export class BenchContextImpl implements BenchContext { ): Promise { const uri = this.getUri(relativePath); const diagnostics = diagnosticCodes - ? this.harness.getDiagnostics(uri).filter((d) => diagnosticCodes.includes(d.code as string | number)) + ? filterDiagnosticsByCode(this.harness.getDiagnostics(uri), diagnosticCodes) : []; return this.timedRequest('textDocument/codeAction', { @@ -432,6 +432,28 @@ function toLspRange(range: Range): { }; } +/** + * Keeps diagnostics whose `code` is in `codes`, falling back to `data.code` + * for servers (such as Langium) that carry their issue code in the opaque `data` payload. + */ +function filterDiagnosticsByCode(diagnostics: Diagnostic[], codes: (string | number)[]): Diagnostic[] { + const matched: Diagnostic[] = []; + for (const d of diagnostics) { + if (d.code !== undefined && codes.includes(d.code)) { + matched.push(d); + continue; + } + const data = d.data; + if (typeof data === 'object' && data !== null && 'code' in data) { + const dataCode = (data as { code: unknown }).code; + if ((typeof dataCode === 'string' || typeof dataCode === 'number') && codes.includes(dataCode)) { + matched.push(d); + } + } + } + return matched; +} + /** * Mapping of extensions -> language ids */ diff --git a/test-integration/langium-grammar.test.ts b/test-integration/langium-grammar.test.ts index b924048..05c39c0 100644 --- a/test-integration/langium-grammar.test.ts +++ b/test-integration/langium-grammar.test.ts @@ -243,34 +243,18 @@ describe('langium grammar language server (integration)', () => { }); }); - it('answers code actions, and offers a quickfix when given the raw diagnostic', async () => { + it('offers the uppercase quickfix when filtering by the data.code issue code', async () => { const range = initialDiagnostics[0].range; ctx.collectTimings(); - // Langium carries its issue code in `data.code` rather than `code`, so this - // filter matches nothing and no diagnostics are forwarded to the server - const filtered = await ctx.codeAction(FILE, range, ['rule-name-uppercase']); - expectTimedSuccess(ctx, 'textDocument/codeAction'); - expect(filtered).toEqual([]); - - // sending the published diagnostic through `request` yields the quickfix - const actions = await ctx.request }; - }> | null>( - 'textDocument/codeAction', - { - textDocument: { uri: `file://${path.join(workspaceDir, FILE)}` }, - range, - context: { diagnostics: initialDiagnostics }, - }, - 'quickfix', - ); - const timing = timingFor(ctx, 'textDocument/codeAction'); - expect(timing?.label).toBe('quickfix'); - expect(timing?.success, timing?.error).toBe(true); + }> | null; + expectTimedSuccess(ctx, 'textDocument/codeAction'); expect(actions).toHaveLength(1); + expect(actions?.[0].title).toBe('First letter to upper case'); expect(actions?.[0].kind).toBe('quickfix'); const edits = Object.values(actions?.[0].edit.changes ?? {})[0]; expect(edits).toEqual([ diff --git a/test/context.test.ts b/test/context.test.ts index 7e821a8..3f47c08 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -497,6 +497,41 @@ describe('BenchContextImpl', () => { expect(params.context.diagnostics.map((d) => d.code)).toEqual([2322, 'no-unused']); }); + describe('codeAction diagnostic matching', () => { + const range = { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } }; + + async function sentDiagnostics(diagnostics: Diagnostic[], codes: (string | number)[]): Promise { + harness.setDiagnostics(`file://${path.resolve(tmpDir, 'sample.ts')}`, diagnostics); + await ctx.codeAction('sample.ts', range, codes); + const req = harness.requests.find((r) => r.method === 'textDocument/codeAction'); + const params = req?.params as { context: { diagnostics: Diagnostic[] } }; + return params.context.diagnostics.map((d) => d.message); + } + + it('matches via code', async () => { + expect(await sentDiagnostics([{ range: {}, message: 'a', code: 'x' }], ['x'])).toEqual(['a']); + }); + + it('matches via data.code', async () => { + const diagnostics = [{ range: {}, message: 'a', data: { code: 'rule-name-uppercase' } }]; + expect(await sentDiagnostics(diagnostics, ['rule-name-uppercase'])).toEqual(['a']); + }); + + it('matches nothing when neither code nor data.code is requested', async () => { + const diagnostics = [{ range: {}, message: 'a', code: 'x', data: { code: 'y' } }]; + expect(await sentDiagnostics(diagnostics, ['z'])).toEqual([]); + }); + + it('ignores data that is not an object', async () => { + const diagnostics = [ + { range: {}, message: 'a', data: 'rule-name-uppercase' }, + { range: {}, message: 'b', data: null }, + { range: {}, message: 'c', data: 42 }, + ]; + expect(await sentDiagnostics(diagnostics, ['rule-name-uppercase', 42])).toEqual([]); + }); + }); + it('records a failed timing when the request rejects', async () => { harness.failMethods.add('textDocument/definition'); const res = await ctx.definition('sample.ts', 0, 6); From a28c6392359569f6d335dd814f2b157acc270820 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:01:16 +0100 Subject: [PATCH 14/19] add resolve request helpers, note Langium suite in CI Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 7 ++-- README.md | 18 +++++++++ src/cli.ts | 6 +++ src/context.ts | 25 ++++++++++++ src/harness.ts | 9 ++++- src/types.ts | 6 +++ test-integration/langium-grammar.test.ts | 17 +++++++++ test/context.test.ts | 48 ++++++++++++++++++++++++ 8 files changed, 132 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64a3339..9cf88c6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,8 @@ jobs: - name: Install dependencies run: npm ci - # clones, installs, and builds the minilogo language server, then drives it - # over stdio via the built lsbench harness - - name: Integration test (minilogo language server) + # clones, installs, and builds the minilogo language server, starts the Langium + # grammar language server from devDependencies, and drives both over stdio + # via the built lsbench harness + - name: Integration test (minilogo + Langium grammar language servers) run: npm run test:integration diff --git a/README.md b/README.md index 3615beb..05a6dd1 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,12 @@ export default async function (ctx: BenchContext) { | `typeHierarchySubtypes(item)` | `typeHierarchy/subtypes` (timed) | | `documentDiagnostic(path, previousResultId?)` | `textDocument/diagnostic` (timed) | | `workspaceDiagnostic(previousResultIds?)` | `workspace/diagnostic` (timed) | +| `completionItemResolve(item)` | `completionItem/resolve` (timed) | +| `codeLensResolve(codeLens)` | `codeLens/resolve` (timed) | +| `inlayHintResolve(hint)` | `inlayHint/resolve` (timed) | +| `codeActionResolve(action)` | `codeAction/resolve` (timed) | +| `documentLinkResolve(link)` | `documentLink/resolve` (timed) | +| `workspaceSymbolResolve(symbol)` | `workspaceSymbol/resolve` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | @@ -127,6 +133,18 @@ if (items && items.length > 0) { } ``` +Resolve requests take an item returned by the matching request and send it back as is: + +```ts +const list = (await ctx.completion("src/index.ts", 15, 10)) as { items: unknown[] } | unknown[] | null; +const items = Array.isArray(list) ? list : (list?.items ?? []); +if (items.length > 0) { + await ctx.completionItemResolve(items[0]); +} +``` + +The server only answers these when its provider advertises `resolveProvider: true`. + `documentDiagnostic` and `workspaceDiagnostic` only work against servers that expose `diagnosticProvider` in their capabilities. lsbench does not advertise the `textDocument.diagnostic` client capability, since some servers would then stop pushing diagnostics and break `waitForDiagnostics`. In some cases you may also need to register a language ID for a given extension. diff --git a/src/cli.ts b/src/cli.ts index f5dff0d..15c2fa8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -248,6 +248,12 @@ Timed LSP requests (return the raw LSP result, or null on failure) typeHierarchySubtypes(item) typeHierarchy/subtypes (item from prepareTypeHierarchy) documentDiagnostic(path, prevResultId?) textDocument/diagnostic (needs a server with diagnosticProvider) workspaceDiagnostic(prevResultIds?) workspace/diagnostic (prevResultIds is [{uri,value}], default []) + completionItemResolve(item) completionItem/resolve (item from completion, sent as the params) + codeLensResolve(codeLens) codeLens/resolve (codeLens from codeLens, sent as the params) + inlayHintResolve(hint) inlayHint/resolve (hint from inlayHint, sent as the params) + codeActionResolve(action) codeAction/resolve (action from codeAction, sent as the params) + documentLinkResolve(link) documentLink/resolve (link from documentLink, sent as the params) + workspaceSymbolResolve(symbol) workspaceSymbol/resolve (symbol from workspaceSymbol, sent as the params) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. diff --git a/src/context.ts b/src/context.ts index e9d7dcc..e909b9f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -322,6 +322,31 @@ export class BenchContextImpl implements BenchContext { return this.timedRequest('workspace/diagnostic', { previousResultIds }); } + // resolve requests send the raw item from a prior request as the params, unwrapped + async completionItemResolve(item: unknown): Promise { + return this.timedRequest('completionItem/resolve', item); + } + + async codeLensResolve(codeLens: unknown): Promise { + return this.timedRequest('codeLens/resolve', codeLens); + } + + async inlayHintResolve(hint: unknown): Promise { + return this.timedRequest('inlayHint/resolve', hint); + } + + async codeActionResolve(action: unknown): Promise { + return this.timedRequest('codeAction/resolve', action); + } + + async documentLinkResolve(link: unknown): Promise { + return this.timedRequest('documentLink/resolve', link); + } + + async workspaceSymbolResolve(symbol: unknown): Promise { + return this.timedRequest('workspaceSymbol/resolve', symbol); + } + // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { diff --git a/src/harness.ts b/src/harness.ts index e64eb75..d16d429 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -350,6 +350,8 @@ export class LspHarness { ], }, }, + dataSupport: true, + resolveSupport: { properties: ['edit'] }, }, signatureHelp: { dynamicRegistration: true, @@ -362,7 +364,12 @@ export class LspHarness { selectionRange: { dynamicRegistration: true }, documentLink: { dynamicRegistration: true, tooltipSupport: true }, codeLens: { dynamicRegistration: true }, - inlayHint: { dynamicRegistration: true }, + inlayHint: { + dynamicRegistration: true, + resolveSupport: { + properties: ['tooltip', 'textEdits', 'label.tooltip', 'label.location', 'label.command'], + }, + }, callHierarchy: { dynamicRegistration: true }, typeHierarchy: { dynamicRegistration: true }, semanticTokens: { diff --git a/src/types.ts b/src/types.ts index b043e5e..84ad372 100644 --- a/src/types.ts +++ b/src/types.ts @@ -154,6 +154,12 @@ export interface BenchContext { typeHierarchySubtypes(item: unknown): Promise; documentDiagnostic(relativePath: string, previousResultId?: string): Promise; workspaceDiagnostic(previousResultIds?: { uri: string; value: string }[]): Promise; + completionItemResolve(item: unknown): Promise; + codeLensResolve(codeLens: unknown): Promise; + inlayHintResolve(hint: unknown): Promise; + codeActionResolve(action: unknown): Promise; + documentLinkResolve(link: unknown): Promise; + workspaceSymbolResolve(symbol: unknown): Promise; // ── Document mutations ────────────────────────────────────────────── edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise; diff --git a/test-integration/langium-grammar.test.ts b/test-integration/langium-grammar.test.ts index 05c39c0..a54660a 100644 --- a/test-integration/langium-grammar.test.ts +++ b/test-integration/langium-grammar.test.ts @@ -471,6 +471,11 @@ describe('langium grammar language server (integration)', () => { } const semantic = caps?.semanticTokensProvider as { full?: { delta?: boolean } }; expect(semantic.full?.delta).toBeFalsy(); + // advertised providers without resolve support (codeActionProvider is a bare `true`) + for (const key of ['completionProvider', 'codeActionProvider', 'workspaceSymbolProvider']) { + const provider = caps?.[key] as { resolveProvider?: boolean } | boolean | undefined; + expect(typeof provider === 'object' && provider.resolveProvider, `${key}.resolveProvider`).toBeFalsy(); + } }); // missing capability: declarationProvider is false @@ -493,4 +498,16 @@ describe('langium grammar language server (integration)', () => { it.skip('inlayHint'); // missing capability: no diagnosticProvider (the grammar server only pushes diagnostics) it.skip('documentDiagnostic / workspaceDiagnostic'); + // missing capability: completionProvider has no resolveProvider + it.skip('completionItemResolve'); + // missing capability: codeActionProvider is `true`, without resolveProvider + it.skip('codeActionResolve'); + // missing capability: workspaceSymbolProvider.resolveProvider is false + it.skip('workspaceSymbolResolve'); + // missing capability: no codeLensProvider + it.skip('codeLensResolve'); + // missing capability: no documentLinkProvider + it.skip('documentLinkResolve'); + // missing capability: no inlayHintProvider + it.skip('inlayHintResolve'); }); diff --git a/test/context.test.ts b/test/context.test.ts index 3f47c08..6fd431e 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -357,6 +357,54 @@ describe('BenchContextImpl', () => { }); } + // resolve requests that send the raw item from a prior request as the params + const resolveRequests = [ + { name: 'completionItemResolve', method: 'completionItem/resolve', item: { label: 'x', data: { id: 1 } } }, + { + name: 'codeLensResolve', + method: 'codeLens/resolve', + item: { range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, data: 1 }, + }, + { + name: 'inlayHintResolve', + method: 'inlayHint/resolve', + item: { position: { line: 0, character: 7 }, label: ': number', data: 1 }, + }, + { + name: 'codeActionResolve', + method: 'codeAction/resolve', + item: { title: 'Fix it', kind: 'quickfix', data: 1 }, + }, + { + name: 'documentLinkResolve', + method: 'documentLink/resolve', + item: { range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, data: 1 }, + }, + { + name: 'workspaceSymbolResolve', + method: 'workspaceSymbol/resolve', + item: { name: 'x', kind: 13, location: { uri: 'file:///sample.ts' } }, + }, + ] as const; + + for (const { name, method, item } of resolveRequests) { + it(`${name} issues ${method} with the item as the params and records a timing`, async () => { + const res = await ctx[name](item); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toHaveLength(1); + const [req] = harness.requests; + expect(req.method).toBe(method); + expect(req.params).toEqual(item); + + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe(method); + expect(timings[0].success).toBe(true); + expect(timings[0].duration_ms).toBeGreaterThanOrEqual(0); + }); + } + it('documentDiagnostic issues textDocument/diagnostic without previousResultId when omitted and records a timing', async () => { await ctx.openDocument('sample.ts'); const res = await ctx.documentDiagnostic('sample.ts'); From ad4fb918ed93edf758ee2557b3edd50e53bc646c Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:05:10 +0100 Subject: [PATCH 15/19] track document text on edit, honor server save sync options, add willSave/willSaveWaitUntil Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 +- README.md | 6 +- src/cli.ts | 8 +- src/context.ts | 103 +++++++++++++-- src/harness.ts | 91 ++++++++++++- src/index.ts | 2 +- src/types.ts | 5 + test-integration/langium-grammar.test.ts | 30 ++++- test-integration/minilogo.test.ts | 36 +++++- test/context.test.ts | 158 ++++++++++++++++++++++- test/harness.test.ts | 93 +++++++++++++ 11 files changed, 509 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc8588c..3981226 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,17 @@ Adds many more LSP requests to `BenchContext`, plus a fix for `addRegisteredLang - **Workspace symbols:** `workspaceSymbol` - **Call/type hierarchy:** `prepareCallHierarchy`, `callHierarchyIncomingCalls`, `callHierarchyOutgoingCalls`, `prepareTypeHierarchy`, `typeHierarchySupertypes`, `typeHierarchySubtypes` - **Pull diagnostics:** `documentDiagnostic`, `workspaceDiagnostic`. The `textDocument.diagnostic` client capability is intentionally not advertised, since some servers switch from push to pull diagnostics when it is present, which would break `waitForDiagnostics`. -- **Document lifecycle:** `saveDocument` +- **Document lifecycle:** `saveDocument`, `willSave`, `willSaveWaitUntil` (timed) + +### Save handling + +- Save related sync options are read from the static `textDocumentSync` capability and from dynamic registrations of `textDocument/didSave`, `textDocument/willSave` and `textDocument/willSaveWaitUntil`. A bare `TextDocumentSyncKind` number implies `didSave` without text, matching `vscode-languageclient`. They are available via `LspHarness.saveSyncOptions()`. +- `saveDocument` only sends `didSave` when the server wants it, and includes the current document text when it asks for `includeText`. `willSave` is also only sent when wanted, while `willSaveWaitUntil` is always sent since it is timed. ### Fixes +- `edit` now applies each edit to the locally tracked document text, in order, following LSP incremental `didChange` semantics. Previously the tracked text never changed after `openDocument`. + - `codeAction` diagnostic code filtering now also matches `data.code`, so quick fixes from servers like Langium that store their issue code in `data` can be triggered. - `addRegisteredLanguage` stored the extension mapping backwards (language id to extension instead of extension to language id). Extensions are now also lowercased to match `detectLanguageId`. diff --git a/README.md b/README.md index 05a6dd1..18991cf 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,9 @@ export default async function (ctx: BenchContext) { | --- | --- | | `openDocument(path)` | Send `textDocument/didOpen` | | `closeDocument(path)` | Send `textDocument/didClose` | -| `saveDocument(path)` | Send `textDocument/didSave` (document must be open) | +| `saveDocument(path)` | Send `textDocument/didSave` if the server wants it, including the current text when it asks for `includeText` (document must be open) | +| `willSave(path, reason?)` | Send `textDocument/willSave` if the server wants it. `reason` defaults to 1 (Manual) (document must be open) | +| `willSaveWaitUntil(path, reason?)` | `textDocument/willSaveWaitUntil` (timed, always sent). `reason` defaults to 1 (Manual) (document must be open) | | `hover(path, line, char)` | `textDocument/hover` (timed) | | `completion(path, line, char)` | `textDocument/completion` (timed) | | `definition(path, line, char)` | `textDocument/definition` (timed) | @@ -117,7 +119,7 @@ export default async function (ctx: BenchContext) { | `codeActionResolve(action)` | `codeAction/resolve` (timed) | | `documentLinkResolve(link)` | `documentLink/resolve` (timed) | | `workspaceSymbolResolve(symbol)` | `workspaceSymbol/resolve` (timed) | -| `edit(path, edits)` | Send `textDocument/didChange` | +| `edit(path, edits)` | Send `textDocument/didChange` and apply the edits to the tracked text, in order | | `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | | `sleep(ms)` | Pause execution | | `request(method, params, label?)` | Arbitrary timed LSP request | diff --git a/src/cli.ts b/src/cli.ts index 15c2fa8..7104763 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -212,7 +212,9 @@ The object passed to your script. Import its type from 'lsbench'. Methods marked Document lifecycle openDocument(path) textDocument/didOpen — must be called before requests on a file closeDocument(path) textDocument/didClose - saveDocument(path) textDocument/didSave (throws if the document is not open) + saveDocument(path) textDocument/didSave, only if the server wants it (with text if it asks for includeText) + willSave(path, reason?) textDocument/willSave, only if the server wants it (reason defaults to 1, Manual) + saveDocument and willSave throw if the document is not open Timed LSP requests (return the raw LSP result, or null on failure) hover(path, line, char) textDocument/hover @@ -254,11 +256,15 @@ Timed LSP requests (return the raw LSP result, or null on failure) codeActionResolve(action) codeAction/resolve (action from codeAction, sent as the params) documentLinkResolve(link) documentLink/resolve (link from documentLink, sent as the params) workspaceSymbolResolve(symbol) workspaceSymbol/resolve (symbol from workspaceSymbol, sent as the params) + willSaveWaitUntil(path, reason?) textDocument/willSaveWaitUntil (always sent, reason defaults to 1, throws if not open) Mutations edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. The document must be open first. Each EditOperation is { range: { start: {line,character}, end: {line,character} }, text }. + Edits in an array apply in order, each range refers to the text + after the previous edits. The tracked text (sent by didSave when the + server asks for includeText) is updated to match. Synchronization waitForDiagnostics(path, timeoutMs?) resolves with the diagnostics array once the server publishes diff --git a/src/context.ts b/src/context.ts index e909b9f..4c7d3cd 100644 --- a/src/context.ts +++ b/src/context.ts @@ -85,18 +85,43 @@ export class BenchContextImpl implements BenchContext { } async saveDocument(relativePath: string): Promise { - const doc = this.openDocuments.get(relativePath); - if (!doc) { - throw new Error(`Document ${relativePath} is not open. Call openDocument() first.`); + const doc = this.getOpenDocument(relativePath); + const { didSave, includeText } = this.harness.saveSyncOptions(); + if (!didSave) { + this.log(`Skipped didSave for ${relativePath}: server did not ask for it`); + return; } this.harness.sendNotification('textDocument/didSave', { textDocument: { uri: doc.uri }, + ...(includeText ? { text: doc.text } : {}), }); this.log(`Saved ${relativePath}`); } + async willSave(relativePath: string, reason = 1): Promise { + const doc = this.getOpenDocument(relativePath); + if (!this.harness.saveSyncOptions().willSave) { + this.log(`Skipped willSave for ${relativePath}: server did not ask for it`); + return; + } + + this.harness.sendNotification('textDocument/willSave', { + textDocument: { uri: doc.uri }, + reason, + }); + } + + // always sent, since the caller explicitly asked for it to be timed + async willSaveWaitUntil(relativePath: string, reason = 1): Promise { + const doc = this.getOpenDocument(relativePath); + return this.timedRequest('textDocument/willSaveWaitUntil', { + textDocument: { uri: doc.uri }, + reason, + }); + } + // ── Timed LSP requests ────────────────────────────────────────────── async hover(relativePath: string, line: number, character: number): Promise { @@ -350,10 +375,7 @@ export class BenchContextImpl implements BenchContext { // ── Document mutations ────────────────────────────────────────────── async edit(relativePath: string, edits: EditOperation | EditOperation[]): Promise { - const doc = this.openDocuments.get(relativePath); - if (!doc) { - throw new Error(`Document ${relativePath} is not open. Call openDocument() first.`); - } + const doc = this.getOpenDocument(relativePath); const editArray = Array.isArray(edits) ? edits : [edits]; doc.version++; @@ -363,8 +385,11 @@ export class BenchContextImpl implements BenchContext { text: e.text, })); - // Apply edits to our local copy of the text (simplified: just for version tracking) - // A more precise implementation would apply the actual text edits + // mirror the change locally, each edit applies to the result of the previous one + for (const e of editArray) { + doc.text = applyEdit(doc.text, e); + } + this.harness.sendNotification('textDocument/didChange', { textDocument: { uri: doc.uri, version: doc.version }, contentChanges, @@ -394,6 +419,14 @@ export class BenchContextImpl implements BenchContext { // ── Internal helpers ──────────────────────────────────────────────── + private getOpenDocument(relativePath: string): { uri: string; version: number; text: string } { + const doc = this.openDocuments.get(relativePath); + if (!doc) { + throw new Error(`Document ${relativePath} is not open. Call openDocument() first.`); + } + return doc; + } + private getUri(relativePath: string): string { const doc = this.openDocuments.get(relativePath); if (doc) { @@ -457,6 +490,58 @@ function toLspRange(range: Range): { }; } +/** Replace the text covered by `edit.range` with `edit.text` */ +function applyEdit(text: string, edit: EditOperation): string { + const lineStarts = computeLineStarts(text); + let start = positionToOffset(text, lineStarts, edit.range.start); + let end = positionToOffset(text, lineStarts, edit.range.end); + if (start > end) { + [start, end] = [end, start]; + } + return text.slice(0, start) + edit.text + text.slice(end); +} + +/** Offsets at which each line begins, treating \n, \r\n and \r as line breaks like LSP does */ +function computeLineStarts(text: string): number[] { + const starts = [0]; + for (let i = 0; i < text.length; i++) { + const ch = text.charCodeAt(i); + if (ch === 13 /* \r */) { + if (text.charCodeAt(i + 1) === 10 /* \n */) { + i++; + } + starts.push(i + 1); + } else if (ch === 10 /* \n */) { + starts.push(i + 1); + } + } + return starts; +} + +/** + * Convert an LSP position to a string offset. Characters are UTF-16 code units, which is + * what JS string indices count. Out of range positions are clamped as the LSP spec requires: + * a character past the line end maps to the line end, a line past the last maps to the end. + */ +function positionToOffset(text: string, lineStarts: number[], pos: Position): number { + if (pos.line < 0) { + return 0; + } + if (pos.line >= lineStarts.length) { + return text.length; + } + const lineStart = lineStarts[pos.line]; + let lineEnd = pos.line + 1 < lineStarts.length ? lineStarts[pos.line + 1] : text.length; + // exclude the line break itself, so a position can never land inside \r\n + if (lineEnd > lineStart && text.charCodeAt(lineEnd - 1) === 10) { + lineEnd--; + } + if (lineEnd > lineStart && text.charCodeAt(lineEnd - 1) === 13) { + lineEnd--; + } + return Math.min(lineStart + Math.max(pos.character, 0), lineEnd); +} + /** * Keeps diagnostics whose `code` is in `codes`, falling back to `data.code` * for servers (such as Langium) that carry their issue code in the opaque `data` payload. diff --git a/src/harness.ts b/src/harness.ts index d16d429..e7c6e54 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -26,6 +26,27 @@ export interface Diagnostic { [key: string]: unknown; } +/** Which save related notifications the server wants, from static and dynamic registration */ +export interface SaveSyncOptions { + /** server wants textDocument/didSave */ + didSave: boolean; + /** didSave should carry the full document text */ + includeText: boolean; + /** server wants textDocument/willSave */ + willSave: boolean; + /** server wants textDocument/willSaveWaitUntil */ + willSaveWaitUntil: boolean; +} + +interface Registration { + id: string; + method: string; + registerOptions?: unknown; +} + +/** save related methods whose dynamic registrations we track */ +const SAVE_METHODS = new Set(['textDocument/didSave', 'textDocument/willSave', 'textDocument/willSaveWaitUntil']); + /** * Manages a language server process and its JSON-RPC connection. */ @@ -35,6 +56,8 @@ export class LspHarness { private diagnosticsMap = new Map(); private diagnosticsListeners = new Map void>>(); private _capabilities: ServerCapabilities | null = null; + /** dynamic save registrations by registration id */ + private saveRegistrations = new Map(); private verbose: boolean; constructor( @@ -49,6 +72,24 @@ export class LspHarness { return this._capabilities; } + /** Save related sync options, merging the static textDocumentSync capability with dynamic registrations */ + saveSyncOptions(): SaveSyncOptions { + const options = staticSaveSyncOptions(this._capabilities?.textDocumentSync); + for (const reg of this.saveRegistrations.values()) { + if (reg.method === 'textDocument/didSave') { + options.didSave = true; + if (hasIncludeText(reg.registerOptions)) { + options.includeText = true; + } + } else if (reg.method === 'textDocument/willSave') { + options.willSave = true; + } else if (reg.method === 'textDocument/willSaveWaitUntil') { + options.willSaveWaitUntil = true; + } + } + return options; + } + get conn(): rpc.MessageConnection { if (!this.connection) { throw new Error('LSP connection not initialized'); @@ -153,13 +194,20 @@ export class LspHarness { this.connection.onRequest(method, () => null); } - // Handle client/registerCapability (dynamic registration) - this.connection.onRequest('client/registerCapability', () => { - return; // Accept all registrations + // accept all dynamic registrations, remembering save related ones + this.connection.onRequest('client/registerCapability', (params: { registrations?: Registration[] }) => { + for (const reg of params.registrations ?? []) { + if (SAVE_METHODS.has(reg.method)) { + this.saveRegistrations.set(reg.id, reg); + } + } }); - this.connection.onRequest('client/unregisterCapability', () => { - return; + // the LSP spec really does spell this field 'unregisterations' + this.connection.onRequest('client/unregisterCapability', (params: { unregisterations?: Registration[] }) => { + for (const reg of params.unregisterations ?? []) { + this.saveRegistrations.delete(reg.id); + } }); // no user is present to pick an action, so dismiss the prompt @@ -239,6 +287,7 @@ export class LspHarness { this.process = null; this.diagnosticsMap.clear(); this.diagnosticsListeners.clear(); + this.saveRegistrations.clear(); } /** Get cached diagnostics for a URI */ @@ -430,6 +479,38 @@ export class LspHarness { } } +/** + * Reads save options from a static textDocumentSync capability. A bare TextDocumentSyncKind + * number implies didSave without text, matching vscode-languageclient. + */ +function staticSaveSyncOptions(sync: unknown): SaveSyncOptions { + const options: SaveSyncOptions = { didSave: false, includeText: false, willSave: false, willSaveWaitUntil: false }; + if (typeof sync === 'number') { + options.didSave = true; + } else if (typeof sync === 'object' && sync !== null) { + const { save, willSave, willSaveWaitUntil } = sync as { + save?: unknown; + willSave?: unknown; + willSaveWaitUntil?: unknown; + }; + if (save === true) { + options.didSave = true; + } else if (typeof save === 'object' && save !== null) { + options.didSave = true; + options.includeText = hasIncludeText(save); + } + options.willSave = willSave === true; + options.willSaveWaitUntil = willSaveWaitUntil === true; + } + return options; +} + +function hasIncludeText(options: unknown): boolean { + return ( + typeof options === 'object' && options !== null && (options as { includeText?: unknown }).includeText === true + ); +} + /** Convert an absolute file path to a file:// URI */ export function pathToUri(filePath: string): string { const resolved = path.resolve(filePath); diff --git a/src/index.ts b/src/index.ts index ef891c1..55d63a8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ // authoring action scripts. export { addRegisteredLanguage, BenchContextImpl } from './context.js'; -export type { Diagnostic } from './harness.js'; +export type { Diagnostic, SaveSyncOptions } from './harness.js'; export { LspHarness, pathToUri, uriToPath } from './harness.js'; export { loadActionScript, resolveServerConfig, runBenchmark } from './runner.js'; export { buildReport, computeMethodStats, printSummary } from './stats.js'; diff --git a/src/types.ts b/src/types.ts index 84ad372..1704cd1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -118,7 +118,12 @@ export interface BenchContext { // ── Document lifecycle ────────────────────────────────────────────── openDocument(relativePath: string): Promise; closeDocument(relativePath: string): Promise; + /** Sends didSave only if the server asked for it, with the tracked text when it wants includeText */ saveDocument(relativePath: string): Promise; + /** Sends willSave only if the server asked for it. `reason` is a TextDocumentSaveReason, default 1 (Manual) */ + willSave(relativePath: string, reason?: number): Promise; + /** Timed willSaveWaitUntil request, always sent. `reason` defaults to 1 (Manual) */ + willSaveWaitUntil(relativePath: string, reason?: number): Promise; // ── Timed LSP requests ────────────────────────────────────────────── hover(relativePath: string, line: number, character: number): Promise; diff --git a/test-integration/langium-grammar.test.ts b/test-integration/langium-grammar.test.ts index a54660a..9d22378 100644 --- a/test-integration/langium-grammar.test.ts +++ b/test-integration/langium-grammar.test.ts @@ -1,7 +1,7 @@ import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { addRegisteredLanguage, BenchContextImpl, LspHarness, type RequestTiming } from 'lsbench'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; // End-to-end test against Langium's own grammar language server, which registers // far more providers than minilogo (formatter, semantic tokens, call and type @@ -425,12 +425,32 @@ describe('langium grammar language server (integration)', () => { } }); - it('sends didSave as an untimed notification and the server stays responsive', async () => { + it('skips didSave and willSave since the server does not ask for them', async () => { + // the grammar server advertises textDocumentSync save, willSave and willSaveWaitUntil as false + expect(harness.saveSyncOptions()).toEqual({ + didSave: false, + includeText: false, + willSave: false, + willSaveWaitUntil: false, + }); + ctx.collectTimings(); - // the grammar server advertises textDocumentSync.save = false, so it ignores didSave; - // this checks the client side: no throw, no timing, and the server still answers - await ctx.saveDocument(FILE); + const sendNotification = vi.spyOn(harness, 'sendNotification'); + try { + await ctx.saveDocument(FILE); + await ctx.willSave(FILE); + expect(sendNotification).not.toHaveBeenCalled(); + } finally { + sendNotification.mockRestore(); + } expect(ctx.collectTimings()).toHaveLength(0); + }); + + it('times willSaveWaitUntil even though the server does not advertise it', async () => { + // Langium answers with no edits when it has no willSaveWaitUntil handler + const edits = await ctx.willSaveWaitUntil(FILE); + expectTimedSuccess(ctx, 'textDocument/willSaveWaitUntil'); + expect(edits).toEqual([]); const highlights = (await ctx.documentHighlight(FILE, 11, 12)) as unknown[] | null; expect(highlights).toHaveLength(5); diff --git a/test-integration/minilogo.test.ts b/test-integration/minilogo.test.ts index edfcd33..92f934a 100644 --- a/test-integration/minilogo.test.ts +++ b/test-integration/minilogo.test.ts @@ -2,7 +2,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { addRegisteredLanguage, BenchContextImpl, LspHarness, type RequestTiming, type ServerConfig } from 'lsbench'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { examplesDir, serverEntry } from './minilogo.js'; // End-to-end test against a real, built Langium language server (minilogo). @@ -183,17 +183,39 @@ describe('minilogo language server (integration)', () => { expect(inTestLogo?.location.range.start).toEqual({ line: 9, character: 4 }); }); - it('sends didSave as an untimed notification and the server stays responsive', async () => { + it('skips didSave and willSave since the server does not ask for them', async () => { + // minilogo advertises textDocumentSync save, willSave and willSaveWaitUntil as false + expect(harness.saveSyncOptions()).toEqual({ + didSave: false, + includeText: false, + willSave: false, + willSaveWaitUntil: false, + }); + ctx.collectTimings(); - // minilogo advertises textDocumentSync.save = false, so it ignores didSave; - // this checks the client side: no throw, no timing, and the server still answers - await ctx.saveDocument('test.logo'); + const sendNotification = vi.spyOn(harness, 'sendNotification'); + try { + await ctx.saveDocument('test.logo'); + await ctx.willSave('test.logo'); + expect(sendNotification).not.toHaveBeenCalled(); + } finally { + sendNotification.mockRestore(); + } expect(ctx.collectTimings()).toHaveLength(0); + await expect(ctx.saveDocument('not-open.logo')).rejects.toThrow(/not open/); + await expect(ctx.willSave('not-open.logo')).rejects.toThrow(/not open/); + await expect(ctx.willSaveWaitUntil('not-open.logo')).rejects.toThrow(/not open/); + }); + + it('times willSaveWaitUntil even though the server does not advertise it', async () => { + // Langium answers with no edits when it has no willSaveWaitUntil handler + const edits = await ctx.willSaveWaitUntil('test.logo'); + expectTimedSuccess(ctx, 'textDocument/willSaveWaitUntil'); + expect(edits).toEqual([]); + const highlights = (await ctx.documentHighlight('test.logo', 24, 2)) as unknown[] | null; expect(highlights).toHaveLength(3); - - await expect(ctx.saveDocument('not-open.logo')).rejects.toThrow(/not open/); }); // the following methods are not advertised by minilogo (Langium 4.3 minilogo only diff --git a/test/context.test.ts b/test/context.test.ts index 6fd431e..03179bf 100644 --- a/test/context.test.ts +++ b/test/context.test.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import type { Diagnostic, LspHarness } from 'lsbench'; +import type { Diagnostic, EditOperation, LspHarness, SaveSyncOptions } from 'lsbench'; import { addRegisteredLanguage, BenchContextImpl } from 'lsbench'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; @@ -27,6 +27,8 @@ class FakeHarness { /** methods that should reject when requested */ failMethods = new Set(); response: unknown = { ok: true }; + /** what the fake server asks for around saves */ + saveOptions: SaveSyncOptions = { didSave: true, includeText: false, willSave: true, willSaveWaitUntil: true }; async sendRequest(method: string, params: unknown): Promise { this.requests.push({ method, params }); @@ -51,6 +53,15 @@ class FakeHarness { onDiagnostics(uri: string, _timeoutMs: number): Promise { return Promise.resolve(this.diagnostics.get(uri) ?? []); } + + saveSyncOptions(): SaveSyncOptions { + return { ...this.saveOptions }; + } +} + +/** shorthand for an edit replacing the range from (sl, sc) to (el, ec) */ +function op(sl: number, sc: number, el: number, ec: number, text: string): EditOperation { + return { range: { start: { line: sl, character: sc }, end: { line: el, character: ec } }, text }; } describe('BenchContextImpl', () => { @@ -130,6 +141,77 @@ describe('BenchContextImpl', () => { expect(ctx.collectTimings()).toHaveLength(0); }); + it('saveDocument includes the current text when the server asks for includeText', async () => { + harness.saveOptions.includeText = true; + await ctx.openDocument('sample.ts'); + await ctx.saveDocument('sample.ts'); + + expect(harness.notifications[1]).toEqual({ + method: 'textDocument/didSave', + params: { textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, text: 'const x: number = 1;\n' }, + }); + }); + + it('saveDocument skips didSave when the server does not want it', async () => { + harness.saveOptions.didSave = false; + await ctx.openDocument('sample.ts'); + await ctx.saveDocument('sample.ts'); + + expect(harness.notifications.map((n) => n.method)).toEqual(['textDocument/didOpen']); + }); + + it('willSave sends an untimed willSave with the reason, defaulting to Manual', async () => { + await ctx.openDocument('sample.ts'); + await ctx.willSave('sample.ts'); + await ctx.willSave('sample.ts', 2); + + expect(harness.notifications.slice(1)).toEqual([ + { + method: 'textDocument/willSave', + params: { textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, reason: 1 }, + }, + { + method: 'textDocument/willSave', + params: { textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, reason: 2 }, + }, + ]); + expect(harness.requests).toHaveLength(0); + expect(ctx.collectTimings()).toHaveLength(0); + }); + + it('willSave skips the notification when the server does not want it', async () => { + harness.saveOptions.willSave = false; + await ctx.openDocument('sample.ts'); + await ctx.willSave('sample.ts'); + + expect(harness.notifications.map((n) => n.method)).toEqual(['textDocument/didOpen']); + }); + + it('willSave and willSaveWaitUntil throw when the document is not open', async () => { + await expect(ctx.willSave('sample.ts')).rejects.toThrow(/is not open/); + await expect(ctx.willSaveWaitUntil('sample.ts')).rejects.toThrow(/is not open/); + expect(harness.notifications).toHaveLength(0); + expect(harness.requests).toHaveLength(0); + }); + + it('willSaveWaitUntil issues a timed request even when the server does not advertise it', async () => { + harness.saveOptions.willSaveWaitUntil = false; + await ctx.openDocument('sample.ts'); + const res = await ctx.willSaveWaitUntil('sample.ts', 3); + + expect(res).toEqual({ ok: true }); + expect(harness.requests).toEqual([ + { + method: 'textDocument/willSaveWaitUntil', + params: { textDocument: { uri: expect.stringMatching(/sample\.ts$/) }, reason: 3 }, + }, + ]); + const timings = ctx.collectTimings(); + expect(timings).toHaveLength(1); + expect(timings[0].method).toBe('textDocument/willSaveWaitUntil'); + expect(timings[0].success).toBe(true); + }); + it('resetDocuments closes every open document and clears state', async () => { await ctx.openDocument('sample.ts'); await ctx.resetDocuments(); @@ -629,6 +711,80 @@ describe('BenchContextImpl', () => { expect(params.textDocument.version).toBe(2); expect(params.contentChanges).toHaveLength(1); }); + + describe('tracked text', () => { + /** open `content` as a fresh document, apply `edits`, and read the tracked text back via didSave */ + async function textAfter(content: string, edits: EditOperation | EditOperation[]): Promise { + fs.writeFileSync(path.join(tmpDir, 'edit.txt'), content, 'utf-8'); + harness.saveOptions.includeText = true; + await ctx.openDocument('edit.txt'); + await ctx.edit('edit.txt', edits); + await ctx.saveDocument('edit.txt'); + const save = harness.notifications[harness.notifications.length - 1]; + expect(save.method).toBe('textDocument/didSave'); + await ctx.closeDocument('edit.txt'); + return (save.params as { text: string }).text; + } + + it('replaces text within a single line', async () => { + expect(await textAfter('const x = 1;\nlet y;\n', op(0, 6, 0, 7, 'foo'))).toBe( + 'const foo = 1;\nlet y;\n', + ); + }); + + it('replaces text spanning multiple lines', async () => { + expect(await textAfter('aaa\nbbb\nccc\n', op(0, 1, 2, 2, 'X'))).toBe('aXc\n'); + }); + + it('inserts at an empty range, including at the end of the document', async () => { + expect(await textAfter('ab\ncd', op(1, 1, 1, 1, '-'))).toBe('ab\nc-d'); + expect(await textAfter('ab\ncd', op(1, 2, 1, 2, '\nef'))).toBe('ab\ncd\nef'); + }); + + it('deletes text, including a whole line break', async () => { + expect(await textAfter('one\ntwo\nthree\n', op(1, 0, 2, 0, ''))).toBe('one\nthree\n'); + expect(await textAfter('one two', op(0, 3, 0, 7, ''))).toBe('one'); + }); + + it('applies a batch in order, each range relative to the previous result', async () => { + const edits = [ + // insert a new first line, shifting everything down + op(0, 0, 0, 0, 'first\n'), + // line 1 is now the original line 0 + op(1, 0, 1, 3, 'ONE'), + // join the old lines 1 and 2, now at lines 2 and 3 + op(2, 3, 3, 0, ' '), + ]; + expect(await textAfter('one\ntwo\nthree\n', edits)).toBe('first\nONE\ntwo three\n'); + }); + + it('accumulates text across separate edit calls', async () => { + fs.writeFileSync(path.join(tmpDir, 'edit.txt'), 'abc', 'utf-8'); + harness.saveOptions.includeText = true; + await ctx.openDocument('edit.txt'); + await ctx.edit('edit.txt', op(0, 3, 0, 3, 'd')); + await ctx.edit('edit.txt', op(0, 0, 0, 1, '')); + await ctx.saveDocument('edit.txt'); + const save = harness.notifications[harness.notifications.length - 1]; + expect((save.params as { text: string }).text).toBe('bcd'); + }); + + it('handles \\r\\n line endings without splitting them', async () => { + expect(await textAfter('ab\r\ncd\r\n', op(1, 0, 1, 2, 'XY'))).toBe('ab\r\nXY\r\n'); + // a character past the line end clamps to before the \r\n + expect(await textAfter('ab\r\ncd\r\n', op(0, 99, 0, 99, '!'))).toBe('ab!\r\ncd\r\n'); + expect(await textAfter('ab\r\ncd', op(0, 2, 1, 0, ''))).toBe('abcd'); + }); + + it('counts characters in UTF-16 code units', async () => { + // the emoji is a surrogate pair, two code units wide + expect(await textAfter('a😀b\n', op(0, 3, 0, 4, 'c'))).toBe('a😀c\n'); + }); + + it('clamps a line past the end of the document to the end', async () => { + expect(await textAfter('ab\n', op(5, 0, 5, 0, 'z'))).toBe('ab\nz'); + }); + }); }); describe('notify and waitForDiagnostics', () => { diff --git a/test/harness.test.ts b/test/harness.test.ts index fa3bc73..ae868a7 100644 --- a/test/harness.test.ts +++ b/test/harness.test.ts @@ -129,3 +129,96 @@ describe('LspHarness.stop', () => { expect(alive).toBe(false); }); }); + +/** + * A fake server advertising the textDocumentSync capability given in argv, which on + * request forwards client/registerCapability or client/unregisterCapability to the client. + */ +const syncServer = ` +import * as rpc from 'vscode-jsonrpc/node'; +const conn = rpc.createMessageConnection( + new rpc.StreamMessageReader(process.stdin), + new rpc.StreamMessageWriter(process.stdout), +); +const sync = JSON.parse(process.argv[1]); +conn.onRequest('initialize', () => ({ capabilities: sync === null ? {} : { textDocumentSync: sync } })); +conn.onRequest('test/forward', ([method, params]) => conn.sendRequest(method, params)); +conn.onRequest('shutdown', () => null); +conn.onNotification('exit', () => process.exit(0)); +conn.listen(); +`; + +describe('LspHarness.saveSyncOptions', () => { + async function withSyncServer(sync: unknown, body: (harness: LspHarness) => Promise): Promise { + const harness = new LspHarness( + { + command: process.execPath, + args: ['--input-type=module', '-e', syncServer, JSON.stringify(sync)], + }, + process.cwd(), + ); + try { + await harness.start(); + await body(harness); + } finally { + await harness.stop(); + } + } + + const none = { didSave: false, includeText: false, willSave: false, willSaveWaitUntil: false }; + + const staticCases: Array<[string, unknown, typeof none]> = [ + ['no textDocumentSync', null, none], + ['a bare TextDocumentSyncKind wants didSave without text', 2, { ...none, didSave: true }], + ['save: false', { change: 2, save: false }, none], + ['save: true', { save: true }, { ...none, didSave: true }], + ['save: {} without includeText', { save: {} }, { ...none, didSave: true }], + ['save: { includeText: true }', { save: { includeText: true } }, { ...none, didSave: true, includeText: true }], + [ + 'willSave and willSaveWaitUntil', + { willSave: true, willSaveWaitUntil: true }, + { ...none, willSave: true, willSaveWaitUntil: true }, + ], + ]; + + for (const [name, sync, expected] of staticCases) { + it(`reads the static capability: ${name}`, async () => { + await withSyncServer(sync, async (harness) => { + expect(harness.saveSyncOptions()).toEqual(expected); + }); + }); + } + + it('merges dynamic registrations and drops them on unregister', async () => { + await withSyncServer({ change: 2, save: false }, async (harness) => { + await harness.sendRequest('test/forward', [ + 'client/registerCapability', + { + registrations: [ + { id: 'save', method: 'textDocument/didSave', registerOptions: { includeText: true } }, + { id: 'will', method: 'textDocument/willSave', registerOptions: {} }, + { id: 'until', method: 'textDocument/willSaveWaitUntil' }, + { id: 'hover', method: 'textDocument/hover' }, + ], + }, + ]); + expect(harness.saveSyncOptions()).toEqual({ + didSave: true, + includeText: true, + willSave: true, + willSaveWaitUntil: true, + }); + + await harness.sendRequest('test/forward', [ + 'client/unregisterCapability', + { + unregisterations: [ + { id: 'save', method: 'textDocument/didSave' }, + { id: 'until', method: 'textDocument/willSaveWaitUntil' }, + ], + }, + ]); + expect(harness.saveSyncOptions()).toEqual({ ...none, willSave: true }); + }); + }); +}); From ae0033eeaa0b3f7e39fa362210c21783d6e92bb3 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:06:36 +0100 Subject: [PATCH 16/19] examples: showcase new BenchContext methods Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 2 +- examples/typescript-actions.ts | 169 +++++++++++++++++++++++++++------ 2 files changed, 143 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 18991cf..ed74c25 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ An action script is a file that default-exports an async function receiving a `BenchContext`. The [`examples/`](examples) directory has a few starting points: -- [`examples/typescript-actions.ts`](examples/typescript-actions.ts): a fuller driver exercising hover, completion, definition, references, edits, and more. +- [`examples/typescript-actions.ts`](examples/typescript-actions.ts): a fuller driver exercising hover, completion (with resolve), navigation, formatting, document structure, semantic tokens, workspace symbols, call and type hierarchy, edits, and saves. - [`examples/cold-start.ts`](examples/cold-start.ts): a minimal cold-start driver (i.e. a benchmark that restarts the LS on each run). - [`examples/custom-language.ts`](examples/custom-language.ts): benchmarking a non-mainstream language server (a Langium DSL) via `addRegisteredLanguage`. diff --git a/examples/typescript-actions.ts b/examples/typescript-actions.ts index fb5ee97..10242fb 100644 --- a/examples/typescript-actions.ts +++ b/examples/typescript-actions.ts @@ -9,38 +9,136 @@ * * This script opens a file, waits for the server to finish loading, * then fires a series of LSP requests that exercise typical editor - * interactions: hover, completions, go-to-definition, references, etc. + * interactions: hover, completions, go-to-definition, references, + * formatting, document structure, semantic tokens, hierarchies, edits + * and saves. + * + * Requests a server doesn't support still get timed (usually as a fast error + * or empty result), so trim the sections your server doesn't implement. * * Adapt the file paths and positions to your own workspace. */ -import type { BenchContext } from 'lsbench'; +import type { BenchContext, Range } from 'lsbench'; + +const FILE = 'src/index.ts'; + +// a symbol to target in FILE, adjust to a real function or class in your code +const SYMBOL = { line: 10, character: 5 }; + +// a range covering the top of FILE, used by range based requests +const TOP_RANGE: Range = { + start: { line: 0, character: 0 }, + end: { line: 40, character: 0 }, +}; export default async function (ctx: BenchContext) { // ── 1. Open the main file and wait for diagnostics ──────────────── // (This ensures tsserver has finished loading the project.) - await ctx.openDocument('src/index.ts'); - await ctx.waitForDiagnostics('src/index.ts', 30_000); + await ctx.openDocument(FILE); + await ctx.waitForDiagnostics(FILE, 30_000); + + // ── 2. Core requests ────────────────────────────────────────────── + await coreRequests(ctx); + + // ── 3. Navigation ───────────────────────────────────────────────── + await navigation(ctx); + + // ── 4. Formatting ───────────────────────────────────────────────── + // Formatting returns edits without applying them, so this is safe to repeat. + await ctx.formatting(FILE); + await ctx.rangeFormatting(FILE, TOP_RANGE); - // ── 2. Hover over a symbol ──────────────────────────────────────── - // Hover at line 10, column 5 — adjust to a real symbol in your code. - await ctx.hover('src/index.ts', 10, 5); + // ── 5. Document structure ───────────────────────────────────────── + await documentStructure(ctx); - // ── 3. Request completions ──────────────────────────────────────── - // Trigger completion at a position after a dot (e.g. `object.`) - await ctx.completion('src/index.ts', 15, 10); + // ── 6. Semantic tokens ──────────────────────────────────────────── + await semanticTokens(ctx); - // ── 4. Go to definition ─────────────────────────────────────────── - await ctx.definition('src/index.ts', 10, 5); + // ── 7. Workspace symbols ────────────────────────────────────────── + // Query a prefix of a symbol name that exists in your project. + await ctx.workspaceSymbol('create'); - // ── 5. Find all references ──────────────────────────────────────── - await ctx.references('src/index.ts', 10, 5); + // ── 8. Call and type hierarchy ──────────────────────────────────── + await callHierarchy(ctx); + await typeHierarchy(ctx); - // ── 6. Document symbols ─────────────────────────────────────────── - await ctx.documentSymbol('src/index.ts'); + // ── 9. Edit, save, then undo the edit ───────────────────────────── + await editAndSave(ctx); - // ── 7. Simulate an edit, then re-check ──────────────────────────── - // Insert a line, then request diagnostics and hover again. - await ctx.edit('src/index.ts', { + // ── 10. Close the document ──────────────────────────────────────── + await ctx.closeDocument(FILE); +} + +/** hover, completion (plus resolve), definition, references and symbols */ +async function coreRequests(ctx: BenchContext) { + // hover over a symbol + await ctx.hover(FILE, SYMBOL.line, SYMBOL.character); + + // trigger completion after a dot (e.g. `object.`), then resolve the first + // item to fetch its documentation and detail lazily, as editors do on selection + const completions = await ctx.completion(FILE, 15, 10); + const firstCompletion = firstOf(completionItems(completions)); + if (firstCompletion) { + await ctx.completionItemResolve(firstCompletion); + } + + await ctx.definition(FILE, SYMBOL.line, SYMBOL.character); + await ctx.references(FILE, SYMBOL.line, SYMBOL.character); + await ctx.documentSymbol(FILE); +} + +/** declaration and document highlight, as triggered by cursor movement */ +async function navigation(ctx: BenchContext) { + await ctx.declaration(FILE, SYMBOL.line, SYMBOL.character); + await ctx.documentHighlight(FILE, SYMBOL.line, SYMBOL.character); +} + +/** requests an editor sends after opening a file to render its structure */ +async function documentStructure(ctx: BenchContext) { + await ctx.foldingRange(FILE); + await ctx.selectionRange(FILE, [{ line: SYMBOL.line, character: SYMBOL.character }]); + await ctx.documentLink(FILE); + await ctx.codeLens(FILE); + await ctx.inlayHint(FILE, TOP_RANGE); +} + +/** full semantic tokens, then a delta against the returned resultId */ +async function semanticTokens(ctx: BenchContext) { + const full = await ctx.semanticTokensFull(FILE); + const resultId = (full as { resultId?: string } | null)?.resultId; + + // only servers that support deltas return a resultId + if (resultId) { + await ctx.semanticTokensDelta(FILE, resultId); + } +} + +/** prepare a call hierarchy item, then expand its incoming and outgoing calls */ +async function callHierarchy(ctx: BenchContext) { + const items = await ctx.prepareCallHierarchy(FILE, SYMBOL.line, SYMBOL.character); + const item = firstOf(items); + if (!item) { + return; + } + await ctx.callHierarchyIncomingCalls(item); + await ctx.callHierarchyOutgoingCalls(item); +} + +/** prepare a type hierarchy item, then expand its supertypes and subtypes */ +async function typeHierarchy(ctx: BenchContext) { + // target a class or interface for meaningful results + const items = await ctx.prepareTypeHierarchy(FILE, SYMBOL.line, SYMBOL.character); + const item = firstOf(items); + if (!item) { + return; + } + await ctx.typeHierarchySupertypes(item); + await ctx.typeHierarchySubtypes(item); +} + +/** insert a line, re-check it, save, then remove the line again */ +async function editAndSave(ctx: BenchContext) { + await ctx.edit(FILE, { range: { start: { line: 20, character: 0 }, end: { line: 20, character: 0 }, @@ -48,21 +146,38 @@ export default async function (ctx: BenchContext) { text: 'const __benchTemp = 42;\n', }); - // Wait for the server to process the change - await ctx.waitForDiagnostics('src/index.ts', 10_000); + // wait for the server to process the change, then hover the new variable + await ctx.waitForDiagnostics(FILE, 10_000); + await ctx.hover(FILE, 20, 10); - // Hover the newly inserted variable - await ctx.hover('src/index.ts', 20, 10); + // save like an editor would: willSaveWaitUntil is timed and may return + // edits (e.g. organize imports), saveDocument only sends didSave when the + // server asked for it. Neither writes to disk. + await ctx.willSaveWaitUntil(FILE); + await ctx.saveDocument(FILE); - // ── 8. Clean up the edit (undo the inserted line) ───────────────── - await ctx.edit('src/index.ts', { + // undo the inserted line so each iteration starts from the same text + await ctx.edit(FILE, { range: { start: { line: 20, character: 0 }, end: { line: 21, character: 0 }, }, text: '', }); +} + +/** completion results are either an item array or a CompletionList */ +function completionItems(result: unknown): unknown { + if (Array.isArray(result)) { + return result; + } + return (result as { items?: unknown[] } | null)?.items ?? null; +} - // ── 9. Close the document ───────────────────────────────────────── - await ctx.closeDocument('src/index.ts'); +/** the first element of an array result, or undefined for null or empty results */ +function firstOf(result: unknown): unknown { + if (Array.isArray(result) && result.length > 0) { + return result[0]; + } + return undefined; } From b0bebc42d0c0384c6997224d447daae1504a6669 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:14:49 +0100 Subject: [PATCH 17/19] release prep: v0.2.0, docs and changelog refresh Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 33 +++++++- README.md | 212 +++++++++++++++++++++++++++------------------- package-lock.json | 4 +- package.json | 2 +- src/cli.ts | 99 ++++++++++++++-------- src/types.ts | 2 +- 6 files changed, 222 insertions(+), 130 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3981226..23cf276 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,8 @@ # CHANGELOG -## Unreleased +## v0.2.0 -Adds many more LSP requests to `BenchContext`, plus a fix for `addRegisteredLanguage`. +Adds most remaining LSP requests to `BenchContext`, server-aware save handling, answers for common server to client requests, and a second integration suite against Langium's grammar language server. ### New BenchContext methods @@ -13,19 +13,44 @@ Adds many more LSP requests to `BenchContext`, plus a fix for `addRegisteredLang - **Workspace symbols:** `workspaceSymbol` - **Call/type hierarchy:** `prepareCallHierarchy`, `callHierarchyIncomingCalls`, `callHierarchyOutgoingCalls`, `prepareTypeHierarchy`, `typeHierarchySupertypes`, `typeHierarchySubtypes` - **Pull diagnostics:** `documentDiagnostic`, `workspaceDiagnostic`. The `textDocument.diagnostic` client capability is intentionally not advertised, since some servers switch from push to pull diagnostics when it is present, which would break `waitForDiagnostics`. +- **Resolve:** `completionItemResolve`, `codeActionResolve`, `codeLensResolve`, `inlayHintResolve`, `documentLinkResolve`, `workspaceSymbolResolve` - **Document lifecycle:** `saveDocument`, `willSave`, `willSaveWaitUntil` (timed) ### Save handling -- Save related sync options are read from the static `textDocumentSync` capability and from dynamic registrations of `textDocument/didSave`, `textDocument/willSave` and `textDocument/willSaveWaitUntil`. A bare `TextDocumentSyncKind` number implies `didSave` without text, matching `vscode-languageclient`. They are available via `LspHarness.saveSyncOptions()`. +- Save related sync options are read from the static `textDocumentSync` capability and from dynamic registrations of `textDocument/didSave`, `textDocument/willSave` and `textDocument/willSaveWaitUntil`. A bare `TextDocumentSyncKind` number implies `didSave` without text, matching `vscode-languageclient`. They are available via `LspHarness.saveSyncOptions()`, and `SaveSyncOptions` is exported. - `saveDocument` only sends `didSave` when the server wants it, and includes the current document text when it asks for `includeText`. `willSave` is also only sent when wanted, while `willSaveWaitUntil` is always sent since it is timed. +### Server to client requests + +- Refresh requests (`workspace/semanticTokens/refresh`, `inlayHint/refresh`, `codeLens/refresh`, `inlineValue/refresh`, `diagnostic/refresh`) and `window/workDoneProgress/create` are acknowledged. +- `window/showMessageRequest` is dismissed with `null`, and `workspace/applyEdit` is declined with `applied: false`. +- `client/unregisterCapability` is now handled. + +Previously these went unanswered, which could stall servers that wait on the response. + +### Client capabilities + +- Advertises capabilities for every new request, including `codeAction` `dataSupport` and `resolveSupport`, `inlayHint` and workspace symbol `resolveSupport`, semantic token requests (full, delta, range), and `linkSupport` for declaration. + +### Behavior changes + +- `saveDocument` now respects the server's save options, so it may send nothing, or send `didSave` with the full text, where it always sent a bare `didSave` before. +- `codeAction` and `inlayHint` `resolveSupport` and workspace symbol `resolveSupport` are now advertised, so some servers may return partial items and defer work to the matching resolve request. Benchmarks of those requests may get faster, with the cost moving to resolve. + ### Fixes +- `stop()` never force killed a server that ignored `SIGTERM`, since it checked `process.killed` (which only reports that a signal was sent). It now checks for an actual exit and sends `SIGKILL` after 3 seconds. - `edit` now applies each edit to the locally tracked document text, in order, following LSP incremental `didChange` semantics. Previously the tracked text never changed after `openDocument`. - - `codeAction` diagnostic code filtering now also matches `data.code`, so quick fixes from servers like Langium that store their issue code in `data` can be triggered. - `addRegisteredLanguage` stored the extension mapping backwards (language id to extension instead of extension to language id). Extensions are now also lowercased to match `detectLanguageId`. +- `BenchContext.workspaceRoot` is documented as the absolute workspace path it actually holds, not a URI. + +### Docs and tests + +- README and `lsbench prime` list the full API grouped by area, describe save sync and server to client handling, and correct the stale CLI options and server configuration sections (a JSON server config file was documented but never supported, use `--init-options-file` instead). +- New integration suite against Langium's grammar language server (from devDependencies), covering formatting, code actions, semantic tokens, call and type hierarchy, and more. The minilogo suite now covers the additional methods it supports, and both suites list unsupported methods as skipped. +- `examples/typescript-actions.ts` showcases the new methods. ## v0.1.0 diff --git a/README.md b/README.md index ed74c25..10d28c1 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,12 @@ Benchmark arbitrary language servers with scripted LSP actions. ![lsbench example with langium-minilogo](demo/lsbench.gif) ```bash -# bench a ts language server over stdio +# bench a ts language server over stdio, 50 iterations, report to results.json lsbench "typescript-language-server --stdio" \ - --workspace ./my-project \ # point to your workspace - --script ./bench-actions.ts \ # set the benchmark script - --iterations 50 \ # set iteration count - --output results.json # configure output + --workspace ./my-project \ + --script ./bench-actions.ts \ + --iterations 50 \ + --output results.json ``` ## Installation @@ -73,57 +73,86 @@ export default async function (ctx: BenchContext) { ### BenchContext API +Paths are relative to the workspace root, positions are zero based. Methods marked (timed) record a timing entry and return the raw LSP result, or `null` on failure. `ctx.workspaceRoot` holds the absolute workspace root path. + +**Document lifecycle** (all but `openDocument` and `closeDocument` require an open document) + | Method | Description | | --- | --- | | `openDocument(path)` | Send `textDocument/didOpen` | | `closeDocument(path)` | Send `textDocument/didClose` | -| `saveDocument(path)` | Send `textDocument/didSave` if the server wants it, including the current text when it asks for `includeText` (document must be open) | -| `willSave(path, reason?)` | Send `textDocument/willSave` if the server wants it. `reason` defaults to 1 (Manual) (document must be open) | -| `willSaveWaitUntil(path, reason?)` | `textDocument/willSaveWaitUntil` (timed, always sent). `reason` defaults to 1 (Manual) (document must be open) | -| `hover(path, line, char)` | `textDocument/hover` (timed) | -| `completion(path, line, char)` | `textDocument/completion` (timed) | -| `definition(path, line, char)` | `textDocument/definition` (timed) | -| `references(path, line, char)` | `textDocument/references` (timed) | -| `typeDefinition(path, line, char)` | `textDocument/typeDefinition` (timed) | -| `implementation(path, line, char)` | `textDocument/implementation` (timed) | -| `declaration(path, line, char)` | `textDocument/declaration` (timed) | -| `documentHighlight(path, line, char)` | `textDocument/documentHighlight` (timed) | -| `documentSymbol(path)` | `textDocument/documentSymbol` (timed) | -| `formatting(path)` | `textDocument/formatting` (timed) | -| `rangeFormatting(path, range)` | `textDocument/rangeFormatting` (timed) | -| `onTypeFormatting(path, line, char, ch)` | `textDocument/onTypeFormatting` (timed) | -| `rename(path, line, char, newName)` | `textDocument/rename` (timed) | -| `prepareRename(path, line, char)` | `textDocument/prepareRename` (timed) | -| `codeAction(path, range, codes?)` | `textDocument/codeAction` (timed). `codes` selects cached diagnostics by `code`, falling back to `data.code` (as used by Langium) | -| `signatureHelp(path, line, char)` | `textDocument/signatureHelp` (timed) | -| `foldingRange(path)` | `textDocument/foldingRange` (timed) | -| `selectionRange(path, positions)` | `textDocument/selectionRange` (timed) | -| `documentLink(path)` | `textDocument/documentLink` (timed) | -| `codeLens(path)` | `textDocument/codeLens` (timed) | -| `inlayHint(path, range)` | `textDocument/inlayHint` (timed) | -| `semanticTokensFull(path)` | `textDocument/semanticTokens/full` (timed) | -| `semanticTokensRange(path, range)` | `textDocument/semanticTokens/range` (timed) | -| `semanticTokensDelta(path, previousResultId)` | `textDocument/semanticTokens/full/delta` (timed) | -| `workspaceSymbol(query)` | `workspace/symbol` (timed) | -| `prepareCallHierarchy(path, line, char)` | `textDocument/prepareCallHierarchy` (timed) | -| `callHierarchyIncomingCalls(item)` | `callHierarchy/incomingCalls` (timed) | -| `callHierarchyOutgoingCalls(item)` | `callHierarchy/outgoingCalls` (timed) | -| `prepareTypeHierarchy(path, line, char)` | `textDocument/prepareTypeHierarchy` (timed) | -| `typeHierarchySupertypes(item)` | `typeHierarchy/supertypes` (timed) | -| `typeHierarchySubtypes(item)` | `typeHierarchy/subtypes` (timed) | -| `documentDiagnostic(path, previousResultId?)` | `textDocument/diagnostic` (timed) | -| `workspaceDiagnostic(previousResultIds?)` | `workspace/diagnostic` (timed) | -| `completionItemResolve(item)` | `completionItem/resolve` (timed) | -| `codeLensResolve(codeLens)` | `codeLens/resolve` (timed) | -| `inlayHintResolve(hint)` | `inlayHint/resolve` (timed) | -| `codeActionResolve(action)` | `codeAction/resolve` (timed) | -| `documentLinkResolve(link)` | `documentLink/resolve` (timed) | -| `workspaceSymbolResolve(symbol)` | `workspaceSymbol/resolve` (timed) | | `edit(path, edits)` | Send `textDocument/didChange` and apply the edits to the tracked text, in order | -| `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` | +| `saveDocument(path)` | Send `textDocument/didSave` only if the server asks for it, with the tracked text when it wants `includeText` | +| `willSave(path, reason?)` | Send `textDocument/willSave` only if the server asks for it. `reason` defaults to 1 (Manual) | +| `willSaveWaitUntil(path, reason?)` | `textDocument/willSaveWaitUntil` (timed, always sent). `reason` defaults to 1 (Manual) | + +**Navigation and editing** (timed) + +| Method | Description | +| --- | --- | +| `hover(path, line, char)` | `textDocument/hover` | +| `completion(path, line, char)` | `textDocument/completion` | +| `signatureHelp(path, line, char)` | `textDocument/signatureHelp` | +| `definition(path, line, char)` | `textDocument/definition` | +| `declaration(path, line, char)` | `textDocument/declaration` | +| `typeDefinition(path, line, char)` | `textDocument/typeDefinition` | +| `implementation(path, line, char)` | `textDocument/implementation` | +| `references(path, line, char)` | `textDocument/references` (includes the declaration) | +| `documentHighlight(path, line, char)` | `textDocument/documentHighlight` | +| `prepareRename(path, line, char)` | `textDocument/prepareRename` | +| `rename(path, line, char, newName)` | `textDocument/rename` | +| `codeAction(path, range, codes?)` | `textDocument/codeAction`. `codes` selects cached diagnostics by `code`, falling back to `data.code` (as used by Langium) | +| `formatting(path)` | `textDocument/formatting` | +| `rangeFormatting(path, range)` | `textDocument/rangeFormatting` | +| `onTypeFormatting(path, line, char, ch)` | `textDocument/onTypeFormatting` | + +**Document structure** (timed) + +| Method | Description | +| --- | --- | +| `documentSymbol(path)` | `textDocument/documentSymbol` | +| `foldingRange(path)` | `textDocument/foldingRange` | +| `selectionRange(path, positions)` | `textDocument/selectionRange` | +| `documentLink(path)` | `textDocument/documentLink` | +| `codeLens(path)` | `textDocument/codeLens` | +| `inlayHint(path, range)` | `textDocument/inlayHint` | +| `semanticTokensFull(path)` | `textDocument/semanticTokens/full` | +| `semanticTokensRange(path, range)` | `textDocument/semanticTokens/range` | +| `semanticTokensDelta(path, previousResultId)` | `textDocument/semanticTokens/full/delta` | + +**Workspace, hierarchies, and pull diagnostics** (timed) + +| Method | Description | +| --- | --- | +| `workspaceSymbol(query)` | `workspace/symbol` | +| `prepareCallHierarchy(path, line, char)` | `textDocument/prepareCallHierarchy` | +| `callHierarchyIncomingCalls(item)` | `callHierarchy/incomingCalls` | +| `callHierarchyOutgoingCalls(item)` | `callHierarchy/outgoingCalls` | +| `prepareTypeHierarchy(path, line, char)` | `textDocument/prepareTypeHierarchy` | +| `typeHierarchySupertypes(item)` | `typeHierarchy/supertypes` | +| `typeHierarchySubtypes(item)` | `typeHierarchy/subtypes` | +| `documentDiagnostic(path, previousResultId?)` | `textDocument/diagnostic` | +| `workspaceDiagnostic(previousResultIds?)` | `workspace/diagnostic` | + +**Resolve** (timed, the item is sent back as is) + +| Method | Description | +| --- | --- | +| `completionItemResolve(item)` | `completionItem/resolve` | +| `codeActionResolve(action)` | `codeAction/resolve` | +| `codeLensResolve(codeLens)` | `codeLens/resolve` | +| `inlayHintResolve(hint)` | `inlayHint/resolve` | +| `documentLinkResolve(link)` | `documentLink/resolve` | +| `workspaceSymbolResolve(symbol)` | `workspaceSymbol/resolve` | + +**Helpers** + +| Method | Description | +| --- | --- | +| `waitForDiagnostics(path, timeout?)` | Wait for `publishDiagnostics` (default 30000 ms) | | `sleep(ms)` | Pause execution | -| `request(method, params, label?)` | Arbitrary timed LSP request | -| `notify(method, params)` | Send any LSP notification | +| `request(method, params, label?)` | Arbitrary LSP request (timed) | +| `notify(method, params)` | Arbitrary LSP notification | Call and type hierarchy requests take an item returned by the matching prepare call: @@ -135,7 +164,7 @@ if (items && items.length > 0) { } ``` -Resolve requests take an item returned by the matching request and send it back as is: +Resolve requests take an item returned by the matching request. The server only answers them when its provider advertises `resolveProvider: true`: ```ts const list = (await ctx.completion("src/index.ts", 15, 10)) as { items: unknown[] } | unknown[] | null; @@ -145,9 +174,25 @@ if (items.length > 0) { } ``` -The server only answers these when its provider advertises `resolveProvider: true`. +lsbench advertises `resolveSupport` for completion items, code actions, inlay hints, and workspace symbols, so some servers return partial items and defer that work to the resolve request. + +`documentDiagnostic` and `workspaceDiagnostic` only work against servers that expose `diagnosticProvider`. lsbench does not advertise the `textDocument.diagnostic` client capability, since some servers would then stop pushing diagnostics and break `waitForDiagnostics`. + +### Save sync + +`saveDocument` and `willSave` follow the server's save options, read from the static `textDocumentSync` capability and from dynamic registrations of `textDocument/didSave`, `textDocument/willSave`, and `textDocument/willSaveWaitUntil`. A bare `TextDocumentSyncKind` number implies `didSave` without text, matching `vscode-languageclient`. When the server does not ask for a notification it is skipped and logged in verbose mode. `willSaveWaitUntil` is always sent so it can be timed. + +### Server to client requests + +lsbench answers requests from the server so it never stalls waiting on a client: -`documentDiagnostic` and `workspaceDiagnostic` only work against servers that expose `diagnosticProvider` in their capabilities. lsbench does not advertise the `textDocument.diagnostic` client capability, since some servers would then stop pushing diagnostics and break `waitForDiagnostics`. +- `workspace/configuration` returns an empty object per item +- `client/registerCapability` and `client/unregisterCapability` are accepted (save related registrations are tracked) +- `workspace/*/refresh` (semantic tokens, inlay hints, code lenses, inline values, diagnostics) and `window/workDoneProgress/create` are acknowledged +- `window/showMessageRequest` is dismissed with `null` +- `workspace/applyEdit` is declined with `applied: false`, lsbench never modifies the workspace + +### Registering languages In some cases you may also need to register a language ID for a given extension. That's straightforward to do with `addRegisteredLanguage`, which will then impact all context related actions for documents with a matching extension. @@ -164,50 +209,44 @@ This will ensure that opening a document with the extension `.dsl` will have an ## CLI options ``` -Usage: lsbench [options] +Usage: lsbench [run] [options] Arguments: - server Server command or path to config file + server Server command, e.g. "typescript-language-server --stdio" Options: - -w, --workspace Workspace directory (required) - -s, --script Action driver script (required) - -n, --iterations Timed iterations (default: 10) - --warmup Warmup iterations (default: 2) - -o, --output JSON report output file - --restart Restart server between iterations - -v, --verbose Verbose logging - -V, --version Show version - -h, --help Show help + -w, --workspace Workspace directory (required) + -s, --script Action driver script, .ts (required) + -n, --iterations Timed iterations (default: 10) + --warmup Warmup iterations, not recorded (default: 2) + -o, --output JSON report output file + --init-options-file JSON file with LSP initializationOptions + --restart Restart the server between iterations + -v, --verbose Verbose logging + -V, --version Show version + -h, --help Show help + +Commands: + run Run a benchmark (default command) + prime Print a primer on using lsbench ``` ## Server configuration -You can pass a simple command string: +The server argument is a command string, split on whitespace. Anything after `--` is appended to the server's arguments: ```bash -lsbench "typescript-language-server --stdio" +lsbench "typescript-language-server --stdio" -w ./project -s ./actions.ts -- --log-level 4 ``` -Or a JSON config file for a bit more control: - -```json -{ - "command": "typescript-language-server", - "args": ["--stdio", "--log-level", "warn"], - "env": { "TSS_LOG": "-level verbose" }, - "initializationOptions": { - "preferences": { "includeInlayParameterNameHints": "none" } - } -} -``` +Pass LSP `initializationOptions` as a JSON file: ```bash -lsbench ./server-config.json -w ./project -s ./actions.ts +lsbench "typescript-language-server --stdio" -w ./project -s ./actions.ts \ + --init-options-file ./init-options.json ``` -See [`examples/init-options.json`](examples/init-options.json) for a sample -config file. +See [`examples/init-options.json`](examples/init-options.json) for a sample. For full control over `command`, `args`, `env`, and `initializationOptions`, drive `LspHarness` programmatically with a `ServerConfig`. ## Output format @@ -278,6 +317,7 @@ npm test # unit tests (vitest) npm run lint # oxlint npm run format # biome format check npm run knip # unused dependency/export check +npm run test:integration # minilogo + Langium grammar servers ``` Use `npm run dev` for a watch build while iterating. @@ -294,11 +334,13 @@ Note that `prepublishOnly` cleans `dist/` and then runs `build:prod`. There are two test tiers: - **Unit tests**: `npm test` runs the regular suite in `test/` via vitest. -- **Integration tests**: `npm run test:integration` builds lsbench, then - clones, installs, and builds a Langium ([minilogo](https://github.com/TypeFox/langium-minilogo)) - language server and interacts with it via stdio. The suite runs over some of the following benchmark checks: go-to-definition, references, document symbols, hover, and a full `runBenchmark` report. +- **Integration tests**: `npm run test:integration` builds lsbench, then drives two real language servers over stdio: + - **minilogo**: clones, installs, and builds [langium-minilogo](https://github.com/TypeFox/langium-minilogo), then covers the methods it supports (symbols, definition, references, hover, highlight, prepareRename, folding, workspace symbols, save sync) plus a full `runBenchmark` report. + - **Langium grammar**: starts Langium's own grammar language server from devDependencies against a small fixture (`test-integration/langium-grammar/shapes.langium`). It covers the broader provider set: completion, rename, formatting, code actions via `data.code`, semantic tokens, call and type hierarchy, edits, and save sync. + + Methods a server does not advertise are listed as skipped tests, and each suite asserts that those providers are indeed absent. -The integration run clones down & builds the minilogo server once on first use, so it's possible that it might be slow (timeouts are 120s per test / 600s per hook, per `vitest.integration.config.ts`). To account for this, the CI runs it as a separate `integration` job. +The minilogo server is cloned and built once on first use, so the first run can be slow (timeouts are 120s per test and 600s per hook, per `vitest.integration.config.ts`). CI runs both suites in a separate `integration` job. ## License diff --git a/package-lock.json b/package-lock.json index d9f214d..010cecc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "lsbench", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lsbench", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "dependencies": { "commander": "^14.0.3", diff --git a/package.json b/package.json index a4da300..8543844 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lsbench", - "version": "0.1.0", + "version": "0.2.0", "description": "Benchmark arbitrary language servers with scripted LSP actions", "license": "MIT", "author": "montymxb", diff --git a/src/cli.ts b/src/cli.ts index 7104763..dfb492a 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -207,32 +207,45 @@ All file paths are relative to the workspace root. Positions are zero-based ## The context API (BenchContext) The object passed to your script. Import its type from 'lsbench'. Methods marked -(timed) record a RequestTiming entry; others are notifications or helpers. +(timed) record a RequestTiming entry and return the raw LSP result, or null on +failure. Others are notifications or helpers. -Document lifecycle - openDocument(path) textDocument/didOpen — must be called before requests on a file +Document lifecycle (all but openDocument/closeDocument throw if the document is not open) + openDocument(path) textDocument/didOpen, call before requests on a file closeDocument(path) textDocument/didClose - saveDocument(path) textDocument/didSave, only if the server wants it (with text if it asks for includeText) - willSave(path, reason?) textDocument/willSave, only if the server wants it (reason defaults to 1, Manual) - saveDocument and willSave throw if the document is not open - -Timed LSP requests (return the raw LSP result, or null on failure) + edit(path, edits) textDocument/didChange. edits is an EditOperation or an array, + each { range: { start: {line,character}, end: {line,character} }, text }. + Array edits apply in order, each range refers to the text after + the previous edits. The tracked document text is updated to match. + saveDocument(path) textDocument/didSave, only if the server asks for it, with the + tracked text when it wants includeText + willSave(path, reason?) textDocument/willSave, only if the server asks for it (reason default 1, Manual) + willSaveWaitUntil(path, reason?) textDocument/willSaveWaitUntil (timed, always sent, reason default 1) + + Save options come from the static textDocumentSync capability and from dynamic + didSave/willSave/willSaveWaitUntil registrations. A bare TextDocumentSyncKind + number implies didSave without text. + +Navigation and editing (timed) hover(path, line, char) textDocument/hover completion(path, line, char) textDocument/completion + signatureHelp(path, line, char) textDocument/signatureHelp definition(path, line, char) textDocument/definition - references(path, line, char) textDocument/references (includeDeclaration: true) + declaration(path, line, char) textDocument/declaration typeDefinition(path, line, char) textDocument/typeDefinition implementation(path, line, char) textDocument/implementation - declaration(path, line, char) textDocument/declaration + references(path, line, char) textDocument/references (includeDeclaration: true) documentHighlight(path, line, char) textDocument/documentHighlight - documentSymbol(path) textDocument/documentSymbol + prepareRename(path, line, char) textDocument/prepareRename + rename(path, line, char, newName) textDocument/rename + codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics by code, + falling back to data.code as used by Langium) formatting(path) textDocument/formatting (tabSize 2, spaces) rangeFormatting(path, range) textDocument/rangeFormatting (tabSize 2, spaces) onTypeFormatting(path, line, char, ch) textDocument/onTypeFormatting (ch is the typed trigger character) - rename(path, line, char, newName) textDocument/rename - prepareRename(path, line, char) textDocument/prepareRename - codeAction(path, range, codes?) textDocument/codeAction (codes filter cached diagnostics by code, falling back to data.code) - signatureHelp(path, line, char) textDocument/signatureHelp + +Document structure (timed) + documentSymbol(path) textDocument/documentSymbol foldingRange(path) textDocument/foldingRange selectionRange(path, positions) textDocument/selectionRange (positions is an array of {line,character}) documentLink(path) textDocument/documentLink @@ -241,46 +254,58 @@ Timed LSP requests (return the raw LSP result, or null on failure) semanticTokensFull(path) textDocument/semanticTokens/full semanticTokensRange(path, range) textDocument/semanticTokens/range semanticTokensDelta(path, prevResultId) textDocument/semanticTokens/full/delta (prevResultId from a prior result) - workspaceSymbol(query) workspace/symbol (workspace-wide, no document needed) + +Workspace, hierarchies, pull diagnostics (timed) + workspaceSymbol(query) workspace/symbol (no document needed) prepareCallHierarchy(path, line, char) textDocument/prepareCallHierarchy (returns CallHierarchyItem[]) callHierarchyIncomingCalls(item) callHierarchy/incomingCalls (item from prepareCallHierarchy) callHierarchyOutgoingCalls(item) callHierarchy/outgoingCalls (item from prepareCallHierarchy) prepareTypeHierarchy(path, line, char) textDocument/prepareTypeHierarchy (returns TypeHierarchyItem[]) typeHierarchySupertypes(item) typeHierarchy/supertypes (item from prepareTypeHierarchy) typeHierarchySubtypes(item) typeHierarchy/subtypes (item from prepareTypeHierarchy) - documentDiagnostic(path, prevResultId?) textDocument/diagnostic (needs a server with diagnosticProvider) + documentDiagnostic(path, prevResultId?) textDocument/diagnostic workspaceDiagnostic(prevResultIds?) workspace/diagnostic (prevResultIds is [{uri,value}], default []) - completionItemResolve(item) completionItem/resolve (item from completion, sent as the params) - codeLensResolve(codeLens) codeLens/resolve (codeLens from codeLens, sent as the params) - inlayHintResolve(hint) inlayHint/resolve (hint from inlayHint, sent as the params) - codeActionResolve(action) codeAction/resolve (action from codeAction, sent as the params) - documentLinkResolve(link) documentLink/resolve (link from documentLink, sent as the params) - workspaceSymbolResolve(symbol) workspaceSymbol/resolve (symbol from workspaceSymbol, sent as the params) - willSaveWaitUntil(path, reason?) textDocument/willSaveWaitUntil (always sent, reason defaults to 1, throws if not open) - -Mutations - edit(path, edits) textDocument/didChange — edits is an EditOperation or array of them. - The document must be open first. Each EditOperation is - { range: { start: {line,character}, end: {line,character} }, text }. - Edits in an array apply in order, each range refers to the text - after the previous edits. The tracked text (sent by didSave when the - server asks for includeText) is updated to match. + + Pull diagnostics need a server with diagnosticProvider. lsbench does not + advertise the textDocument.diagnostic client capability, since some servers + would then stop pushing diagnostics and break waitForDiagnostics. + +Resolve (timed, the item from the matching request is sent back as the params) + completionItemResolve(item) completionItem/resolve + codeActionResolve(action) codeAction/resolve + codeLensResolve(codeLens) codeLens/resolve + inlayHintResolve(hint) inlayHint/resolve + documentLinkResolve(link) documentLink/resolve + workspaceSymbolResolve(symbol) workspaceSymbol/resolve + + Only answered when the provider advertises resolveProvider: true. lsbench + advertises resolveSupport for completion items, code actions, inlay hints and + workspace symbols, so some servers defer work from the request to resolve. Synchronization waitForDiagnostics(path, timeoutMs?) resolves with the diagnostics array once the server publishes them (default timeout 30_000ms). Call after open/edit before timing. - sleep(ms) pause execution — useful to let background indexing settle. + sleep(ms) pause execution, useful to let background indexing settle. Escape hatches (for methods without a convenience wrapper) - request(method, params, label?) send an arbitrary LSP request; it is timed. label appears in the report. - notify(method, params) send an arbitrary LSP notification (not timed — no response). + request(method, params, label?) send an arbitrary LSP request (timed). label appears in the report. + notify(method, params) send an arbitrary LSP notification (not timed, no response). Property - workspaceRoot the resolved workspace root URI. + workspaceRoot absolute path of the workspace root. + +## Server to client requests + +lsbench answers these so a server never stalls waiting on a client: + workspace/configuration an empty object per item + client/(un)registerCapability accepted, save related registrations are tracked + workspace/*/refresh, workDoneProgress acknowledged + window/showMessageRequest dismissed with null + workspace/applyEdit declined, lsbench never modifies the workspace ## CLI reference - Usage: lsbench [options] + Usage: lsbench [run] [options] Arguments: server Server command, e.g. "typescript-language-server --stdio" diff --git a/src/types.ts b/src/types.ts index 1704cd1..cd6c102 100644 --- a/src/types.ts +++ b/src/types.ts @@ -112,7 +112,7 @@ export interface EditOperation { * All methods that send LSP requests are automatically timed. */ export interface BenchContext { - /** The workspace root URI */ + /** Absolute path of the workspace root */ workspaceRoot: string; // ── Document lifecycle ────────────────────────────────────────────── From 1bf19dff488628e49c20d8b09e6e33517b8e8a3a Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:14:54 +0100 Subject: [PATCH 18/19] changelog: correct note on prior server request handling Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23cf276..cdf1283 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ Adds most remaining LSP requests to `BenchContext`, server-aware save handling, - `window/showMessageRequest` is dismissed with `null`, and `workspace/applyEdit` is declined with `applied: false`. - `client/unregisterCapability` is now handled. -Previously these went unanswered, which could stall servers that wait on the response. +Previously these were rejected with a JSON-RPC `MethodNotFound` error, which some servers log noisily or handle poorly. ### Client capabilities From df2e8a0fdabfa68b95fa9cc76e2a6311e8c0ea30 Mon Sep 17 00:00:00 2001 From: Benjamin Friedman Wilson Date: Mon, 9 Nov 2026 11:42:20 +0100 Subject: [PATCH 19/19] some proofing --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 10d28c1..acd5c03 100644 --- a/README.md +++ b/README.md @@ -17,14 +17,14 @@ lsbench "typescript-language-server --stdio" \ ## Installation -lsbench is published to npm. Install it globally for the CLI: +lsbench is published on npm. You can install it globally to get the CLI: ```bash npm install -g lsbench ``` -Or add it as a dependency to import the `BenchContext` API in your action -scripts: +Or, you can add it as a dependency to import the `BenchContext` API in your action +scripts directly: ```bash npm install lsbench @@ -33,7 +33,7 @@ npm install lsbench ## How it works lsbench spawns a language server process, performs the LSP -initialize/initialized handshake, then runs your action script, which is a +initialize/initialized handshake, then runs your action script. That script is a TypeScript file that drives a sequence of LSP requests against a target workspace. @@ -44,7 +44,7 @@ a JSON report with per-method statistics and per-run breakdowns. An action script is a file that default-exports an async function receiving a `BenchContext`. The [`examples/`](examples) directory has a few -starting points: +starting points you can checkout: - [`examples/typescript-actions.ts`](examples/typescript-actions.ts): a fuller driver exercising hover, completion (with resolve), navigation, formatting, document structure, semantic tokens, workspace symbols, call and type hierarchy, edits, and saves. - [`examples/cold-start.ts`](examples/cold-start.ts): a minimal cold-start @@ -52,7 +52,7 @@ starting points: - [`examples/custom-language.ts`](examples/custom-language.ts): benchmarking a non-mainstream language server (a Langium DSL) via `addRegisteredLanguage`. - [`examples/compare-servers.ts`](examples/compare-servers.ts): importing `runBenchmark` to compare two servers programmatically and diff the reports. -A typical script looks like: +A typical script looks akin to this: ```typescript import { BenchContext } from "lsbench"; @@ -73,7 +73,7 @@ export default async function (ctx: BenchContext) { ### BenchContext API -Paths are relative to the workspace root, positions are zero based. Methods marked (timed) record a timing entry and return the raw LSP result, or `null` on failure. `ctx.workspaceRoot` holds the absolute workspace root path. +The following paths should be considered relative to your workspace root, and their positions are zero based. Methods marked as `timed` record a timing entry and return the raw LSP result, or `null` on a failure. `ctx.workspaceRoot` holds the absolute workspace root path for reference. **Document lifecycle** (all but `openDocument` and `closeDocument` require an open document) @@ -154,7 +154,7 @@ Paths are relative to the workspace root, positions are zero based. Methods mark | `request(method, params, label?)` | Arbitrary LSP request (timed) | | `notify(method, params)` | Arbitrary LSP notification | -Call and type hierarchy requests take an item returned by the matching prepare call: +Call and type hierarchy requests expect an item returned by the matching prepare call: ```ts const items = (await ctx.prepareCallHierarchy("src/index.ts", 10, 5)) as unknown[] | null; @@ -164,7 +164,7 @@ if (items && items.length > 0) { } ``` -Resolve requests take an item returned by the matching request. The server only answers them when its provider advertises `resolveProvider: true`: +Resolve requests take an item returned by the matching request. The server only answers when its provider advertises `resolveProvider: true`: ```ts const list = (await ctx.completion("src/index.ts", 15, 10)) as { items: unknown[] } | unknown[] | null; @@ -184,13 +184,13 @@ lsbench advertises `resolveSupport` for completion items, code actions, inlay hi ### Server to client requests -lsbench answers requests from the server so it never stalls waiting on a client: +lsbench answers requests from the server so it doesn't get stuck waiting on a client: - `workspace/configuration` returns an empty object per item - `client/registerCapability` and `client/unregisterCapability` are accepted (save related registrations are tracked) - `workspace/*/refresh` (semantic tokens, inlay hints, code lenses, inline values, diagnostics) and `window/workDoneProgress/create` are acknowledged - `window/showMessageRequest` is dismissed with `null` -- `workspace/applyEdit` is declined with `applied: false`, lsbench never modifies the workspace +- `workspace/applyEdit` is declined with `applied: false`, lsbench avoids modifying thw workspace using server-initiated requests ### Registering languages