-
Notifications
You must be signed in to change notification settings - Fork 763
/
goLanguageServer.ts
1805 lines (1666 loc) · 59.9 KB
/
goLanguageServer.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Modification copyright 2020 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import cp = require('child_process');
import deepEqual = require('deep-equal');
import fs = require('fs');
import moment = require('moment');
import path = require('path');
import semver = require('semver');
import util = require('util');
import vscode = require('vscode');
import {
CancellationToken,
CloseAction,
CompletionItemKind,
ConfigurationParams,
ConfigurationRequest,
ErrorAction,
ExecuteCommandSignature,
HandleDiagnosticsSignature,
InitializeError,
Message,
ProvideCodeLensesSignature,
ProvideCompletionItemsSignature,
ProvideDocumentFormattingEditsSignature,
ResponseError,
RevealOutputChannelOn
} from 'vscode-languageclient';
import { LanguageClient } from 'vscode-languageclient/node';
import { getGoConfig, getGoplsConfig, IsInCloudIDE } from './config';
import { extensionId } from './const';
import { GoCodeActionProvider } from './goCodeAction';
import { GoDefinitionProvider } from './goDeclaration';
import { toolExecutionEnvironment } from './goEnv';
import { GoHoverProvider } from './goExtraInfo';
import { GoDocumentFormattingEditProvider, usingCustomFormatTool } from './goFormat';
import { GoImplementationProvider } from './goImplementations';
import { installTools, latestToolVersion, promptForMissingTool, promptForUpdatingTool } from './goInstallTools';
import { parseLiveFile } from './goLiveErrors';
import {
buildDiagnosticCollection,
lintDiagnosticCollection,
restartLanguageServer,
vetDiagnosticCollection
} from './goMain';
import { GO_MODE } from './goMode';
import { GoDocumentSymbolProvider } from './goOutline';
import { GoReferenceProvider } from './goReferences';
import { GoRenameProvider } from './goRename';
import { GoSignatureHelpProvider } from './goSignature';
import { outputChannel, updateLanguageServerIconGoStatusBar } from './goStatus';
import { GoCompletionItemProvider } from './goSuggest';
import { GoWorkspaceSymbolProvider } from './goSymbol';
import { getTool, Tool } from './goTools';
import { GoTypeDefinitionProvider } from './goTypeDefinition';
import { getFromGlobalState, getFromWorkspaceState, updateGlobalState, updateWorkspaceState } from './stateUtils';
import {
getBinPath,
getCheckForToolsUpdatesConfig,
getCurrentGoPath,
getGoVersion,
getWorkspaceFolderPath,
removeDuplicateDiagnostics
} from './util';
import { Mutex } from './utils/mutex';
import { getToolFromToolPath } from './utils/pathUtils';
import WebRequest = require('web-request');
import { FoldingContext } from 'vscode';
import { ProvideFoldingRangeSignature } from 'vscode-languageclient/lib/common/foldingRange';
export interface LanguageServerConfig {
serverName: string;
path: string;
version: string;
modtime: Date;
enabled: boolean;
flags: string[];
env: any;
features: {
diagnostics: boolean;
formatter?: GoDocumentFormattingEditProvider;
};
checkForUpdates: string;
}
// Global variables used for management of the language client.
// They are global so that the server can be easily restarted with
// new configurations.
export let languageClient: LanguageClient;
let languageServerDisposable: vscode.Disposable;
export let latestConfig: LanguageServerConfig;
export let serverOutputChannel: vscode.OutputChannel;
export let languageServerIsRunning = false;
const languageServerStartMutex = new Mutex();
let serverTraceChannel: vscode.OutputChannel;
let crashCount = 0;
// Some metrics for automated issue reports:
let manualRestartCount = 0;
let totalStartCount = 0;
// defaultLanguageProviders is the list of providers currently registered.
let defaultLanguageProviders: vscode.Disposable[] = [];
// restartCommand is the command used by the user to restart the language
// server.
let restartCommand: vscode.Disposable;
// lastUserAction is the time of the last user-triggered change.
// A user-triggered change is a didOpen, didChange, didSave, or didClose event.
let lastUserAction: Date = new Date();
// startLanguageServerWithFallback starts the language server, if enabled,
// or falls back to the default language providers.
export async function startLanguageServerWithFallback(ctx: vscode.ExtensionContext, activation: boolean) {
for (const folder of vscode.workspace.workspaceFolders || []) {
switch (folder.uri.scheme) {
case 'vsls':
outputChannel.appendLine(
'Language service on the guest side is disabled. ' +
'The server-side language service will provide the language features.'
);
return;
case 'ssh':
outputChannel.appendLine('The language server is not supported for SSH. Disabling it.');
return;
}
}
const goConfig = getGoConfig();
const cfg = buildLanguageServerConfig(goConfig);
// We have some extra prompts for gopls users and for people who have opted
// out of gopls.
if (activation) {
scheduleGoplsSuggestions();
}
// If the language server is gopls, we enable a few additional features.
// These include prompting for updates and surveys.
if (cfg.serverName === 'gopls') {
const tool = getTool(cfg.serverName);
if (tool) {
// If the language server is turned on because it is enabled by default,
// make sure that the user is using a new enough version.
if (cfg.enabled && languageServerUsingDefault(goConfig)) {
suggestUpdateGopls(tool, cfg);
}
}
}
const unlock = await languageServerStartMutex.lock();
try {
const started = await startLanguageServer(ctx, cfg);
// If the server has been disabled, or failed to start,
// fall back to the default providers, while making sure not to
// re-register any providers.
if (!started && defaultLanguageProviders.length === 0) {
registerDefaultProviders(ctx);
}
languageServerIsRunning = started;
updateLanguageServerIconGoStatusBar(started, goConfig['useLanguageServer'] === true);
} finally {
unlock();
}
}
// scheduleGoplsSuggestions sets timeouts for the various gopls-specific
// suggestions. We check user's gopls versions once per day to prompt users to
// update to the latest version. We also check if we should prompt users to
// fill out the survey.
function scheduleGoplsSuggestions() {
if (IsInCloudIDE) {
return;
}
// Some helper functions.
const usingGopls = (cfg: LanguageServerConfig): boolean => {
return cfg.enabled && cfg.serverName === 'gopls';
};
const installGopls = async (cfg: LanguageServerConfig) => {
const tool = getTool('gopls');
const versionToUpdate = await shouldUpdateLanguageServer(tool, cfg);
if (!versionToUpdate) {
return;
}
// If the user has opted in to automatic tool updates, we can update
// without prompting.
const toolsManagementConfig = getGoConfig()['toolsManagement'];
if (toolsManagementConfig && toolsManagementConfig['autoUpdate'] === true) {
const goVersion = await getGoVersion();
const toolVersion = { ...tool, version: versionToUpdate }; // ToolWithVersion
await installTools([toolVersion], goVersion, true);
} else {
promptForUpdatingTool(tool.name, versionToUpdate);
}
};
const update = async () => {
setTimeout(update, timeDay);
let cfg = buildLanguageServerConfig(getGoConfig());
if (!usingGopls(cfg)) {
// This shouldn't happen, but if the user has a non-gopls language
// server enabled, we shouldn't prompt them to change.
if (cfg.serverName !== '') {
return;
}
// Prompt the user to enable gopls and record what actions they took.
await promptAboutGoplsOptOut(false);
// Check if the language server has now been enabled, and if so,
// it will be installed below.
cfg = buildLanguageServerConfig(getGoConfig());
if (!cfg.enabled) {
return;
}
}
await installGopls(cfg);
};
const survey = async () => {
setTimeout(survey, timeDay);
const cfg = buildLanguageServerConfig(getGoConfig());
if (!usingGopls(cfg)) {
return;
}
maybePromptForGoplsSurvey();
};
setTimeout(update, 10 * timeMinute);
setTimeout(survey, 30 * timeMinute);
}
export async function promptAboutGoplsOptOut(surveyOnly: boolean) {
// Check if the configuration is set in the workspace.
const useLanguageServer = getGoConfig().inspect('useLanguageServer');
const workspace = useLanguageServer.workspaceFolderValue === false || useLanguageServer.workspaceValue === false;
let cfg = getGoplsOptOutConfig(workspace);
const promptFn = async (): Promise<GoplsOptOutConfig> => {
if (cfg.prompt === false) {
return cfg;
}
// Prompt the user ~once a month.
if (cfg.lastDatePrompted && daysBetween(new Date(), cfg.lastDatePrompted) < 30) {
return cfg;
}
cfg.lastDatePrompted = new Date();
if (surveyOnly) {
await promptForGoplsOptOutSurvey(
cfg,
`Looks like you've disabled the Go language server, which is the recommended default for this extension.
Would you be willing to tell us why you've disabled it?`
);
return cfg;
}
const selected = await vscode.window.showInformationMessage(
`We noticed that you have disabled the language server.
It has [stabilized](https://blog.golang.org/gopls-vscode-go) and is now enabled by default in this extension.
Would you like to enable it now?`,
{ title: 'Enable' },
{ title: 'Not now' },
{ title: 'Never' }
);
if (!selected) {
return cfg;
}
switch (selected.title) {
case 'Enable':
{
// Change the user's Go configuration to enable the language server.
// Remove the setting entirely, since it's on by default now.
const goConfig = getGoConfig();
await goConfig.update('useLanguageServer', undefined, vscode.ConfigurationTarget.Global);
if (goConfig.inspect('useLanguageServer').workspaceValue === false) {
await goConfig.update('useLanguageServer', undefined, vscode.ConfigurationTarget.Workspace);
}
if (goConfig.inspect('useLanguageServer').workspaceFolderValue === false) {
await goConfig.update(
'useLanguageServer',
undefined,
vscode.ConfigurationTarget.WorkspaceFolder
);
}
cfg.prompt = false;
}
break;
case 'Not now':
cfg.prompt = true;
break;
case 'Never':
cfg.prompt = false;
await promptForGoplsOptOutSurvey(
cfg,
'No problem. Would you be willing to tell us why you have opted out of the language server?'
);
break;
}
return cfg;
};
cfg = await promptFn();
flushGoplsOptOutConfig(cfg, workspace);
}
async function promptForGoplsOptOutSurvey(cfg: GoplsOptOutConfig, msg: string): Promise<GoplsOptOutConfig> {
const s = await vscode.window.showInformationMessage(msg, { title: 'Yes' }, { title: 'No' });
if (!s) {
return cfg;
}
switch (s.title) {
case 'Yes':
cfg.prompt = false;
await vscode.env.openExternal(vscode.Uri.parse('https://forms.gle/hwC8CncV7Cyc2yBN6'));
break;
case 'No':
break;
}
return cfg;
}
export interface GoplsOptOutConfig {
prompt?: boolean;
lastDatePrompted?: Date;
}
const goplsOptOutConfigKey = 'goplsOptOutConfig';
export const getGoplsOptOutConfig = (workspace: boolean): GoplsOptOutConfig => {
return getStateConfig(goplsOptOutConfigKey, workspace) as GoplsOptOutConfig;
};
function flushGoplsOptOutConfig(cfg: GoplsOptOutConfig, workspace: boolean) {
if (workspace) {
updateWorkspaceState(goplsOptOutConfigKey, JSON.stringify(cfg));
}
updateGlobalState(goplsOptOutConfigKey, JSON.stringify(cfg));
}
async function startLanguageServer(ctx: vscode.ExtensionContext, config: LanguageServerConfig): Promise<boolean> {
// If the client has already been started, make sure to clear existing
// diagnostics and stop it.
if (languageClient) {
if (languageClient.diagnostics) {
languageClient.diagnostics.clear();
}
await languageClient.stop();
if (languageServerDisposable) {
languageServerDisposable.dispose();
}
}
// Check if we should recreate the language client. This may be necessary
// if the user has changed settings in their config.
if (!deepEqual(latestConfig, config)) {
// Track the latest config used to start the language server,
// and rebuild the language client.
latestConfig = config;
languageClient = await buildLanguageClient(buildLanguageClientOption(config));
crashCount = 0;
}
// If the user has not enabled the language server, return early.
if (!config.enabled) {
return false;
}
// Set up the command to allow the user to manually restart the
// language server.
if (!restartCommand) {
restartCommand = vscode.commands.registerCommand('go.languageserver.restart', async () => {
await suggestGoplsIssueReport(
"Looks like you're about to manually restart the language server.",
errorKind.manualRestart
);
manualRestartCount++;
restartLanguageServer();
});
ctx.subscriptions.push(restartCommand);
}
// Before starting the language server, make sure to deregister any
// currently registered language providers.
disposeDefaultProviders();
languageServerDisposable = languageClient.start();
totalStartCount++;
ctx.subscriptions.push(languageServerDisposable);
await languageClient.onReady();
return true;
}
export interface BuildLanguageClientOption extends LanguageServerConfig {
outputChannel?: vscode.OutputChannel;
traceOutputChannel?: vscode.OutputChannel;
}
// buildLanguageClientOption returns the default, extra configuration
// used in building a new LanguageClient instance. Options specified
// in LanguageServerConfig
function buildLanguageClientOption(cfg: LanguageServerConfig): BuildLanguageClientOption {
// Reuse the same output channel for each instance of the server.
if (cfg.enabled) {
if (!serverOutputChannel) {
serverOutputChannel = vscode.window.createOutputChannel(cfg.serverName + ' (server)');
}
if (!serverTraceChannel) {
serverTraceChannel = vscode.window.createOutputChannel(cfg.serverName);
}
}
return Object.assign(
{
outputChannel: serverOutputChannel,
traceOutputChannel: serverTraceChannel
},
cfg
);
}
// buildLanguageClient returns a language client built using the given language server config.
// The returned language client need to be started before use.
export async function buildLanguageClient(cfg: BuildLanguageClientOption): Promise<LanguageClient> {
const goplsWorkspaceConfig = await adjustGoplsWorkspaceConfiguration(cfg, getGoplsConfig(), 'gopls', undefined);
const documentSelector = [
// Filter out unsupported document types, e.g. vsls, git, ssh.
// https://docs.microsoft.com/en-us/visualstudio/liveshare/reference/extensions#visual-studio-code-1
//
// - files
{ language: 'go', scheme: 'file' },
{ language: 'go.mod', scheme: 'file' },
{ language: 'go.sum', scheme: 'file' },
// - unsaved files
{ language: 'go', scheme: 'untitled' },
{ language: 'go.mod', scheme: 'untitled' },
{ language: 'go.sum', scheme: 'untitled' }
];
// Let gopls know about .tmpl - this is experimental, so enable it only in the experimental mode now.
if (isInPreviewMode()) {
documentSelector.push({ language: 'tmpl', scheme: 'file' }, { language: 'tmpl', scheme: 'untitled' });
}
const c = new LanguageClient(
'go', // id
cfg.serverName, // name e.g. gopls
{
command: cfg.path,
args: ['-mode=stdio', ...cfg.flags],
options: { env: cfg.env }
},
{
initializationOptions: goplsWorkspaceConfig,
documentSelector,
uriConverters: {
// Apply file:/// scheme to all file paths.
code2Protocol: (uri: vscode.Uri): string =>
(uri.scheme ? uri : uri.with({ scheme: 'file' })).toString(),
protocol2Code: (uri: string) => vscode.Uri.parse(uri)
},
outputChannel: cfg.outputChannel,
traceOutputChannel: cfg.traceOutputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationFailedHandler: (error: WebRequest.ResponseError<InitializeError>): boolean => {
vscode.window.showErrorMessage(
`The language server is not able to serve any features. Initialization failed: ${error}. `
);
suggestGoplsIssueReport(
'The gopls server failed to initialize',
errorKind.initializationFailure,
error
);
return false;
},
errorHandler: {
error: (error: Error, message: Message, count: number): ErrorAction => {
// Allow 5 crashes before shutdown.
if (count < 5) {
return ErrorAction.Continue;
}
vscode.window.showErrorMessage(
`Error communicating with the language server: ${error}: ${message}.`
);
return ErrorAction.Shutdown;
},
closed: (): CloseAction => {
// Allow 5 crashes before shutdown.
crashCount++;
if (crashCount < 5) {
return CloseAction.Restart;
}
suggestGoplsIssueReport(
'The connection to gopls has been closed. The gopls server may have crashed.',
errorKind.crash
);
return CloseAction.DoNotRestart;
}
},
middleware: {
executeCommand: async (command: string, args: any[], next: ExecuteCommandSignature) => {
try {
return await next(command, args);
} catch (e) {
const answer = await vscode.window.showErrorMessage(
`Command '${command}' failed: ${e}.`,
'Show Trace'
);
if (answer === 'Show Trace') {
serverOutputChannel.show();
}
return null;
}
},
provideFoldingRanges: async (
doc: vscode.TextDocument,
context: FoldingContext,
token: CancellationToken,
next: ProvideFoldingRangeSignature
) => {
const ranges = await next(doc, context, token);
if ((!ranges || ranges.length === 0) && doc.lineCount > 0) {
return undefined;
}
return ranges;
},
provideCodeLenses: async (
doc: vscode.TextDocument,
token: vscode.CancellationToken,
next: ProvideCodeLensesSignature
): Promise<vscode.CodeLens[]> => {
const codeLens = await next(doc, token);
if (!codeLens || codeLens.length === 0) {
return codeLens;
}
const goplsEnabledLens = (getGoConfig().get('overwriteGoplsMiddleware') as any)?.codelens ?? {};
return codeLens.reduce((lenses: vscode.CodeLens[], lens: vscode.CodeLens) => {
switch (lens.command.title) {
case 'run test': {
if (goplsEnabledLens.test) {
return [...lenses, lens];
}
return [...lenses, ...createTestCodeLens(lens)];
}
case 'run benchmark': {
if (goplsEnabledLens.bench) {
return [...lenses, lens];
}
return [...lenses, ...createBenchmarkCodeLens(lens)];
}
default: {
return [...lenses, lens];
}
}
}, []);
},
provideDocumentFormattingEdits: async (
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken,
next: ProvideDocumentFormattingEditsSignature
) => {
if (cfg.features.formatter) {
return cfg.features.formatter.provideDocumentFormattingEdits(document, options, token);
}
return next(document, options, token);
},
handleDiagnostics: (
uri: vscode.Uri,
diagnostics: vscode.Diagnostic[],
next: HandleDiagnosticsSignature
) => {
if (!cfg.features.diagnostics) {
return null;
}
// Deduplicate diagnostics with those found by the other tools.
removeDuplicateDiagnostics(vetDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(buildDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(lintDiagnosticCollection, uri, diagnostics);
return next(uri, diagnostics);
},
provideCompletionItem: async (
document: vscode.TextDocument,
position: vscode.Position,
context: vscode.CompletionContext,
token: vscode.CancellationToken,
next: ProvideCompletionItemsSignature
) => {
const list = await next(document, position, context, token);
if (!list) {
return list;
}
const items = Array.isArray(list) ? list : list.items;
// Give all the candidates the same filterText to trick VSCode
// into not reordering our candidates. All the candidates will
// appear to be equally good matches, so VSCode's fuzzy
// matching/ranking just maintains the natural "sortText"
// ordering. We can only do this in tandem with
// "incompleteResults" since otherwise client side filtering is
// important.
if (!Array.isArray(list) && list.isIncomplete && list.items.length > 1) {
let hardcodedFilterText = items[0].filterText;
if (!hardcodedFilterText) {
// tslint:disable:max-line-length
// According to LSP spec,
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
// if filterText is falsy, the `label` should be used.
// But we observed that's not the case.
// Even if vscode picked the label value, that would
// cause to reorder candiates, which is not ideal.
// Force to use non-empty `label`.
// https://github.com/golang/vscode-go/issues/441
hardcodedFilterText = items[0].label;
}
for (const item of items) {
item.filterText = hardcodedFilterText;
}
}
// TODO(hyangah): when v1.42+ api is available, we can simplify
// language-specific configuration lookup using the new
// ConfigurationScope.
// const paramHintsEnabled = vscode.workspace.getConfiguration(
// 'editor.parameterHints',
// { languageId: 'go', uri: document.uri });
const editorParamHintsEnabled = vscode.workspace.getConfiguration(
'editor.parameterHints',
document.uri
)['enabled'];
const goParamHintsEnabled = vscode.workspace.getConfiguration('[go]', document.uri)[
'editor.parameterHints.enabled'
];
let paramHintsEnabled = false;
if (typeof goParamHintsEnabled === 'undefined') {
paramHintsEnabled = editorParamHintsEnabled;
} else {
paramHintsEnabled = goParamHintsEnabled;
}
// If the user has parameterHints (signature help) enabled,
// trigger it for function or method completion items.
if (paramHintsEnabled) {
for (const item of items) {
if (item.kind === CompletionItemKind.Method || item.kind === CompletionItemKind.Function) {
item.command = {
title: 'triggerParameterHints',
command: 'editor.action.triggerParameterHints'
};
}
}
}
return list;
},
// Keep track of the last file change in order to not prompt
// user if they are actively working.
didOpen: (e, next) => {
lastUserAction = new Date();
next(e);
},
didChange: (e, next) => {
lastUserAction = new Date();
next(e);
},
didClose: (e, next) => {
lastUserAction = new Date();
next(e);
},
didSave: (e, next) => {
lastUserAction = new Date();
next(e);
},
workspace: {
configuration: async (
params: ConfigurationParams,
token: CancellationToken,
next: ConfigurationRequest.HandlerSignature
): Promise<any[] | ResponseError<void>> => {
const configs = await next(params, token);
if (!configs || !Array.isArray(configs)) {
return configs;
}
const ret = [] as any[];
for (let i = 0; i < configs.length; i++) {
let workspaceConfig = configs[i];
if (!!workspaceConfig && typeof workspaceConfig === 'object') {
const scopeUri = params.items[i].scopeUri;
const resource = scopeUri ? vscode.Uri.parse(scopeUri) : undefined;
const section = params.items[i].section;
workspaceConfig = await adjustGoplsWorkspaceConfiguration(
cfg,
workspaceConfig,
section,
resource
);
}
ret.push(workspaceConfig);
}
return ret;
}
}
}
}
);
return c;
}
// filterGoplsDefaultConfigValues removes the entries filled based on the default values
// and selects only those the user explicitly specifies in their settings.
// This returns a new object created based on the filtered properties of workspaceConfig.
// Exported for testing.
export function filterGoplsDefaultConfigValues(workspaceConfig: any, resource: vscode.Uri): any {
if (!workspaceConfig) {
workspaceConfig = {};
}
const cfg = getGoplsConfig(resource);
const filtered = {} as { [key: string]: any };
for (const [key, value] of Object.entries(workspaceConfig)) {
if (typeof value === 'function') {
continue;
}
const c = cfg.inspect(key);
// select only the field whose current value comes from non-default setting.
if (
!c ||
!deepEqual(c.defaultValue, value) ||
// c.defaultValue !== value would be most likely sufficient, except
// when gopls' default becomes different from extension's default.
// So, we also forward the key if ever explicitely stated in one of the
// settings layers.
c.globalLanguageValue !== undefined ||
c.globalValue !== undefined ||
c.workspaceFolderLanguageValue !== undefined ||
c.workspaceFolderValue !== undefined ||
c.workspaceLanguageValue !== undefined ||
c.workspaceValue !== undefined
) {
filtered[key] = value;
}
}
return filtered;
}
// passGoConfigToGoplsConfigValues passes some of the relevant 'go.' settings to gopls settings.
// This assumes `goplsWorkspaceConfig` is an output of filterGoplsDefaultConfigValues,
// so it is modifiable and doesn't contain properties that are not explicitly set.
// - go.buildTags and go.buildFlags are passed as gopls.build.buildFlags
// if goplsWorkspaceConfig doesn't explicitly set it yet.
// Exported for testing.
export function passGoConfigToGoplsConfigValues(goplsWorkspaceConfig: any, goWorkspaceConfig: any): any {
if (!goplsWorkspaceConfig) {
goplsWorkspaceConfig = {};
}
const buildFlags = [] as string[];
if (goWorkspaceConfig?.buildFlags) {
buildFlags.push(...goWorkspaceConfig?.buildFlags);
}
if (goWorkspaceConfig?.buildTags && buildFlags.indexOf('-tags') === -1) {
buildFlags.push('-tags', goWorkspaceConfig?.buildTags);
}
// If gopls.build.buildFlags is set, don't touch it.
if (buildFlags.length > 0 && goplsWorkspaceConfig['build.buildFlags'] === undefined) {
goplsWorkspaceConfig['build.buildFlags'] = buildFlags;
}
return goplsWorkspaceConfig;
}
// adjustGoplsWorkspaceConfiguration filters unnecessary options and adds any necessary, additional
// options to the gopls config. See filterGoplsDefaultConfigValues, passGoConfigToGoplsConfigValues.
// If this is for the nightly extension, we also request to activate features under experiments.
async function adjustGoplsWorkspaceConfiguration(
cfg: LanguageServerConfig,
workspaceConfig: any,
section: string,
resource: vscode.Uri
): Promise<any> {
// We process only gopls config
if (section !== 'gopls') {
return workspaceConfig;
}
workspaceConfig = filterGoplsDefaultConfigValues(workspaceConfig, resource);
// note: workspaceConfig is a modifiable, valid object.
workspaceConfig = passGoConfigToGoplsConfigValues(workspaceConfig, getGoConfig(resource));
// Only modify the user's configurations for the Nightly.
if (!isInPreviewMode()) {
return workspaceConfig;
}
// allExperiments is only available with gopls/v0.5.2 and above.
const version = await getLocalGoplsVersion(cfg);
if (!version) {
return workspaceConfig;
}
const sv = semver.parse(version, true);
if (!sv || semver.lt(sv, 'v0.5.2')) {
return workspaceConfig;
}
if (!workspaceConfig['allExperiments']) {
workspaceConfig['allExperiments'] = true;
}
return workspaceConfig;
}
// createTestCodeLens adds the go.test.cursor and go.debug.cursor code lens
function createTestCodeLens(lens: vscode.CodeLens): vscode.CodeLens[] {
// CodeLens argument signature in gopls is [fileName: string, testFunctions: string[], benchFunctions: string[]],
// so this needs to be deconstructured here
// Note that there will always only be one test function name in this context
if (lens.command.arguments.length < 2 || lens.command.arguments[1].length < 1) {
return [lens];
}
return [
new vscode.CodeLens(lens.range, {
...lens.command,
command: 'go.test.cursor',
arguments: [{ functionName: lens.command.arguments[1][0] }]
}),
new vscode.CodeLens(lens.range, {
title: 'debug test',
command: 'go.debug.cursor',
arguments: [{ functionName: lens.command.arguments[1][0] }]
})
];
}
function createBenchmarkCodeLens(lens: vscode.CodeLens): vscode.CodeLens[] {
// CodeLens argument signature in gopls is [fileName: string, testFunctions: string[], benchFunctions: string[]],
// so this needs to be deconstructured here
// Note that there will always only be one benchmark function name in this context
if (lens.command.arguments.length < 3 || lens.command.arguments[2].length < 1) {
return [lens];
}
return [
new vscode.CodeLens(lens.range, {
...lens.command,
command: 'go.benchmark.cursor',
arguments: [{ functionName: lens.command.arguments[2][0] }]
}),
new vscode.CodeLens(lens.range, {
title: 'debug benchmark',
command: 'go.debug.cursor',
arguments: [{ functionName: lens.command.arguments[2][0] }]
})
];
}
// registerUsualProviders registers the language feature providers if the language server is not enabled.
function registerDefaultProviders(ctx: vscode.ExtensionContext) {
const completionProvider = new GoCompletionItemProvider(ctx.globalState);
defaultLanguageProviders.push(completionProvider);
defaultLanguageProviders.push(
vscode.languages.registerCompletionItemProvider(GO_MODE, completionProvider, '.', '"')
);
defaultLanguageProviders.push(vscode.languages.registerHoverProvider(GO_MODE, new GoHoverProvider()));
defaultLanguageProviders.push(vscode.languages.registerDefinitionProvider(GO_MODE, new GoDefinitionProvider()));
defaultLanguageProviders.push(vscode.languages.registerReferenceProvider(GO_MODE, new GoReferenceProvider()));
defaultLanguageProviders.push(
vscode.languages.registerDocumentSymbolProvider(GO_MODE, new GoDocumentSymbolProvider())
);
defaultLanguageProviders.push(vscode.languages.registerWorkspaceSymbolProvider(new GoWorkspaceSymbolProvider()));
defaultLanguageProviders.push(
vscode.languages.registerSignatureHelpProvider(GO_MODE, new GoSignatureHelpProvider(), '(', ',')
);
defaultLanguageProviders.push(
vscode.languages.registerImplementationProvider(GO_MODE, new GoImplementationProvider())
);
defaultLanguageProviders.push(
vscode.languages.registerDocumentFormattingEditProvider(GO_MODE, new GoDocumentFormattingEditProvider())
);
defaultLanguageProviders.push(
vscode.languages.registerTypeDefinitionProvider(GO_MODE, new GoTypeDefinitionProvider())
);
defaultLanguageProviders.push(vscode.languages.registerRenameProvider(GO_MODE, new GoRenameProvider()));
defaultLanguageProviders.push(vscode.workspace.onDidChangeTextDocument(parseLiveFile, null, ctx.subscriptions));
defaultLanguageProviders.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoCodeActionProvider()));
for (const provider of defaultLanguageProviders) {
ctx.subscriptions.push(provider);
}
}
function disposeDefaultProviders() {
for (const disposable of defaultLanguageProviders) {
disposable.dispose();
}
defaultLanguageProviders = [];
}
export async function watchLanguageServerConfiguration(e: vscode.ConfigurationChangeEvent) {
if (!e.affectsConfiguration('go')) {
return;
}
if (
e.affectsConfiguration('go.useLanguageServer') ||
e.affectsConfiguration('go.languageServerFlags') ||
e.affectsConfiguration('go.languageServerExperimentalFeatures') ||
e.affectsConfiguration('go.alternateTools') ||
e.affectsConfiguration('go.toolsEnvVars') ||
e.affectsConfiguration('go.formatTool')
// TODO: Should we check http.proxy too? That affects toolExecutionEnvironment too.
) {
restartLanguageServer();
}
if (e.affectsConfiguration('go.useLanguageServer') && getGoConfig()['useLanguageServer'] === false) {
promptAboutGoplsOptOut(true);
}
}
export function buildLanguageServerConfig(goConfig: vscode.WorkspaceConfiguration): LanguageServerConfig {
let formatter: GoDocumentFormattingEditProvider;
if (usingCustomFormatTool(goConfig)) {
formatter = new GoDocumentFormattingEditProvider();
}
const cfg: LanguageServerConfig = {
serverName: '',
path: '',
version: '', // compute version lazily
modtime: null,
enabled: goConfig['useLanguageServer'] === true,
flags: goConfig['languageServerFlags'] || [],
features: {
// TODO: We should have configs that match these names.
// Ultimately, we should have a centralized language server config rather than separate fields.
diagnostics: goConfig['languageServerExperimentalFeatures']['diagnostics'],
formatter: formatter
},
env: toolExecutionEnvironment(),
checkForUpdates: getCheckForToolsUpdatesConfig(goConfig)
};
// Don't look for the path if the server is not enabled.
if (!cfg.enabled) {
return cfg;
}
const languageServerPath = getLanguageServerToolPath();
if (!languageServerPath) {
// Assume the getLanguageServerToolPath will show the relevant
// errors to the user. Disable the language server.
cfg.enabled = false;
return cfg;
}
cfg.path = languageServerPath;
cfg.serverName = getToolFromToolPath(cfg.path);
// Get the mtime of the language server binary so that we always pick up
// the right version.
const stats = fs.statSync(languageServerPath);
if (!stats) {
vscode.window.showErrorMessage(`Unable to stat path to language server binary: ${languageServerPath}.
Please try reinstalling it.`);
// Disable the language server.
cfg.enabled = false;
return cfg;
}
cfg.modtime = stats.mtime;
return cfg;
}
/**
*
* Return the absolute path to the correct binary. If the required tool is not available,
* prompt the user to install it. Only gopls is officially supported.
*/
export function getLanguageServerToolPath(): string {
const goConfig = getGoConfig();
// Check that all workspace folders are configured with the same GOPATH.
if (!allFoldersHaveSameGopath()) {
vscode.window.showInformationMessage(
'The Go language server is currently not supported in a multi-root set-up with different GOPATHs.'
);
return;
}
// Get the path to gopls (getBinPath checks for alternate tools).
const goplsBinaryPath = getBinPath('gopls');
if (path.isAbsolute(goplsBinaryPath)) {
return goplsBinaryPath;
}
const alternateTools = goConfig['alternateTools'];
if (alternateTools) {
// The user's alternate language server was not found.
const goplsAlternate = alternateTools['gopls'];
if (goplsAlternate) {
vscode.window.showErrorMessage(
`Cannot find the alternate tool ${goplsAlternate} configured for gopls.
Please install it and reload this VS Code window.`
);
return;
}
}
// Prompt the user to install gopls.
promptForMissingTool('gopls');