-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
CucumberLanguageServer.ts
484 lines (450 loc) · 16.5 KB
/
CucumberLanguageServer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import {
buildSuggestions,
CucumberExpressions,
ExpressionBuilder,
ExpressionBuilderResult,
getGenerateSnippetCodeAction,
getGherkinCompletionItems,
getGherkinDiagnostics,
getGherkinDocumentFeatureSymbol,
getGherkinFormattingEdits,
getGherkinSemanticTokens,
getStepDefinitionLocationLinks,
Index,
jsSearchIndex,
ParserAdapter,
semanticTokenTypes,
Suggestion,
} from '@cucumber/language-service'
import {
CodeAction,
CodeActionKind,
ConfigurationRequest,
Connection,
DidChangeConfigurationNotification,
ServerCapabilities,
TextDocuments,
TextDocumentSyncKind,
} from 'vscode-languageserver'
import { TextDocument } from 'vscode-languageserver-textdocument'
import { buildStepTexts } from './buildStepTexts.js'
import { extname, Files } from './Files.js'
import { getLanguage, loadGherkinSources, loadGlueSources } from './fs.js'
import { getStepDefinitionSnippetLinks } from './getStepDefinitionSnippetLinks.js'
import { Settings } from './types.js'
import { version } from './version.js'
type ServerInfo = {
name: string
version: string
}
// In order to allow 0-config in LSP clients we provide default settings.
// This should be consistent with the `README.md` in `cucumber/vscode` - this is to
// ensure the docs for the plugin reflect the defaults.
const defaultSettings: Settings = {
// IMPORTANT: If you change features or glue below, please also create a PR to update
// the vscode extension defaults accordingly in https://github.com/cucumber/vscode/blob/main/README.md#extension-settings
features: [
// Cucumber-JVM
'src/test/**/*.feature',
// Cucumber-Ruby, Cucumber-Js, Behat, Behave, Godog
'features/**/*.feature',
// Pytest-BDD
'tests/**/*.feature',
// SpecFlow
'*specs*/**/*.feature',
],
glue: [
// Cucumber-JVM
'src/test/**/*.java',
// Cucumber-Js
'features/**/*.ts',
'features/**/*.tsx',
'features/**/*.js',
'features/**/*.jsx',
// Behat
'features/**/*.php',
// Behave
'features/**/*.py',
// Pytest-BDD
'tests/**/*.py',
// Cucumber Rust
'tests/**/*.rs',
'features/**/*.rs',
// Cucumber-Ruby
'features/**/*.rb',
// SpecFlow
'*specs*/**/*.cs',
// Godog
'features/**/*_test.go',
],
parameterTypes: [],
snippetTemplates: {},
}
export class CucumberLanguageServer {
private readonly expressionBuilder: ExpressionBuilder
private searchIndex: Index
private expressionBuilderResult: ExpressionBuilderResult | undefined = undefined
private reindexingTimeout: NodeJS.Timeout
private rootUri: string
private files: Files
public registry: CucumberExpressions.ParameterTypeRegistry
public expressions: readonly CucumberExpressions.Expression[] = []
public suggestions: readonly Suggestion[] = []
constructor(
private readonly connection: Connection,
private readonly documents: TextDocuments<TextDocument>,
parserAdapter: ParserAdapter,
private readonly makeFiles: (rootUri: string) => Files,
private readonly onReindexed: (
registry: CucumberExpressions.ParameterTypeRegistry,
expressions: readonly CucumberExpressions.Expression[],
suggestions: readonly Suggestion[]
) => void
) {
this.expressionBuilder = new ExpressionBuilder(parserAdapter)
connection.onInitialize(async (params) => {
// connection.console.log(`PARAMS: ${JSON.stringify(params, null, 2)}`)
await parserAdapter.init()
if (params.clientInfo) {
connection.console.info(
`Initializing connection from ${params.clientInfo.name} ${params.clientInfo.version}`
)
} else {
connection.console.info(`Initializing connection from unknown client`)
}
if (params.rootPath) {
this.rootUri = `file://${params.rootPath}`
} else if (params.rootUri) {
this.rootUri = params.rootUri
} else if (params.workspaceFolders && params.workspaceFolders.length > 0) {
this.rootUri = params.workspaceFolders[0].uri
} else {
connection.console.error(`Could not determine rootPath`)
}
this.files = makeFiles(this.rootUri)
// Some users have reported that the globs don't find any files. This is to debug that issue
connection.console.info(`Root uri : ${this.rootUri}`)
connection.console.info(`Current dir : ${process.cwd()}`)
if (params.capabilities.workspace?.configuration) {
connection.onDidChangeConfiguration((params) => {
this.connection.console.info(`Client sent workspace/configuration`)
this.reindex(<Settings>params.settings).catch((err) => {
connection.console.error(`Failed to reindex: ${err.message}`)
})
})
try {
await connection.client.register(DidChangeConfigurationNotification.type)
} catch (err) {
connection.console.info(`Client does not support client/registerCapability. This is OK.`)
}
} else {
this.connection.console.info('onDidChangeConfiguration is disabled')
}
if (params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration) {
connection.onDidChangeWatchedFiles(async () => {
connection.console.info(`onDidChangeWatchedFiles`)
})
} else {
connection.console.info('onDidChangeWatchedFiles is disabled')
}
if (params.capabilities.textDocument?.semanticTokens) {
connection.languages.semanticTokens.onDelta(() => {
return {
data: [],
}
})
connection.languages.semanticTokens.onRange(() => {
return {
data: [],
}
})
connection.languages.semanticTokens.on((semanticTokenParams) => {
const doc = documents.get(semanticTokenParams.textDocument.uri)
if (!doc) return { data: [] }
const gherkinSource = doc.getText()
return getGherkinSemanticTokens(
gherkinSource,
(this.expressionBuilderResult?.expressionLinks || []).map((l) => l.expression)
)
})
} else {
connection.console.info('semanticTokens is disabled')
}
if (params.capabilities.textDocument?.completion?.completionItem?.snippetSupport) {
connection.onCompletion((params) => {
if (!this.searchIndex) return []
const doc = documents.get(params.textDocument.uri)
if (!doc) return []
const gherkinSource = doc.getText()
return getGherkinCompletionItems(gherkinSource, params.position, this.searchIndex).slice()
})
connection.onCompletionResolve((item) => item)
} else {
connection.console.info('onCompletion is disabled')
}
if (params.capabilities.textDocument?.formatting) {
connection.onDocumentFormatting((params) => {
const doc = documents.get(params.textDocument.uri)
if (!doc) return []
const gherkinSource = doc.getText()
return getGherkinFormattingEdits(gherkinSource)
})
} else {
connection.console.info('onDocumentFormatting is disabled')
}
if (params.capabilities.textDocument?.codeAction) {
connection.onCodeAction(async (params) => {
const diagnostics = params.context.diagnostics
if (this.expressionBuilderResult) {
const settings = await this.getSettings()
const links = getStepDefinitionSnippetLinks(
this.expressionBuilderResult.expressionLinks.map((l) => l.locationLink)
)
if (links.length === 0) {
connection.console.info(
`Unable to generate step definition. Please create one first manually.`
)
return []
}
const codeActions: CodeAction[] = []
for (const link of links) {
const languageName = getLanguage(extname(link.targetUri))
if (!languageName) {
connection.console.info(
`Unable to generate step definition snippet for unknown extension ${link}`
)
return []
}
const mustacheTemplate = settings.snippetTemplates[languageName]
const createFile = !(await this.files.exists(link.targetUri))
const relativePath = this.files.relativePath(link.targetUri)
const codeAction = getGenerateSnippetCodeAction(
diagnostics,
link,
relativePath,
createFile,
mustacheTemplate,
languageName,
this.expressionBuilderResult.registry
)
if (codeAction) {
codeActions.push(codeAction)
}
}
return codeActions
}
return []
})
} else {
connection.console.info('onCodeAction is disabled')
}
if (params.capabilities.textDocument?.definition) {
connection.onDefinition((params) => {
const doc = documents.get(params.textDocument.uri)
if (!doc || !this.expressionBuilderResult) return []
const gherkinSource = doc.getText()
return getStepDefinitionLocationLinks(
gherkinSource,
params.position,
this.expressionBuilderResult.expressionLinks
)
})
} else {
connection.console.info('onDefinition is disabled')
}
if (params.capabilities.textDocument?.documentSymbol) {
connection.onDocumentSymbol((params) => {
const doc = documents.get(params.textDocument.uri)
if (!doc) return []
const gherkinSource = doc.getText()
const symbol = getGherkinDocumentFeatureSymbol(gherkinSource)
return symbol ? [symbol] : null
})
} else {
connection.console.info('onDocumentSymbol is disabled')
}
return {
capabilities: this.capabilities(),
serverInfo: this.info(),
}
})
connection.onInitialized(() => {
connection.console.info(`${this.info().name} ${this.info().version} initialized`)
this.reindex().catch((err) => connection.console.error(err.message))
})
documents.listen(connection)
// The content of a text document has changed. This event is emitted
// when the text document is first opened or when its content has changed.
documents.onDidChangeContent(async (change) => {
this.scheduleReindexing()
if (change.document.uri.match(/\.feature$/)) {
await this.sendDiagnostics(change.document)
}
})
}
public capabilities(): ServerCapabilities {
return {
textDocumentSync: TextDocumentSyncKind.Incremental,
completionProvider: {
resolveProvider: false,
},
codeActionProvider: {
resolveProvider: false,
workDoneProgress: false,
codeActionKinds: [CodeActionKind.QuickFix],
},
workspace: {
workspaceFolders: {
changeNotifications: true,
supported: true,
},
},
semanticTokensProvider: {
range: false,
full: {
delta: false,
},
legend: {
tokenTypes: semanticTokenTypes,
tokenModifiers: [],
},
},
documentSymbolProvider: {
label: 'Cucumber',
},
documentFormattingProvider: true,
definitionProvider: true,
}
}
public info(): ServerInfo {
return {
name: 'Cucumber Language Server',
version,
}
}
private async sendDiagnostics(textDocument: TextDocument): Promise<void> {
const diagnostics = getGherkinDiagnostics(
textDocument.getText(),
(this.expressionBuilderResult?.expressionLinks || []).map((l) => l.expression)
)
await this.connection.sendDiagnostics({
uri: textDocument.uri,
diagnostics,
})
}
private scheduleReindexing() {
clearTimeout(this.reindexingTimeout)
const timeoutMillis = 3000
this.connection.console.info(`Scheduling reindexing in ${timeoutMillis} ms`)
this.reindexingTimeout = setTimeout(() => {
this.reindex().catch((err) =>
this.connection.console.error(`Failed to reindex: ${err.message}`)
)
}, timeoutMillis)
}
private async getSettings(): Promise<Settings> {
try {
const config = await this.connection.sendRequest(ConfigurationRequest.type, {
items: [
{
section: 'cucumber',
},
],
})
if (config && config.length === 1) {
const settings: Partial<Settings> | null = config[0]
return {
features: getArray(settings?.features, defaultSettings.features),
glue: getArray(settings?.glue, defaultSettings.glue),
parameterTypes: getArray(settings?.parameterTypes, defaultSettings.parameterTypes),
snippetTemplates: {},
}
} else {
this.connection.console.error(
`The client responded with a config we cannot process: ${JSON.stringify(config, null, 2)}`
)
this.connection.console.error(`Using default settings`)
return defaultSettings
}
} catch (err) {
this.connection.console.error(`Failed to request configuration: ${err.message}`)
this.connection.console.error(`Using default settings`)
return defaultSettings
}
}
private async reindex(settings?: Settings) {
if (!settings) {
settings = await this.getSettings()
}
// TODO: Send WorkDoneProgressBegin notification
// https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#workDoneProgress
this.connection.console.info(`Reindexing ${this.rootUri}`)
const gherkinSources = await loadGherkinSources(this.files, settings.features)
this.connection.console.info(
`* Found ${gherkinSources.length} feature file(s) in ${JSON.stringify(settings.features)}`
)
const stepTexts = gherkinSources.reduce<readonly string[]>(
(prev, gherkinSource) => prev.concat(buildStepTexts(gherkinSource.content)),
[]
)
this.connection.console.info(`* Found ${stepTexts.length} steps in those feature files`)
const glueSources = await loadGlueSources(this.files, settings.glue)
this.connection.console.info(
`* Found ${glueSources.length} glue file(s) in ${JSON.stringify(settings.glue)}`
)
this.expressionBuilderResult = this.expressionBuilder.build(
glueSources,
settings.parameterTypes
)
this.connection.console.info(
`* Found ${this.expressionBuilderResult.parameterTypeLinks.length} parameter types in those glue files`
)
for (const parameterTypeLink of this.expressionBuilderResult.parameterTypeLinks) {
this.connection.console.info(
` * {${parameterTypeLink.parameterType.name}} = ${parameterTypeLink.parameterType.regexpStrings}`
)
}
this.connection.console.info(
`* Found ${this.expressionBuilderResult.expressionLinks.length} step definitions in those glue files`
)
for (const error of this.expressionBuilderResult.errors) {
this.connection.console.error(`* Step Definition errors: ${error.stack}`)
}
// Send diagnostics for all documents now that we're updated
const gherkinDocuments = this.documents.all().filter((doc) => doc.uri.match(/\.feature$/))
await Promise.all(
gherkinDocuments.map((doc) =>
this.sendDiagnostics(doc).catch((err) =>
this.connection.console.error(`Error: ${err.message}`)
)
)
)
// Tell the client to update all semantic tokens
this.connection.languages.semanticTokens.refresh()
try {
const expressions = this.expressionBuilderResult.expressionLinks.map((l) => l.expression)
const suggestions = buildSuggestions(
this.expressionBuilderResult.registry,
stepTexts,
expressions
)
this.connection.console.info(`* Built ${suggestions.length} suggestions for auto complete`)
this.searchIndex = jsSearchIndex(suggestions)
const registry = this.expressionBuilderResult.registry
this.registry = registry
this.expressions = expressions
this.suggestions = suggestions
this.onReindexed(registry, expressions, suggestions)
} catch (err) {
this.connection.console.error(err.stack)
this.connection.console.error(
'Please report an issue at https://github.com/cucumber/language-service/issues with the above stack trace'
)
}
// TODO: Send WorkDoneProgressEnd notification
}
}
function getArray<T>(arr: readonly T[] | undefined | null, defaultArr: readonly T[]): readonly T[] {
if (!Array.isArray(arr) || arr.length === 0) return defaultArr
return arr
}