Debian Codegraph @

gopls/internal/server/general.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package server
6
7 // This file defines server methods related to initialization,
8 // options, shutdown, and exit.
9
10 import (
11 "context"
12 "encoding/json"
13 "errors"
14 "fmt"
15 "go/build"
16 "os"
17 "path"
18 "path/filepath"
19 "slices"
20 "sort"
21 "strings"
22 "sync"
23
24 "golang.org/x/telemetry/counter"
25 "golang.org/x/tools/gopls/internal/cache"
26 "golang.org/x/tools/gopls/internal/debug"
27 debuglog "golang.org/x/tools/gopls/internal/debug/log"
28 "golang.org/x/tools/gopls/internal/file"
29 "golang.org/x/tools/gopls/internal/filecache"
30 "golang.org/x/tools/gopls/internal/filewatcher"
31 "golang.org/x/tools/gopls/internal/protocol"
32 "golang.org/x/tools/gopls/internal/protocol/semtok"
33 "golang.org/x/tools/gopls/internal/settings"
34 "golang.org/x/tools/gopls/internal/telemetry"
35 "golang.org/x/tools/gopls/internal/util/bug"
36 "golang.org/x/tools/gopls/internal/util/goversion"
37 "golang.org/x/tools/gopls/internal/util/moremaps"
38 "golang.org/x/tools/gopls/internal/util/moreslices"
39 "golang.org/x/tools/internal/event"
40 "golang.org/x/tools/internal/jsonrpc2"
41 )
42
43 func (s *server) Initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) {
44 ctx, done := event.Start(ctx, "server.Initialize")
45 defer done()
46
47 var clientName string
48 if params != nil && params.ClientInfo != nil {
49 clientName = params.ClientInfo.Name
50 }
51 recordClientInfo(clientName)
52
53 s.stateMu.Lock()
54 if s.state >= serverInitializing {
55 defer s.stateMu.Unlock()
56 return nil, fmt.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state)
57 }
58 s.state = serverInitializing
59 s.stateMu.Unlock()
60
61 s.progress.SetSupportsWorkDoneProgress(params.Capabilities.Window.WorkDoneProgress)
62
63 options := s.Options().Clone()
64 // TODO(rfindley): eliminate this defer.
65 defer func() { s.SetOptions(options) }()
66
67 // Process initialization options.
68 {
69 res, errs := options.Set(params.InitializationOptions)
70 s.handleOptionResult(ctx, res, errs)
71 }
72 options.ForClientCapabilities(params.ClientInfo, params.Capabilities)
73
74 if options.MaxFileCacheBytes > 0 {
75 filecache.SetBudget(options.MaxFileCacheBytes)
76 }
77
78 if options.ShowBugReports {
79 // Report the next bug that occurs on the server.
80 bug.Handle(func(b bug.Bug) {
81 msg := &protocol.ShowMessageParams{
82 Type: protocol.Error,
83 Message: fmt.Sprintf("A bug occurred on the server: %s\nLocation:%s", b.Description, b.Key),
84 }
85 go s.eventuallyShowMessage(context.Background(), msg)
86 })
87 }
88
89 folders := params.WorkspaceFolders
90 if len(folders) == 0 {
91 if params.RootURI != "" {
92 folders = []protocol.WorkspaceFolder{{
93 URI: string(params.RootURI),
94 Name: path.Base(params.RootURI.Path()),
95 }}
96 }
97 }
98 s.pendingFolders = append(s.pendingFolders, folders...)
99
100 var codeActionProvider any = true
101 if ca := params.Capabilities.TextDocument.CodeAction; len(ca.CodeActionLiteralSupport.CodeActionKind.ValueSet) > 0 {
102 // If the client has specified CodeActionLiteralSupport,
103 // send the code actions we support.
104 //
105 // Using CodeActionOptions is only valid if codeActionLiteralSupport is set.
106 codeActionProvider = &protocol.CodeActionOptions{
107 CodeActionKinds: s.getSupportedCodeActions(),
108 ResolveProvider: true,
109 }
110 }
111
112 var diagnosticProvider *protocol.Or_ServerCapabilities_diagnosticProvider
113 if options.PullDiagnostics {
114 diagnosticProvider = &protocol.Or_ServerCapabilities_diagnosticProvider{
115 Value: protocol.DiagnosticOptions{
116 InterFileDependencies: true,
117 WorkspaceDiagnostics: false, // we don't support workspace/diagnostic
118 },
119 }
120 }
121
122 var renameOpts any = true
123 if r := params.Capabilities.TextDocument.Rename; r != nil && r.PrepareSupport {
124 renameOpts = protocol.RenameOptions{
125 PrepareProvider: r.PrepareSupport,
126 }
127 }
128
129 var semanticTokenProvider any
130 if options.SemanticTokens || options.ConfigurationSupported {
131 // Also provide the semantic token provider if the client supports
132 // Configuration calls. Reasoning:
133 //
134 // There are two ways to tell the client that this LSP server supports
135 // semantic token calls:
136 // 1. Return the semanticTokenProvider here in the `InitializeResult`
137 // 2. Anytime after Initialize() finishes, call
138 // client.register("textDocument/semanticTokens") with the
139 // semanticTokenProvider. Doing it this way would have many
140 // specific requirements:
141 // * The client must have set
142 // `SemanticTokensClientCapabilities.dynamicRegistration = true`.
143 // * The server must maintain the state of what it has actively
144 // registered on the client, as the LSP doesn't allow the same
145 // capability to be registered multiple times.
146 // * As most clients don't support dynamic registration, we wouldn't
147 // be able to just support that route, we would have to maintain
148 // both static and dynamic registration paths.
149 //
150 // For all these reasons, we choose not to support the dynamic
151 // registration and fully rely on option 1.
152 //
153 // The only way the server would ever change to start/stop supporting
154 // semantic tokens is on a user's change of setting: `semanticTokens`.
155 // gopls only *retrieves* updated user configuration by sending
156 // `workspace/configuration` requests to the client.
157 // `options.ConfigurationSupported` indicates whether the client
158 // supports those calls and gopls doesn't send the `configuration`
159 // requests if not.
160 //
161 // gopls also will only send `workspace/configuration` requests after
162 // it receives a `workspace/didChangeConfiguration` request or if a new
163 // directory is added to the current session. We can't determine
164 // through the `ClientCapabilities` whether the either of these things
165 // can happen, so we have to always assume that they will.
166 //
167 // To conclude, the only signal to guarantee that gopls will never see
168 // updated user configs is if the client has
169 // `options.ConfigurationSupported = false`. So if the user currently
170 // has semanticTokens disabled AND their client doesn't support
171 // configuration calls, we know we never need to support semantic
172 // tokens and can inform the client by *not* returning a
173 // semanticTokenProvider. In any other case (the current scope) we need
174 // to return a semanticTokenProvider here so that the client will try
175 // to send `semanticToken` requests in the possibility that the user's
176 // gopls settings at that point allow us to return them.
177 semanticTokenProvider = protocol.SemanticTokensOptions{
178 Range: &protocol.Or_SemanticTokensOptions_range{Value: true},
179 Full: &protocol.Or_SemanticTokensOptions_full{Value: true},
180 Legend: protocol.SemanticTokensLegend{
181 TokenTypes: moreslices.ConvertStrings[string](semtok.Types),
182 TokenModifiers: moreslices.ConvertStrings[string](semtok.Modifiers),
183 },
184 }
185 // Note: If we ever get to a point that the performance of
186 // semanticTokens isn't significantly different from other file level
187 // LSP methods, we should remove this option alltogether and always
188 // return the semanticTokenProvider. At that point users can configure
189 // whether their client will send calls for the semantic tokens. This
190 // is a setting that should ideally live on the front-end.
191 }
192
193 versionInfo := debug.VersionInfo()
194
195 goplsVersion, err := json.Marshal(versionInfo)
196 if err != nil {
197 return nil, err
198 }
199
200 return &protocol.InitializeResult{
201 Capabilities: protocol.ServerCapabilities{
202 CallHierarchyProvider: &protocol.Or_ServerCapabilities_callHierarchyProvider{Value: true},
203 CodeActionProvider: codeActionProvider,
204 CodeLensProvider: &protocol.CodeLensOptions{}, // must be non-nil to enable the code lens capability
205 CompletionProvider: &protocol.CompletionOptions{
206 TriggerCharacters: []string{"."},
207 },
208 DefinitionProvider: &protocol.Or_ServerCapabilities_definitionProvider{Value: true},
209 TypeDefinitionProvider: &protocol.Or_ServerCapabilities_typeDefinitionProvider{Value: true},
210 ImplementationProvider: &protocol.Or_ServerCapabilities_implementationProvider{Value: true},
211 DocumentFormattingProvider: &protocol.Or_ServerCapabilities_documentFormattingProvider{Value: true},
212 DocumentSymbolProvider: &protocol.Or_ServerCapabilities_documentSymbolProvider{Value: true},
213 WorkspaceSymbolProvider: &protocol.Or_ServerCapabilities_workspaceSymbolProvider{Value: true},
214 ExecuteCommandProvider: &protocol.ExecuteCommandOptions{
215 Commands: protocol.NonNilSlice(options.SupportedCommands),
216 },
217 FoldingRangeProvider: &protocol.Or_ServerCapabilities_foldingRangeProvider{Value: true},
218 HoverProvider: &protocol.Or_ServerCapabilities_hoverProvider{Value: true},
219 DocumentHighlightProvider: &protocol.Or_ServerCapabilities_documentHighlightProvider{Value: true},
220 DocumentLinkProvider: &protocol.DocumentLinkOptions{},
221 InlayHintProvider: protocol.InlayHintOptions{},
222 DiagnosticProvider: diagnosticProvider,
223 ReferencesProvider: &protocol.Or_ServerCapabilities_referencesProvider{Value: true},
224 RenameProvider: renameOpts,
225 SelectionRangeProvider: &protocol.Or_ServerCapabilities_selectionRangeProvider{Value: true},
226 SemanticTokensProvider: semanticTokenProvider,
227 SignatureHelpProvider: &protocol.SignatureHelpOptions{
228 TriggerCharacters: []string{"(", ","},
229 // Used to update or dismiss signature help when it's already active,
230 // typically after a call expression is closed.
231 RetriggerCharacters: []string{")"},
232 },
233 TextDocumentSync: &protocol.TextDocumentSyncOptions{
234 Change: protocol.Incremental,
235 OpenClose: true,
236 Save: &protocol.SaveOptions{
237 IncludeText: false,
238 },
239 },
240 TypeHierarchyProvider: &protocol.Or_ServerCapabilities_typeHierarchyProvider{Value: true},
241 Workspace: &protocol.WorkspaceOptions{
242 WorkspaceFolders: &protocol.WorkspaceFolders5Gn{
243 Supported: true,
244 ChangeNotifications: "workspace/didChangeWorkspaceFolders",
245 },
246 FileOperations: &protocol.FileOperationOptions{
247 DidCreate: &protocol.FileOperationRegistrationOptions{
248 Filters: []protocol.FileOperationFilter{{
249 Scheme: "file",
250 // gopls is only interested with files in .go extension.
251 Pattern: protocol.FileOperationPattern{Glob: "**/*.go"},
252 }},
253 },
254 },
255 },
256 Experimental: map[string]any{
257 // interactiveResolveProvider lists the LSP objects that support
258 // an interactive resolution stage. For instance, the presence of
259 // "command" indicates that the server handles "command/resolve"
260 // requests.
261 //
262 // Due to the existence of "codeAction/resolve" and language
263 // clients that resolve code action eagerly, "codeAction" can
264 // never be interactively resolved.
265 //
266 // TODO(hxjiang): experiment with interactively resolving
267 // "RenameParams". See golang/go#69107.
268 "interactiveResolveProvider": protocol.InteractiveResolveOptions{
269 Kinds: []string{"command"},
270 },
271 },
272 },
273 ServerInfo: &protocol.ServerInfo{
274 Name: "gopls",
275 Version: string(goplsVersion),
276 },
277 }, nil
278 }
279
280 func (s *server) Initialized(ctx context.Context, params *protocol.InitializedParams) error {
281 ctx, done := event.Start(ctx, "server.Initialized")
282 defer done()
283
284 s.stateMu.Lock()
285 if s.state >= serverInitialized {
286 defer s.stateMu.Unlock()
287 return fmt.Errorf("%w: initialized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state)
288 }
289 s.state = serverInitialized
290 s.stateMu.Unlock()
291
292 for _, not := range s.notifications {
293 s.client.ShowMessage(ctx, not) // ignore error
294 }
295 s.notifications = nil
296
297 s.addFolders(ctx, s.pendingFolders)
298
299 s.pendingFolders = nil
300 s.checkViewGoVersions()
301
302 var registrations []protocol.Registration
303 options := s.Options()
304 if options.ConfigurationSupported && options.DynamicConfigurationSupported {
305 // Even though we are registering `didChangeConfiguration` based on the
306 // client capabilities, clients can and do still send requests to it
307 // even if it's not registered.
308 registrations = append(registrations, protocol.Registration{
309 ID: "workspace/didChangeConfiguration",
310 Method: "workspace/didChangeConfiguration",
311 })
312 }
313 if len(registrations) > 0 {
314 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
315 Registrations: registrations,
316 }); err != nil {
317 return err
318 }
319 }
320
321 // Ask (maybe) about enabling telemetry. Do this asynchronously, as it's OK
322 // for users to ignore or dismiss the question.
323 go s.maybePromptForTelemetry(ctx, options.TelemetryPrompt)
324
325 return nil
326 }
327
328 // checkViewGoVersions checks whether any Go version used by a view is too old,
329 // raising a showMessage notification if so.
330 //
331 // It should be called after views change.
332 func (s *server) checkViewGoVersions() {
333 oldestVersion, fromBuild := go1Point(), true
334 for _, view := range s.session.Views() {
335 viewVersion := view.GoVersion()
336 if oldestVersion == -1 || viewVersion < oldestVersion {
337 oldestVersion, fromBuild = viewVersion, false
338 }
339 if viewVersion >= 0 {
340 counter.Inc(fmt.Sprintf("gopls/goversion:1.%d", viewVersion))
341 }
342 }
343
344 if msg, isError := goversion.Message(oldestVersion, fromBuild); msg != "" {
345 mType := protocol.Warning
346 if isError {
347 mType = protocol.Error
348 }
349 s.eventuallyShowMessage(context.Background(), &protocol.ShowMessageParams{
350 Type: mType,
351 Message: msg,
352 })
353 }
354 }
355
356 // go1Point returns the x in Go 1.x. If an error occurs extracting the go
357 // version, it returns -1.
358 //
359 // Copied from the testenv package.
360 func go1Point() int {
361 for _, tag := range slices.Backward(build.Default.ReleaseTags) {
362 var version int
363 if _, err := fmt.Sscanf(tag, "go1.%d", &version); err != nil {
364 continue
365 }
366 return version
367 }
368 return -1
369 }
370
371 // addFolders adds the specified list of "folders" (that's Windows for
372 // directories) to the session. It does not return an error, though it
373 // may report an error to the client over LSP if one or more folders
374 // had problems, for example, folders with unsupported file system.
375 func (s *server) addFolders(ctx context.Context, folders []protocol.WorkspaceFolder) {
376 originalViews := len(s.session.Views())
377 viewErrors := make(map[protocol.URI]error)
378
379 // Skip non-'file' scheme, or invalid workspace folders,
380 // and log them form error reports.
381 // VS Code's file system API
382 // (https://code.visualstudio.com/api/references/vscode-api#FileSystem)
383 // allows extension to define their own schemes and register
384 // them with the workspace. We've seen gitlens://, decompileFs://, etc
385 // but the list can grow over time.
386 var filtered []protocol.WorkspaceFolder
387 for _, f := range folders {
388 uri, err := protocol.ParseDocumentURI(f.URI)
389 if err != nil {
390 debuglog.Warning.Logf(ctx, "skip adding virtual folder %q - invalid folder URI: %v", f.Name, err)
391 continue
392 }
393 if s.session.HasView(uri) {
394 debuglog.Warning.Logf(ctx, "skip adding the already added folder %q - its view has been created before", f.Name)
395 continue
396 }
397 filtered = append(filtered, f)
398 }
399 folders = filtered
400
401 var ndiagnose sync.WaitGroup // number of unfinished diagnose calls
402 if s.Options().VerboseWorkDoneProgress {
403 work := s.progress.Start(ctx, DiagnosticWorkTitle(FromInitialWorkspaceLoad), "Calculating diagnostics for initial workspace load...", nil, nil)
404 defer func() {
405 go func() {
406 ndiagnose.Wait()
407 work.End(ctx, "Done.")
408 }()
409 }()
410 }
411 // Only one view gets to have a workspace.
412 var nsnapshots sync.WaitGroup // number of unfinished snapshot initializations
413 for _, folder := range folders {
414 uri, err := protocol.ParseDocumentURI(folder.URI)
415 if err != nil {
416 viewErrors[folder.URI] = fmt.Errorf("invalid folder URI: %v", err)
417 continue
418 }
419 work := s.progress.Start(ctx, "Setting up workspace", "Loading packages...", nil, nil)
420 snapshot, release, err := s.addView(ctx, folder.Name, uri)
421 if err != nil {
422 if err == cache.ErrViewExists {
423 continue
424 }
425 viewErrors[folder.URI] = err
426 work.End(ctx, fmt.Sprintf("Error loading packages: %s", err))
427 continue
428 }
429 // Inv: release() must be called once.
430
431 // Initialize snapshot asynchronously.
432 initialized := make(chan struct{})
433 nsnapshots.Add(1)
434 go func() {
435 snapshot.AwaitInitialized(ctx)
436 work.End(ctx, "Finished loading packages.")
437 nsnapshots.Done()
438 close(initialized) // signal
439 }()
440
441 // Diagnose the newly created view asynchronously.
442 ndiagnose.Go(func() {
443 s.diagnoseSnapshot(snapshot.BackgroundContext(), snapshot, nil, 0)
444 <-initialized
445 release()
446 })
447 }
448
449 // Wait for snapshots to be initialized so that all files are known.
450 // (We don't need to wait for diagnosis to finish.)
451 nsnapshots.Wait()
452
453 // Register for file watching notifications, if they are supported.
454 if err := s.updateWatchedDirectories(ctx); err != nil {
455 event.Error(ctx, "failed to register for file watching notifications", err)
456 }
457
458 // Report any errors using the protocol.
459 if len(viewErrors) > 0 {
460 var errMsg strings.Builder
461 fmt.Fprintf(&errMsg, "Error loading workspace folders (expected %v, got %v)\n", len(folders), len(s.session.Views())-originalViews)
462 for uri, err := range viewErrors {
463 fmt.Fprintf(&errMsg, "failed to load view for %s: %v\n", uri, err)
464 }
465 showMessage(ctx, s.client, protocol.Error, errMsg.String())
466 }
467 }
468
469 // updateWatchedDirectories syncs the server-side file watcher and client-side
470 // registrations with the current workspace patterns. If the directories to
471 // watch have changed, it unregisters and re-registers client notifications.
472 func (s *server) updateWatchedDirectories(ctx context.Context) error {
473 patterns := s.session.FileWatchingGlobPatterns(ctx)
474
475 // Note: Currently, the server-side watcher acts as a complement to the
476 // client-side watcher (which is registered below). This dual-watching
477 // setup is safe, though it means gopls may receive redundant file
478 // events (one from the client, one from the server-side watcher).
479 //
480 // TODO(hxjiang): If the user enables the server-side file watcher, the
481 // server can eventually skip the client-side registration entirely and
482 // rely solely on the server-side watcher to avoid this redundancy.
483 if err := s.updateServerSideWatcher(ctx, patterns); err != nil {
484 return fmt.Errorf("failed to update server-side file watcher: %w", err)
485 }
486
487 s.watchedGlobPatternsMu.Lock()
488 defer s.watchedGlobPatternsMu.Unlock()
489
490 // Nothing to do if the set of workspace directories is unchanged.
491 if moremaps.SameKeys(s.watchedGlobPatterns, patterns) {
492 return nil
493 }
494
495 // If the set of directories to watch has changed, register the updates and
496 // unregister the previously watched directories. This ordering avoids a
497 // period where no files are being watched. Still, if a user makes on-disk
498 // changes before these updates are complete, we may miss them for the new
499 // directories.
500 prevID := s.watchRegistrationCount - 1
501 if err := s.registerWatchedDirectoriesLocked(ctx, patterns); err != nil {
502 return err
503 }
504 if prevID >= 0 {
505 return s.client.UnregisterCapability(ctx, &protocol.UnregistrationParams{
506 Unregisterations: []protocol.Unregistration{{
507 ID: watchedFilesCapabilityID(prevID),
508 Method: "workspace/didChangeWatchedFiles",
509 }},
510 })
511 }
512 return nil
513 }
514
515 // updateServerSideWatcher synchronizes the file watcher's lifecycle with the
516 // current session settings (creating, replacing, or closing it as needed)
517 // and updates the directories it monitors based on the provided patterns.
518 func (s *server) updateServerSideWatcher(ctx context.Context, patterns map[protocol.RelativePattern]unit) error {
519 wantMode := s.Options().FileWatcher
520 s.fileWatcherMu.Lock()
521 defer s.fileWatcherMu.Unlock()
522
523 // Close file watcher if the file watcher is not the desired mode.
524 if s.fileWatcher != nil && s.fileWatcher.Mode() != wantMode {
525 if err := s.fileWatcher.Close(); err != nil {
526 event.Error(ctx, "failed to close the file watcher", err)
527 }
528 s.fileWatcher = nil
529 }
530
531 if wantMode == settings.FileWatcherOff {
532 return nil
533 }
534
535 // Create new file watcher based on the desired mode.
536 if s.fileWatcher == nil {
537 // TODO(hxjiang): ensure gopls don't process events after shutdown.
538 watcherCtx := context.WithoutCancel(ctx)
539 onChange := func(events []protocol.FileEvent) {
540 modifications := make([]file.Modification, len(events))
541 for i, e := range events {
542 modifications[i] = file.Modification{
543 URI: e.URI,
544 Action: changeTypeToFileAction(e.Type),
545 OnDisk: true,
546 }
547 }
548 if err := s.didModifyFiles(watcherCtx, FromDidChangeWatchedFiles, modifications...); err != nil {
549 event.Error(watcherCtx, "failed to process file changes", err)
550 }
551 }
552 onErr := func(err error) {
553 event.Error(watcherCtx, "file watcher error", err)
554 }
555
556 w, err := filewatcher.New(wantMode, nil, onChange, onErr)
557 if err != nil {
558 return err
559 }
560 s.fileWatcher = w
561 }
562
563 // Inv: s.fileWatcher.Mode() == want
564 dirs := make(map[string]struct{})
565 for pattern := range patterns {
566 if pattern.BaseURI != "" {
567 dirs[pattern.BaseURI.Path()] = struct{}{}
568 }
569 }
570 for dir := range dirs {
571 if err := s.fileWatcher.WatchDir(dir); err != nil {
572 // Log warning but continue watching other directories.
573 event.Log(ctx, fmt.Sprintf("failed to watch directory %s: %v", dir, err))
574 }
575 }
576 return nil
577 }
578
579 func watchedFilesCapabilityID(id int) string {
580 return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id)
581 }
582
583 // registerWatchedDirectoriesLocked sends the workspace/didChangeWatchedFiles
584 // registrations to the client and updates s.watchedDirectories.
585 // The caller must not subsequently mutate patterns.
586 func (s *server) registerWatchedDirectoriesLocked(ctx context.Context, patterns map[protocol.RelativePattern]unit) error {
587 if !s.Options().DynamicWatchedFilesSupported {
588 return nil
589 }
590
591 supportsRelativePatterns := s.Options().RelativePatternsSupported
592
593 s.watchedGlobPatterns = patterns
594 watchers := make([]protocol.FileSystemWatcher, 0, len(patterns)) // must be a slice
595 val := protocol.WatchChange | protocol.WatchDelete | protocol.WatchCreate
596 for pattern := range patterns {
597 var value any
598 if supportsRelativePatterns && pattern.BaseURI != "" {
599 value = pattern
600 } else {
601 p := pattern.Pattern
602 if pattern.BaseURI != "" {
603 p = path.Join(filepath.ToSlash(pattern.BaseURI.Path()), p)
604 }
605 value = p
606 }
607 watchers = append(watchers, protocol.FileSystemWatcher{
608 GlobPattern: protocol.GlobPattern{Value: value},
609 Kind: &val,
610 })
611 }
612
613 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
614 Registrations: []protocol.Registration{{
615 ID: watchedFilesCapabilityID(s.watchRegistrationCount),
616 Method: "workspace/didChangeWatchedFiles",
617 RegisterOptions: protocol.DidChangeWatchedFilesRegistrationOptions{
618 Watchers: watchers,
619 },
620 }},
621 }); err != nil {
622 return err
623 }
624 s.watchRegistrationCount++
625 return nil
626 }
627
628 // Options returns the current server options.
629 //
630 // The caller must not modify the result.
631 func (s *server) Options() *settings.Options {
632 s.optionsMu.Lock()
633 defer s.optionsMu.Unlock()
634 return s.options
635 }
636
637 // SetOptions sets the current server options.
638 //
639 // The caller must not subsequently modify the options.
640 func (s *server) SetOptions(opts *settings.Options) {
641 s.optionsMu.Lock()
642 defer s.optionsMu.Unlock()
643 s.options = opts
644 }
645
646 func (s *server) newFolder(ctx context.Context, folder protocol.DocumentURI, name string, opts *settings.Options) (*cache.Folder, error) {
647 env, err := cache.FetchGoEnv(ctx, folder, opts)
648 if err != nil {
649 return nil, err
650 }
651
652 // Increment folder counters.
653 switch {
654 case env.GOTOOLCHAIN == "auto" || strings.Contains(env.GOTOOLCHAIN, "+auto"):
655 counter.Inc("gopls/gotoolchain:auto")
656 case env.GOTOOLCHAIN == "path" || strings.Contains(env.GOTOOLCHAIN, "+path"):
657 counter.Inc("gopls/gotoolchain:path")
658 case env.GOTOOLCHAIN == "local": // local+auto and local+path handled above
659 counter.Inc("gopls/gotoolchain:local")
660 default:
661 counter.Inc("gopls/gotoolchain:other")
662 }
663
664 // Record whether a driver is in use so that it appears in the
665 // user's telemetry upload. Although we can't correlate the
666 // driver information with the crash or bug.Report at the
667 // granularity of the process instance, users that use a
668 // driver tend to do so most of the time, so we'll get a
669 // strong clue. See #60890 for an example of an issue where
670 // this information would have been helpful.
671 if env.EffectiveGOPACKAGESDRIVER != "" {
672 counter.Inc("gopls/gopackagesdriver")
673 }
674
675 return &cache.Folder{
676 Dir: folder,
677 Name: name,
678 Options: opts,
679 Env: *env,
680 }, nil
681 }
682
683 // fetchFolderOptions makes a workspace/configuration request for the given
684 // folder, and populates options with the result.
685 //
686 // If folder is "", fetchFolderOptions makes an unscoped request.
687 func (s *server) fetchFolderOptions(ctx context.Context, folder protocol.DocumentURI) (*settings.Options, error) {
688 opts := s.Options()
689 if !opts.ConfigurationSupported {
690 return opts, nil
691 }
692 var scopeURI *string
693 if folder != "" {
694 scope := string(folder)
695 scopeURI = &scope
696 }
697 configs, err := s.client.Configuration(ctx, &protocol.ParamConfiguration{
698 Items: []protocol.ConfigurationItem{{
699 ScopeURI: scopeURI,
700 Section: "gopls",
701 }},
702 },
703 )
704 if err != nil {
705 return nil, fmt.Errorf("failed to get workspace configuration from client (%s): %v", folder, err)
706 }
707
708 opts = opts.Clone()
709 for _, config := range configs {
710 res, errs := opts.Set(config)
711 s.handleOptionResult(ctx, res, errs)
712 }
713 return opts, nil
714 }
715
716 func (s *server) eventuallyShowMessage(ctx context.Context, msg *protocol.ShowMessageParams) {
717 s.stateMu.Lock()
718 defer s.stateMu.Unlock()
719 if s.state == serverInitialized {
720 _ = s.client.ShowMessage(ctx, msg) // ignore error
721 }
722 s.notifications = append(s.notifications, msg)
723 }
724
725 func (s *server) handleOptionResult(ctx context.Context, applied []telemetry.CounterPath, optionErrors []error) {
726 for _, path := range applied {
727 path = append(settings.CounterPath{"gopls", "setting"}, path...)
728 counter.Inc(path.FullName())
729 }
730
731 var warnings, errs []string
732 for _, err := range optionErrors {
733 if err == nil {
734 panic("nil error passed to handleOptionErrors")
735 }
736 if errors.Is(err, new(settings.SoftError)) {
737 warnings = append(warnings, err.Error())
738 } else {
739 errs = append(errs, err.Error())
740 }
741 }
742
743 // Sort messages, but put errors first.
744 //
745 // Having stable content for the message allows clients to de-duplicate. This
746 // matters because we may send duplicate warnings for clients that support
747 // dynamic configuration: one for the initial settings, and then more for the
748 // individual viewsettings.
749 var msgs []string
750 msgType := protocol.Warning
751 if len(errs) > 0 {
752 msgType = protocol.Error
753 sort.Strings(errs)
754 msgs = append(msgs, errs...)
755 }
756 if len(warnings) > 0 {
757 sort.Strings(warnings)
758 msgs = append(msgs, warnings...)
759 }
760
761 if len(msgs) > 0 {
762 // Settings
763 combined := "Invalid settings: " + strings.Join(msgs, "; ")
764 params := &protocol.ShowMessageParams{
765 Type: msgType,
766 Message: combined,
767 }
768 s.eventuallyShowMessage(ctx, params)
769 }
770 }
771
772 // Shutdown implements the 'shutdown' LSP handler. It releases resources
773 // associated with the server and waits for all ongoing work to complete.
774 func (s *server) Shutdown(ctx context.Context) error {
775 ctx, done := event.Start(ctx, "server.Shutdown")
776 defer done()
777
778 s.stateMu.Lock()
779 defer s.stateMu.Unlock()
780 if s.state < serverInitialized {
781 event.Log(ctx, "server shutdown without initialization")
782 }
783 if s.state != serverShutDown {
784 // Wait for the webserver (if any) to finish.
785 if s.web != nil {
786 s.web.server.Shutdown(ctx) // ignore error
787 }
788
789 // drop all the active views
790 s.session.Shutdown(ctx)
791 s.state = serverShutDown
792 }
793 return nil
794 }
795
796 func (s *server) Exit(ctx context.Context) error {
797 ctx, done := event.Start(ctx, "server.Exit")
798 defer done()
799
800 s.stateMu.Lock()
801 defer s.stateMu.Unlock()
802
803 s.client.Close() // ignore error
804
805 if s.state != serverShutDown {
806 // TODO: We should be able to do better than this.
807 os.Exit(1)
808 }
809 // We don't terminate the process on a normal exit, we just allow it to
810 // close naturally if needed after the connection is closed.
811 return nil
812 }
813
814 // recordClientInfo records gopls client info.
815 func recordClientInfo(clientName string) {
816 // This table maps LSP (not MCP) clientInfo.Name prefixes to Go telemetry counters.
817 // Where authoritative source is available, we link to it.
818 for _, cli := range [...]struct {
819 clientNamePrefix, telemetryKey string
820 }{
821 {"Visual Studio Code - Insiders", "gopls/client:vscode-insiders"},
822 {"Visual Studio Code", "gopls/client:vscode"},
823
824 {"VSCodium", "gopls/client:vscodium"},
825
826 // https://github.com/coder/code-server/blob/3cb92edc76ecc2cfa5809205897d93d4379b16a6/ci/build/build-vscode.sh#L19
827 {"code-server", "gopls/client:code-server"},
828
829 // https://lists.gnu.org/archive/html/bug-gnu-emacs/2023-03/msg00954.html
830 {"Eglot", "gopls/client:eglot"},
831
832 // https://github.com/govim/govim/pull/1189
833 {"govim", "gopls/client:govim"},
834
835 // https://github.com/helix-editor/helix/blob/d0218f7e78bc0c3af4b0995ab8bda66b9c542cf3/helix-lsp/src/client.rs#L714
836 {"helix", "gopls/client:helix"},
837
838 // https://github.com/neovim/neovim/blob/42333ea98dfcd2994ee128a3467dfe68205154cd/runtime/lua/vim/lsp.lua#L1361
839 // https://github.com/neovim/neovim/blob/fe6026825883b44b09a8d3a03f2d49bfc8ed4725/runtime/lua/vim/lsp/client.lua#564
840 {"Neovim", "gopls/client:neovim"},
841
842 // https://github.com/neoclide/coc.nvim/blob/3dc6153a85ed0f185abec1deb972a66af3fbbfb4/src/language-client/client.ts#L994
843 {"coc.nvim", "gopls/client:coc.nvim"},
844
845 // https://github.com/sublimelsp/LSP/blob/e608f878e7e9dd34aabe4ff0462540fadcd88fcc/plugin/core/sessions.py#L493
846 {"Sublime Text LSP", "gopls/client:sublimetext"},
847
848 {"Cursor", "gopls/client:cursor"},
849
850 // https: //github.com/zed-industries/zed/blob/0ac17526687bf11007f0fbb5c3b2ff463ce47293/crates/release_channel/src/lib.rs#L147
851 {"Zed", "gopls/client:zed"}, // incl. "Zed Dev", "Zed Nightly", "Zed Preview"
852
853 // (Observed empirically.)
854 {"Claude Code", "gopls/client:claude"},
855
856 // (Observed empirically.)
857 {"Antigravity", "gopls/client:antigravity"},
858 {"Jetski", "gopls/client:antigravity"},
859 {"Windsurf", "gopls/client:windsurf"},
860 } {
861 if strings.HasPrefix(clientName, cli.clientNamePrefix) {
862 counter.Inc(cli.telemetryKey)
863 return
864 }
865 }
866
867 // Accumulate at least a local counter for an unknown
868 // client name, but also fall through to count it as
869 // ":other" for collection.
870 if clientName != "" {
871 counter.New(fmt.Sprintf("gopls/client-other:%s", clientName)).Inc()
872 }
873 counter.Inc("gopls/client:other")
874 }