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 5package lsp 6 7import ( 8 "bytes" 9 "context" 10 "encoding/json" 11 "fmt" 12 "os" 13 "path" 14 "path/filepath" 15 "sync" 16 17 "golang.org/x/tools/internal/event" 18 "golang.org/x/tools/internal/jsonrpc2" 19 "golang.org/x/tools/internal/lsp/debug" 20 "golang.org/x/tools/internal/lsp/protocol" 21 "golang.org/x/tools/internal/lsp/source" 22 "golang.org/x/tools/internal/span" 23 errors "golang.org/x/xerrors" 24) 25 26func (s *Server) initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) { 27 s.stateMu.Lock() 28 if s.state >= serverInitializing { 29 defer s.stateMu.Unlock() 30 return nil, errors.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) 31 } 32 s.state = serverInitializing 33 s.stateMu.Unlock() 34 35 // For uniqueness, use the gopls PID rather than params.ProcessID (the client 36 // pid). Some clients might start multiple gopls servers, though they 37 // probably shouldn't. 38 pid := os.Getpid() 39 s.tempDir = filepath.Join(os.TempDir(), fmt.Sprintf("gopls-%d.%s", pid, s.session.ID())) 40 err := os.Mkdir(s.tempDir, 0700) 41 if err != nil { 42 // MkdirTemp could fail due to permissions issues. This is a problem with 43 // the user's environment, but should not block gopls otherwise behaving. 44 // All usage of s.tempDir should be predicated on having a non-empty 45 // s.tempDir. 46 event.Error(ctx, "creating temp dir", err) 47 s.tempDir = "" 48 } 49 s.progress.SetSupportsWorkDoneProgress(params.Capabilities.Window.WorkDoneProgress) 50 51 options := s.session.Options() 52 defer func() { s.session.SetOptions(options) }() 53 54 if err := s.handleOptionResults(ctx, source.SetOptions(options, params.InitializationOptions)); err != nil { 55 return nil, err 56 } 57 options.ForClientCapabilities(params.Capabilities) 58 59 folders := params.WorkspaceFolders 60 if len(folders) == 0 { 61 if params.RootURI != "" { 62 folders = []protocol.WorkspaceFolder{{ 63 URI: string(params.RootURI), 64 Name: path.Base(params.RootURI.SpanURI().Filename()), 65 }} 66 } 67 } 68 for _, folder := range folders { 69 uri := span.URIFromURI(folder.URI) 70 if !uri.IsFile() { 71 continue 72 } 73 s.pendingFolders = append(s.pendingFolders, folder) 74 } 75 // gopls only supports URIs with a file:// scheme, so if we have no 76 // workspace folders with a supported scheme, fail to initialize. 77 if len(folders) > 0 && len(s.pendingFolders) == 0 { 78 return nil, fmt.Errorf("unsupported URI schemes: %v (gopls only supports file URIs)", folders) 79 } 80 81 var codeActionProvider interface{} = true 82 if ca := params.Capabilities.TextDocument.CodeAction; len(ca.CodeActionLiteralSupport.CodeActionKind.ValueSet) > 0 { 83 // If the client has specified CodeActionLiteralSupport, 84 // send the code actions we support. 85 // 86 // Using CodeActionOptions is only valid if codeActionLiteralSupport is set. 87 codeActionProvider = &protocol.CodeActionOptions{ 88 CodeActionKinds: s.getSupportedCodeActions(), 89 } 90 } 91 var renameOpts interface{} = true 92 if r := params.Capabilities.TextDocument.Rename; r.PrepareSupport { 93 renameOpts = protocol.RenameOptions{ 94 PrepareProvider: r.PrepareSupport, 95 } 96 } 97 98 versionInfo := debug.VersionInfo() 99 100 // golang/go#45732: Warn users who've installed sergi/go-diff@v1.2.0, since 101 // it will corrupt the formatting of their files. 102 for _, dep := range versionInfo.Deps { 103 if dep.Path == "github.com/sergi/go-diff" && dep.Version == "v1.2.0" { 104 if err := s.eventuallyShowMessage(ctx, &protocol.ShowMessageParams{ 105 Message: `It looks like you have a bad gopls installation. 106Please reinstall gopls by running 'GO111MODULE=on go get golang.org/x/tools/gopls@latest'. 107See https://github.com/golang/go/issues/45732 for more information.`, 108 Type: protocol.Error, 109 }); err != nil { 110 return nil, err 111 } 112 } 113 } 114 115 goplsVersion, err := json.Marshal(versionInfo) 116 if err != nil { 117 return nil, err 118 } 119 120 return &protocol.InitializeResult{ 121 Capabilities: protocol.ServerCapabilities{ 122 CallHierarchyProvider: true, 123 CodeActionProvider: codeActionProvider, 124 CompletionProvider: protocol.CompletionOptions{ 125 TriggerCharacters: []string{"."}, 126 }, 127 DefinitionProvider: true, 128 TypeDefinitionProvider: true, 129 ImplementationProvider: true, 130 DocumentFormattingProvider: true, 131 DocumentSymbolProvider: true, 132 WorkspaceSymbolProvider: true, 133 ExecuteCommandProvider: protocol.ExecuteCommandOptions{ 134 Commands: options.SupportedCommands, 135 }, 136 FoldingRangeProvider: true, 137 HoverProvider: true, 138 DocumentHighlightProvider: true, 139 DocumentLinkProvider: protocol.DocumentLinkOptions{}, 140 ReferencesProvider: true, 141 RenameProvider: renameOpts, 142 SignatureHelpProvider: protocol.SignatureHelpOptions{ 143 TriggerCharacters: []string{"(", ","}, 144 }, 145 TextDocumentSync: &protocol.TextDocumentSyncOptions{ 146 Change: protocol.Incremental, 147 OpenClose: true, 148 Save: protocol.SaveOptions{ 149 IncludeText: false, 150 }, 151 }, 152 Workspace: protocol.Workspace5Gn{ 153 WorkspaceFolders: protocol.WorkspaceFolders4Gn{ 154 Supported: true, 155 ChangeNotifications: "workspace/didChangeWorkspaceFolders", 156 }, 157 }, 158 }, 159 ServerInfo: struct { 160 Name string `json:"name"` 161 Version string `json:"version,omitempty"` 162 }{ 163 Name: "gopls", 164 Version: string(goplsVersion), 165 }, 166 }, nil 167} 168 169func (s *Server) initialized(ctx context.Context, params *protocol.InitializedParams) error { 170 s.stateMu.Lock() 171 if s.state >= serverInitialized { 172 defer s.stateMu.Unlock() 173 return errors.Errorf("%w: initialized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) 174 } 175 s.state = serverInitialized 176 s.stateMu.Unlock() 177 178 for _, not := range s.notifications { 179 s.client.ShowMessage(ctx, not) 180 } 181 s.notifications = nil 182 183 options := s.session.Options() 184 defer func() { s.session.SetOptions(options) }() 185 186 if err := s.addFolders(ctx, s.pendingFolders); err != nil { 187 return err 188 } 189 s.pendingFolders = nil 190 191 if options.ConfigurationSupported && options.DynamicConfigurationSupported { 192 registrations := []protocol.Registration{ 193 { 194 ID: "workspace/didChangeConfiguration", 195 Method: "workspace/didChangeConfiguration", 196 }, 197 { 198 ID: "workspace/didChangeWorkspaceFolders", 199 Method: "workspace/didChangeWorkspaceFolders", 200 }, 201 } 202 if options.SemanticTokens { 203 registrations = append(registrations, semanticTokenRegistration(options.SemanticTypes, options.SemanticMods)) 204 } 205 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{ 206 Registrations: registrations, 207 }); err != nil { 208 return err 209 } 210 } 211 return nil 212} 213 214func (s *Server) addFolders(ctx context.Context, folders []protocol.WorkspaceFolder) error { 215 originalViews := len(s.session.Views()) 216 viewErrors := make(map[span.URI]error) 217 218 var wg sync.WaitGroup 219 if s.session.Options().VerboseWorkDoneProgress { 220 work := s.progress.Start(ctx, DiagnosticWorkTitle(FromInitialWorkspaceLoad), "Calculating diagnostics for initial workspace load...", nil, nil) 221 defer func() { 222 go func() { 223 wg.Wait() 224 work.End("Done.") 225 }() 226 }() 227 } 228 // Only one view gets to have a workspace. 229 var allFoldersWg sync.WaitGroup 230 for _, folder := range folders { 231 uri := span.URIFromURI(folder.URI) 232 // Ignore non-file URIs. 233 if !uri.IsFile() { 234 continue 235 } 236 work := s.progress.Start(ctx, "Setting up workspace", "Loading packages...", nil, nil) 237 snapshot, release, err := s.addView(ctx, folder.Name, uri) 238 if err != nil { 239 viewErrors[uri] = err 240 work.End(fmt.Sprintf("Error loading packages: %s", err)) 241 continue 242 } 243 var swg sync.WaitGroup 244 swg.Add(1) 245 allFoldersWg.Add(1) 246 go func() { 247 defer swg.Done() 248 defer allFoldersWg.Done() 249 snapshot.AwaitInitialized(ctx) 250 work.End("Finished loading packages.") 251 }() 252 253 // Print each view's environment. 254 buf := &bytes.Buffer{} 255 if err := snapshot.WriteEnv(ctx, buf); err != nil { 256 viewErrors[uri] = err 257 continue 258 } 259 event.Log(ctx, buf.String()) 260 261 // Diagnose the newly created view. 262 wg.Add(1) 263 go func() { 264 s.diagnoseDetached(snapshot) 265 swg.Wait() 266 release() 267 wg.Done() 268 }() 269 } 270 271 // Register for file watching notifications, if they are supported. 272 // Wait for all snapshots to be initialized first, since all files might 273 // not yet be known to the snapshots. 274 allFoldersWg.Wait() 275 if err := s.updateWatchedDirectories(ctx); err != nil { 276 event.Error(ctx, "failed to register for file watching notifications", err) 277 } 278 279 if len(viewErrors) > 0 { 280 errMsg := fmt.Sprintf("Error loading workspace folders (expected %v, got %v)\n", len(folders), len(s.session.Views())-originalViews) 281 for uri, err := range viewErrors { 282 errMsg += fmt.Sprintf("failed to load view for %s: %v\n", uri, err) 283 } 284 return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{ 285 Type: protocol.Error, 286 Message: errMsg, 287 }) 288 } 289 return nil 290} 291 292// updateWatchedDirectories compares the current set of directories to watch 293// with the previously registered set of directories. If the set of directories 294// has changed, we unregister and re-register for file watching notifications. 295// updatedSnapshots is the set of snapshots that have been updated. 296func (s *Server) updateWatchedDirectories(ctx context.Context) error { 297 patterns := s.session.FileWatchingGlobPatterns(ctx) 298 299 s.watchedGlobPatternsMu.Lock() 300 defer s.watchedGlobPatternsMu.Unlock() 301 302 // Nothing to do if the set of workspace directories is unchanged. 303 if equalURISet(s.watchedGlobPatterns, patterns) { 304 return nil 305 } 306 307 // If the set of directories to watch has changed, register the updates and 308 // unregister the previously watched directories. This ordering avoids a 309 // period where no files are being watched. Still, if a user makes on-disk 310 // changes before these updates are complete, we may miss them for the new 311 // directories. 312 prevID := s.watchRegistrationCount - 1 313 if err := s.registerWatchedDirectoriesLocked(ctx, patterns); err != nil { 314 return err 315 } 316 if prevID >= 0 { 317 return s.client.UnregisterCapability(ctx, &protocol.UnregistrationParams{ 318 Unregisterations: []protocol.Unregistration{{ 319 ID: watchedFilesCapabilityID(prevID), 320 Method: "workspace/didChangeWatchedFiles", 321 }}, 322 }) 323 } 324 return nil 325} 326 327func watchedFilesCapabilityID(id int) string { 328 return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id) 329} 330 331func equalURISet(m1, m2 map[string]struct{}) bool { 332 if len(m1) != len(m2) { 333 return false 334 } 335 for k := range m1 { 336 _, ok := m2[k] 337 if !ok { 338 return false 339 } 340 } 341 return true 342} 343 344// registerWatchedDirectoriesLocked sends the workspace/didChangeWatchedFiles 345// registrations to the client and updates s.watchedDirectories. 346func (s *Server) registerWatchedDirectoriesLocked(ctx context.Context, patterns map[string]struct{}) error { 347 if !s.session.Options().DynamicWatchedFilesSupported { 348 return nil 349 } 350 for k := range s.watchedGlobPatterns { 351 delete(s.watchedGlobPatterns, k) 352 } 353 var watchers []protocol.FileSystemWatcher 354 for pattern := range patterns { 355 watchers = append(watchers, protocol.FileSystemWatcher{ 356 GlobPattern: pattern, 357 Kind: uint32(protocol.WatchChange + protocol.WatchDelete + protocol.WatchCreate), 358 }) 359 } 360 361 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{ 362 Registrations: []protocol.Registration{{ 363 ID: watchedFilesCapabilityID(s.watchRegistrationCount), 364 Method: "workspace/didChangeWatchedFiles", 365 RegisterOptions: protocol.DidChangeWatchedFilesRegistrationOptions{ 366 Watchers: watchers, 367 }, 368 }}, 369 }); err != nil { 370 return err 371 } 372 s.watchRegistrationCount++ 373 374 for k, v := range patterns { 375 s.watchedGlobPatterns[k] = v 376 } 377 return nil 378} 379 380func (s *Server) fetchConfig(ctx context.Context, name string, folder span.URI, o *source.Options) error { 381 if !s.session.Options().ConfigurationSupported { 382 return nil 383 } 384 configs, err := s.client.Configuration(ctx, &protocol.ParamConfiguration{ 385 ConfigurationParams: protocol.ConfigurationParams{ 386 Items: []protocol.ConfigurationItem{{ 387 ScopeURI: string(folder), 388 Section: "gopls", 389 }}, 390 }, 391 }) 392 if err != nil { 393 return fmt.Errorf("failed to get workspace configuration from client (%s): %v", folder, err) 394 } 395 for _, config := range configs { 396 if err := s.handleOptionResults(ctx, source.SetOptions(o, config)); err != nil { 397 return err 398 } 399 } 400 return nil 401} 402 403func (s *Server) eventuallyShowMessage(ctx context.Context, msg *protocol.ShowMessageParams) error { 404 s.stateMu.Lock() 405 defer s.stateMu.Unlock() 406 if s.state == serverInitialized { 407 return s.client.ShowMessage(ctx, msg) 408 } 409 s.notifications = append(s.notifications, msg) 410 return nil 411} 412 413func (s *Server) handleOptionResults(ctx context.Context, results source.OptionResults) error { 414 for _, result := range results { 415 if result.Error != nil { 416 msg := &protocol.ShowMessageParams{ 417 Type: protocol.Error, 418 Message: result.Error.Error(), 419 } 420 if err := s.eventuallyShowMessage(ctx, msg); err != nil { 421 return err 422 } 423 } 424 switch result.State { 425 case source.OptionUnexpected: 426 msg := &protocol.ShowMessageParams{ 427 Type: protocol.Error, 428 Message: fmt.Sprintf("unexpected gopls setting %q", result.Name), 429 } 430 if err := s.eventuallyShowMessage(ctx, msg); err != nil { 431 return err 432 } 433 case source.OptionDeprecated: 434 msg := fmt.Sprintf("gopls setting %q is deprecated", result.Name) 435 if result.Replacement != "" { 436 msg = fmt.Sprintf("%s, use %q instead", msg, result.Replacement) 437 } 438 if err := s.eventuallyShowMessage(ctx, &protocol.ShowMessageParams{ 439 Type: protocol.Warning, 440 Message: msg, 441 }); err != nil { 442 return err 443 } 444 } 445 } 446 return nil 447} 448 449// beginFileRequest checks preconditions for a file-oriented request and routes 450// it to a snapshot. 451// We don't want to return errors for benign conditions like wrong file type, 452// so callers should do if !ok { return err } rather than if err != nil. 453func (s *Server) beginFileRequest(ctx context.Context, pURI protocol.DocumentURI, expectKind source.FileKind) (source.Snapshot, source.VersionedFileHandle, bool, func(), error) { 454 uri := pURI.SpanURI() 455 if !uri.IsFile() { 456 // Not a file URI. Stop processing the request, but don't return an error. 457 return nil, nil, false, func() {}, nil 458 } 459 view, err := s.session.ViewOf(uri) 460 if err != nil { 461 return nil, nil, false, func() {}, err 462 } 463 snapshot, release := view.Snapshot(ctx) 464 fh, err := snapshot.GetVersionedFile(ctx, uri) 465 if err != nil { 466 release() 467 return nil, nil, false, func() {}, err 468 } 469 if expectKind != source.UnknownKind && fh.Kind() != expectKind { 470 // Wrong kind of file. Nothing to do. 471 release() 472 return nil, nil, false, func() {}, nil 473 } 474 return snapshot, fh, true, release, nil 475} 476 477func (s *Server) shutdown(ctx context.Context) error { 478 s.stateMu.Lock() 479 defer s.stateMu.Unlock() 480 if s.state < serverInitialized { 481 event.Log(ctx, "server shutdown without initialization") 482 } 483 if s.state != serverShutDown { 484 // drop all the active views 485 s.session.Shutdown(ctx) 486 s.state = serverShutDown 487 if s.tempDir != "" { 488 if err := os.RemoveAll(s.tempDir); err != nil { 489 event.Error(ctx, "removing temp dir", err) 490 } 491 } 492 } 493 return nil 494} 495 496func (s *Server) exit(ctx context.Context) error { 497 s.stateMu.Lock() 498 defer s.stateMu.Unlock() 499 500 s.client.Close() 501 502 if s.state != serverShutDown { 503 // TODO: We should be able to do better than this. 504 os.Exit(1) 505 } 506 // we don't terminate the process on a normal exit, we just allow it to 507 // close naturally if needed after the connection is closed. 508 return nil 509} 510