diff --git a/package-lock.json b/package-lock.json index 6d426c8a..4046acec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,10 @@ "version": "2.0.0", "license": "MIT", "dependencies": { + "@cucumber/gherkin": "^32.2.0", "@cucumber/gherkin-utils": "^12.0.0", "@cucumber/language-service": "^2.0.0", + "@cucumber/messages": "^34.0.0", "fast-glob": "3.3.3", "source-map-support": "0.5.21", "vscode-languageserver": "11.0.0", diff --git a/package.json b/package.json index f9298fb7..f937b844 100644 --- a/package.json +++ b/package.json @@ -83,8 +83,10 @@ "vscode-languageserver-protocol": "3.18.5" }, "dependencies": { + "@cucumber/gherkin": "^32.2.0", "@cucumber/gherkin-utils": "^12.0.0", "@cucumber/language-service": "^2.0.0", + "@cucumber/messages": "^34.0.0", "fast-glob": "3.3.3", "source-map-support": "0.5.21", "vscode-languageserver": "11.0.0", diff --git a/src/CucumberLanguageServer.ts b/src/CucumberLanguageServer.ts index c96f7827..ff6297eb 100644 --- a/src/CucumberLanguageServer.ts +++ b/src/CucumberLanguageServer.ts @@ -13,6 +13,7 @@ import { type Index, jsSearchIndex, type ParserAdapter, + type Source, type Suggestion, semanticTokenTypes, } from '@cucumber/language-service' @@ -32,6 +33,7 @@ import { buildStepTexts } from './buildStepTexts.js' import { extname, type Files } from './Files.js' import { getLanguage, loadGherkinSources, loadGlueSources } from './fs.js' import { getStepDefinitionSnippetLinks } from './getStepDefinitionSnippetLinks.js' +import { getExpressionLinksAt, getStepReferences } from './getStepReferences.js' import type { Settings } from './types.js' import { version } from './version.js' @@ -93,6 +95,7 @@ export class CucumberLanguageServer { private readonly expressionBuilder: ExpressionBuilder private searchIndex!: Index private expressionBuilderResult: ExpressionBuilderResult | undefined = undefined + private gherkinSources: readonly Source<'gherkin'>[] = [] private reindexingTimeout!: NodeJS.Timeout private rootUri!: string private files!: Files @@ -285,6 +288,21 @@ export class CucumberLanguageServer { connection.console.info('onDefinition is disabled') } + if (params.capabilities.textDocument?.references) { + connection.onReferences((params) => { + if (!this.expressionBuilderResult) return [] + const expressionLinks = getExpressionLinksAt( + this.expressionBuilderResult.expressionLinks, + params.textDocument.uri, + params.position + ) + if (expressionLinks.length === 0) return [] + return getStepReferences(this.gherkinSources, expressionLinks).slice() + }) + } else { + connection.console.info('onReferences is disabled') + } + if (params.capabilities.textDocument?.documentSymbol) { connection.onDocumentSymbol((params) => { const doc = documents.get(params.textDocument.uri) @@ -354,6 +372,7 @@ export class CucumberLanguageServer { }, documentFormattingProvider: true, definitionProvider: true, + referencesProvider: true, } } @@ -427,6 +446,7 @@ export class CucumberLanguageServer { this.connection.console.info(`Reindexing ${this.rootUri}`) const gherkinSources = await loadGherkinSources(this.files, settings.features) + this.gherkinSources = gherkinSources this.connection.console.info( `* Found ${gherkinSources.length} feature file(s) in ${JSON.stringify(settings.features)}` ) diff --git a/src/getStepReferences.ts b/src/getStepReferences.ts new file mode 100644 index 00000000..eb8fb9b2 --- /dev/null +++ b/src/getStepReferences.ts @@ -0,0 +1,79 @@ +import { compile } from '@cucumber/gherkin' +import { walkGherkinDocument } from '@cucumber/gherkin-utils' +import { ExpressionLink, parseGherkinDocument, Source } from '@cucumber/language-service' +import { IdGenerator, Step } from '@cucumber/messages' +import { Location, LocationLink, Position, Range } from 'vscode-languageserver-types' + +const newId = IdGenerator.uuid() + +/** + * Returns the step definitions that contain the given position in a glue file + * (anywhere in the step definition, from its expression to the end of its body). + */ +export function getExpressionLinksAt( + expressionLinks: readonly ExpressionLink[], + uri: string, + position: Position +): readonly ExpressionLink[] { + return expressionLinks.filter( + ({ locationLink }) => + locationLink.targetUri === uri && contains(definitionRange(locationLink), position) + ) +} + +// A targetRange starting at the top of the file is the whole file +// (cucumber/language-service#315); use the expression literal instead. +function definitionRange(locationLink: LocationLink): Range { + const { targetRange, targetSelectionRange } = locationLink + const startsAtTop = targetRange.start.line === 0 && targetRange.start.character === 0 + const selectionAtTop = + targetSelectionRange.start.line === 0 && targetSelectionRange.start.character === 0 + return startsAtTop && !selectionAtTop ? targetSelectionRange : targetRange +} + +function contains(range: Range, position: Position): boolean { + if (position.line < range.start.line || position.line > range.end.line) return false + if (position.line === range.start.line && position.character < range.start.character) return false + if (position.line === range.end.line && position.character > range.end.character) return false + return true +} + +/** + * Returns the location of every Gherkin step that matches at least one of the + * expressions. Scenario Outline steps are matched with their Examples values + * substituted (via pickles) and reported once, at the outline step's location. + */ +export function getStepReferences( + gherkinSources: readonly Source<'gherkin'>[], + expressionLinks: readonly ExpressionLink[] +): readonly Location[] { + const locations: Location[] = [] + for (const source of gherkinSources) { + const { gherkinDocument } = parseGherkinDocument(source.content) + if (!gherkinDocument) continue + const stepsById = walkGherkinDocument(gherkinDocument, new Map(), { + step(step, acc) { + acc.set(step.id, step) + return acc + }, + }) + const seen = new Set() + for (const pickle of compile(gherkinDocument, source.uri, newId)) { + for (const pickleStep of pickle.steps) { + const step = stepsById.get(pickleStep.astNodeIds[0]) + if (!step || seen.has(step.id)) continue + if (expressionLinks.some((link) => link.expression.match(pickleStep.text) !== null)) { + seen.add(step.id) + locations.push(Location.create(source.uri, stepRange(step))) + } + } + } + } + return locations +} + +function stepRange(step: Step): Range { + const line = step.location.line - 1 + const start = (step.location.column ?? 1) - 1 + return Range.create(line, start, line, start + step.keyword.length + step.text.length) +} diff --git a/test/getStepReferences.test.ts b/test/getStepReferences.test.ts new file mode 100644 index 00000000..46301cff --- /dev/null +++ b/test/getStepReferences.test.ts @@ -0,0 +1,119 @@ +import { CucumberExpressions, ExpressionLink, Source } from '@cucumber/language-service' +import assert from 'assert' +import { Location, Position, Range } from 'vscode-languageserver-types' + +import { getExpressionLinksAt, getStepReferences } from '../src/getStepReferences.js' + +const glueUri = 'file:///home/testdata/rust/steps.rs' + +// A step definition: the expression literal on `line`, the function body on the next two lines. +function link(expression: CucumberExpressions.Expression, line: number): ExpressionLink { + return { + expression, + locationLink: { + targetUri: glueUri, + targetRange: Range.create(line, 12, line + 2, 1), + targetSelectionRange: Range.create(line, 12, line, 40), + }, + } +} + +describe('getExpressionLinksAt', () => { + const registry = new CucumberExpressions.ParameterTypeRegistry() + const links = [ + link(new CucumberExpressions.CucumberExpression('I have {int} cukes', registry), 3), + link(new CucumberExpressions.CucumberExpression('I eat {int} cukes', registry), 8), + ] + + it('returns the links whose expression contains the position', () => { + const result = getExpressionLinksAt(links, glueUri, Position.create(8, 20)) + assert.deepStrictEqual(result, [links[1]]) + }) + + it('returns the links whose body contains the position', () => { + const result = getExpressionLinksAt(links, glueUri, Position.create(4, 0)) + assert.deepStrictEqual(result, [links[0]]) + }) + + it('returns nothing between step definitions', () => { + assert.deepStrictEqual(getExpressionLinksAt(links, glueUri, Position.create(6, 0)), []) + }) + + it('falls back to the expression literal when the target range is the whole file', () => { + const wholeFile: ExpressionLink = { + ...links[0], + locationLink: { ...links[0].locationLink, targetRange: Range.create(0, 0, 100, 0) }, + } + assert.deepStrictEqual(getExpressionLinksAt([wholeFile], glueUri, Position.create(3, 20)), [ + wholeFile, + ]) + assert.deepStrictEqual(getExpressionLinksAt([wholeFile], glueUri, Position.create(4, 0)), []) + }) + + it('returns nothing for another file', () => { + assert.deepStrictEqual( + getExpressionLinksAt(links, 'file:///home/testdata/rust/other.rs', Position.create(3, 20)), + [] + ) + }) +}) + +describe('getStepReferences', () => { + const registry = new CucumberExpressions.ParameterTypeRegistry() + const haveCukes = link( + new CucumberExpressions.CucumberExpression('I have {int} cukes', registry), + 3 + ) + const eatCukes = link( + new CucumberExpressions.RegularExpression(/^I eat (\d+) cukes$/, registry), + 8 + ) + + const featureUri = 'file:///home/testdata/features/cukes.feature' + const source: Source<'gherkin'> = { + languageName: 'gherkin', + uri: featureUri, + content: `Feature: Cukes + + Scenario: Breakfast + Given I have 3 cukes + When I eat 1 cukes + Then 2 cukes remain + + Scenario Outline: Meals + Given I have cukes + When I eat cukes + + Examples: + | stock | amount | + | 5 | 2 | + | 8 | 3 | +`, + } + + it('finds steps matching a Cucumber Expression', () => { + const result = getStepReferences([source], [haveCukes]) + assert.deepStrictEqual(result, [ + Location.create(featureUri, Range.create(3, 4, 3, 24)), + Location.create(featureUri, Range.create(8, 4, 8, 30)), + ]) + }) + + it('finds Scenario Outline steps once, with Examples values substituted', () => { + const result = getStepReferences([source], [eatCukes]) + assert.deepStrictEqual(result, [ + Location.create(featureUri, Range.create(4, 4, 4, 22)), + Location.create(featureUri, Range.create(9, 4, 9, 29)), + ]) + }) + + it('matches against the union of several links', () => { + const result = getStepReferences([source], [haveCukes, eatCukes]) + assert.strictEqual(result.length, 4) + }) + + it('returns nothing when no step matches', () => { + const none = link(new CucumberExpressions.CucumberExpression('nothing here', registry), 1) + assert.deepStrictEqual(getStepReferences([source], [none]), []) + }) +})