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.
18 "golang.org/x/tools/internal/event"
19 "golang.org/x/tools/internal/jsonrpc2"
20 "golang.org/x/tools/internal/lsp/debug"
21 "golang.org/x/tools/internal/lsp/protocol"
22 "golang.org/x/tools/internal/lsp/source"
23 "golang.org/x/tools/internal/span"
24 errors "golang.org/x/xerrors"
27 func (s *Server) initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) {
29 if s.state >= serverInitializing {
30 defer s.stateMu.Unlock()
31 return nil, errors.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state)
33 s.state = serverInitializing
36 s.clientPID = int(params.ProcessID)
37 s.progress.supportsWorkDoneProgress = params.Capabilities.Window.WorkDoneProgress
39 options := s.session.Options()
40 defer func() { s.session.SetOptions(options) }()
42 if err := s.handleOptionResults(ctx, source.SetOptions(options, params.InitializationOptions)); err != nil {
45 options.ForClientCapabilities(params.Capabilities)
47 folders := params.WorkspaceFolders
48 if len(folders) == 0 {
49 if params.RootURI != "" {
50 folders = []protocol.WorkspaceFolder{{
51 URI: string(params.RootURI),
52 Name: path.Base(params.RootURI.SpanURI().Filename()),
56 for _, folder := range folders {
57 uri := span.URIFromURI(folder.URI)
61 s.pendingFolders = append(s.pendingFolders, folder)
63 // gopls only supports URIs with a file:// scheme, so if we have no
64 // workspace folders with a supported scheme, fail to initialize.
65 if len(folders) > 0 && len(s.pendingFolders) == 0 {
66 return nil, fmt.Errorf("unsupported URI schemes: %v (gopls only supports file URIs)", folders)
69 var codeActionProvider interface{} = true
70 if ca := params.Capabilities.TextDocument.CodeAction; len(ca.CodeActionLiteralSupport.CodeActionKind.ValueSet) > 0 {
71 // If the client has specified CodeActionLiteralSupport,
72 // send the code actions we support.
74 // Using CodeActionOptions is only valid if codeActionLiteralSupport is set.
75 codeActionProvider = &protocol.CodeActionOptions{
76 CodeActionKinds: s.getSupportedCodeActions(),
79 var renameOpts interface{} = true
80 if r := params.Capabilities.TextDocument.Rename; r.PrepareSupport {
81 renameOpts = protocol.RenameOptions{
82 PrepareProvider: r.PrepareSupport,
86 goplsVer := &bytes.Buffer{}
87 debug.PrintVersionInfo(ctx, goplsVer, true, debug.PlainText)
89 return &protocol.InitializeResult{
90 Capabilities: protocol.ServerCapabilities{
91 CallHierarchyProvider: true,
92 CodeActionProvider: codeActionProvider,
93 CompletionProvider: protocol.CompletionOptions{
94 TriggerCharacters: []string{"."},
96 DefinitionProvider: true,
97 TypeDefinitionProvider: true,
98 ImplementationProvider: true,
99 DocumentFormattingProvider: true,
100 DocumentSymbolProvider: true,
101 WorkspaceSymbolProvider: true,
102 ExecuteCommandProvider: protocol.ExecuteCommandOptions{
103 Commands: options.SupportedCommands,
105 FoldingRangeProvider: true,
107 DocumentHighlightProvider: true,
108 DocumentLinkProvider: protocol.DocumentLinkOptions{},
109 ReferencesProvider: true,
110 RenameProvider: renameOpts,
111 SignatureHelpProvider: protocol.SignatureHelpOptions{
112 TriggerCharacters: []string{"(", ","},
114 TextDocumentSync: &protocol.TextDocumentSyncOptions{
115 Change: protocol.Incremental,
117 Save: protocol.SaveOptions{
121 Workspace: protocol.WorkspaceGn{
122 WorkspaceFolders: protocol.WorkspaceFoldersGn{
124 ChangeNotifications: "workspace/didChangeWorkspaceFolders",
129 Name string `json:"name"`
130 Version string `json:"version,omitempty"`
133 Version: goplsVer.String(),
139 func (s *Server) initialized(ctx context.Context, params *protocol.InitializedParams) error {
141 if s.state >= serverInitialized {
142 defer s.stateMu.Unlock()
143 return errors.Errorf("%w: initalized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state)
145 s.state = serverInitialized
148 for _, not := range s.notifications {
149 s.client.ShowMessage(ctx, not)
151 s.notifications = nil
153 options := s.session.Options()
154 defer func() { s.session.SetOptions(options) }()
156 if err := s.addFolders(ctx, s.pendingFolders); err != nil {
159 s.pendingFolders = nil
161 if options.ConfigurationSupported && options.DynamicConfigurationSupported {
162 registrations := []protocol.Registration{
164 ID: "workspace/didChangeConfiguration",
165 Method: "workspace/didChangeConfiguration",
168 ID: "workspace/didChangeWorkspaceFolders",
169 Method: "workspace/didChangeWorkspaceFolders",
172 if options.SemanticTokens {
173 registrations = append(registrations, semanticTokenRegistrations()...)
176 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
177 Registrations: registrations,
185 func (s *Server) addFolders(ctx context.Context, folders []protocol.WorkspaceFolder) error {
186 originalViews := len(s.session.Views())
187 viewErrors := make(map[span.URI]error)
189 var wg sync.WaitGroup
190 if s.session.Options().VerboseWorkDoneProgress {
191 work := s.progress.start(ctx, DiagnosticWorkTitle(FromInitialWorkspaceLoad), "Calculating diagnostics for initial workspace load...", nil, nil)
199 dirsToWatch := map[span.URI]struct{}{}
200 // Only one view gets to have a workspace.
201 assignedWorkspace := false
202 for _, folder := range folders {
203 uri := span.URIFromURI(folder.URI)
204 // Ignore non-file URIs.
208 work := s.progress.start(ctx, "Setting up workspace", "Loading packages...", nil, nil)
209 var workspaceURI span.URI = ""
210 if !assignedWorkspace && s.clientPID != 0 {
211 // For quick-and-dirty testing, set the temp workspace file to
212 // $TMPDIR/gopls-<client PID>.workspace.
214 // This has a couple limitations:
215 // + If there are multiple workspace roots, only the first one gets
216 // written to this dir (and the client has no way to know precisely
218 // + If a single client PID spawns multiple gopls sessions, they will
219 // clobber eachother's temp workspace.
220 wsdir := filepath.Join(os.TempDir(), fmt.Sprintf("gopls-%d.workspace", s.clientPID))
221 workspaceURI = span.URIFromPath(wsdir)
222 assignedWorkspace = true
224 snapshot, release, err := s.addView(ctx, folder.Name, uri, workspaceURI)
226 viewErrors[uri] = err
227 work.end(fmt.Sprintf("Error loading packages: %s", err))
230 var swg sync.WaitGroup
234 snapshot.AwaitInitialized(ctx)
235 work.end("Finished loading packages.")
238 for _, dir := range snapshot.WorkspaceDirectories(ctx) {
239 dirsToWatch[dir] = struct{}{}
242 // Print each view's environment.
243 buf := &bytes.Buffer{}
244 if err := snapshot.WriteEnv(ctx, buf); err != nil {
245 viewErrors[uri] = err
248 event.Log(ctx, buf.String())
250 // Diagnose the newly created view.
253 s.diagnoseDetached(snapshot)
259 // Register for file watching notifications, if they are supported.
260 s.watchedDirectoriesMu.Lock()
261 err := s.registerWatchedDirectoriesLocked(ctx, dirsToWatch)
262 s.watchedDirectoriesMu.Unlock()
266 if len(viewErrors) > 0 {
267 errMsg := fmt.Sprintf("Error loading workspace folders (expected %v, got %v)\n", len(folders), len(s.session.Views())-originalViews)
268 for uri, err := range viewErrors {
269 errMsg += fmt.Sprintf("failed to load view for %s: %v\n", uri, err)
271 return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
272 Type: protocol.Error,
279 // updateWatchedDirectories compares the current set of directories to watch
280 // with the previously registered set of directories. If the set of directories
281 // has changed, we unregister and re-register for file watching notifications.
282 // updatedSnapshots is the set of snapshots that have been updated.
283 func (s *Server) updateWatchedDirectories(ctx context.Context, updatedSnapshots map[source.View]source.Snapshot) error {
284 dirsToWatch := map[span.URI]struct{}{}
285 seenViews := map[source.View]struct{}{}
287 // Collect all of the workspace directories from the updated snapshots.
288 for _, snapshot := range updatedSnapshots {
289 seenViews[snapshot.View()] = struct{}{}
290 for _, dir := range snapshot.WorkspaceDirectories(ctx) {
291 dirsToWatch[dir] = struct{}{}
294 // Not all views were necessarily updated, so check the remaining views.
295 for _, view := range s.session.Views() {
296 if _, ok := seenViews[view]; ok {
299 snapshot, release := view.Snapshot(ctx)
300 for _, dir := range snapshot.WorkspaceDirectories(ctx) {
301 dirsToWatch[dir] = struct{}{}
306 s.watchedDirectoriesMu.Lock()
307 defer s.watchedDirectoriesMu.Unlock()
309 // Nothing to do if the set of workspace directories is unchanged.
310 if equalURISet(s.watchedDirectories, dirsToWatch) {
314 // If the set of directories to watch has changed, register the updates and
315 // unregister the previously watched directories. This ordering avoids a
316 // period where no files are being watched. Still, if a user makes on-disk
317 // changes before these updates are complete, we may miss them for the new
319 if s.watchRegistrationCount > 0 {
320 prevID := s.watchRegistrationCount - 1
321 if err := s.registerWatchedDirectoriesLocked(ctx, dirsToWatch); err != nil {
324 return s.client.UnregisterCapability(ctx, &protocol.UnregistrationParams{
325 Unregisterations: []protocol.Unregistration{{
326 ID: watchedFilesCapabilityID(prevID),
327 Method: "workspace/didChangeWatchedFiles",
334 func watchedFilesCapabilityID(id uint64) string {
335 return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id)
338 func equalURISet(m1, m2 map[span.URI]struct{}) bool {
339 if len(m1) != len(m2) {
351 // registerWatchedDirectoriesLocked sends the workspace/didChangeWatchedFiles
352 // registrations to the client and updates s.watchedDirectories.
353 func (s *Server) registerWatchedDirectoriesLocked(ctx context.Context, dirs map[span.URI]struct{}) error {
354 if !s.session.Options().DynamicWatchedFilesSupported {
357 for k := range s.watchedDirectories {
358 delete(s.watchedDirectories, k)
360 // Work-around microsoft/vscode#100870 by making sure that we are,
361 // at least, watching the user's entire workspace. This will still be
362 // applied to every folder in the workspace.
363 watchers := []protocol.FileSystemWatcher{{
364 GlobPattern: "**/*.{go,mod,sum}",
365 Kind: float64(protocol.WatchChange + protocol.WatchDelete + protocol.WatchCreate),
367 for dir := range dirs {
368 filename := dir.Filename()
370 // If the directory is within a workspace folder, we're already
371 // watching it via the relative path above.
373 for _, view := range s.session.Views() {
374 if source.InDir(view.Folder().Filename(), filename) {
383 // If microsoft/vscode#100870 is resolved before
384 // microsoft/vscode#104387, we will need a work-around for Windows
385 // drive letter casing.
386 watchers = append(watchers, protocol.FileSystemWatcher{
387 GlobPattern: fmt.Sprintf("%s/**/*.{go,mod,sum}", filename),
388 Kind: float64(protocol.WatchChange + protocol.WatchDelete + protocol.WatchCreate),
391 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
392 Registrations: []protocol.Registration{{
393 ID: watchedFilesCapabilityID(s.watchRegistrationCount),
394 Method: "workspace/didChangeWatchedFiles",
395 RegisterOptions: protocol.DidChangeWatchedFilesRegistrationOptions{
402 s.watchRegistrationCount++
404 for dir := range dirs {
405 s.watchedDirectories[dir] = struct{}{}
410 func isSubdirectory(root, leaf string) bool {
411 rel, err := filepath.Rel(root, leaf)
412 return err == nil && !strings.HasPrefix(rel, "..")
415 func (s *Server) fetchConfig(ctx context.Context, name string, folder span.URI, o *source.Options) error {
416 if !s.session.Options().ConfigurationSupported {
419 v := protocol.ParamConfiguration{
420 ConfigurationParams: protocol.ConfigurationParams{
421 Items: []protocol.ConfigurationItem{{
422 ScopeURI: string(folder),
425 ScopeURI: string(folder),
426 Section: fmt.Sprintf("gopls-%s", name),
430 configs, err := s.client.Configuration(ctx, &v)
432 return fmt.Errorf("failed to get workspace configuration from client (%s): %v", folder, err)
434 for _, config := range configs {
435 if err := s.handleOptionResults(ctx, source.SetOptions(o, config)); err != nil {
442 func (s *Server) eventuallyShowMessage(ctx context.Context, msg *protocol.ShowMessageParams) error {
444 defer s.stateMu.Unlock()
445 if s.state == serverInitialized {
446 return s.client.ShowMessage(ctx, msg)
448 s.notifications = append(s.notifications, msg)
452 func (s *Server) handleOptionResults(ctx context.Context, results source.OptionResults) error {
453 for _, result := range results {
454 if result.Error != nil {
455 msg := &protocol.ShowMessageParams{
456 Type: protocol.Error,
457 Message: result.Error.Error(),
459 if err := s.eventuallyShowMessage(ctx, msg); err != nil {
463 switch result.State {
464 case source.OptionUnexpected:
465 msg := &protocol.ShowMessageParams{
466 Type: protocol.Error,
467 Message: fmt.Sprintf("unexpected gopls setting %q", result.Name),
469 if err := s.eventuallyShowMessage(ctx, msg); err != nil {
472 case source.OptionDeprecated:
473 msg := fmt.Sprintf("gopls setting %q is deprecated", result.Name)
474 if result.Replacement != "" {
475 msg = fmt.Sprintf("%s, use %q instead", msg, result.Replacement)
477 if err := s.eventuallyShowMessage(ctx, &protocol.ShowMessageParams{
478 Type: protocol.Warning,
488 // beginFileRequest checks preconditions for a file-oriented request and routes
490 // We don't want to return errors for benign conditions like wrong file type,
491 // so callers should do if !ok { return err } rather than if err != nil.
492 func (s *Server) beginFileRequest(ctx context.Context, pURI protocol.DocumentURI, expectKind source.FileKind) (source.Snapshot, source.VersionedFileHandle, bool, func(), error) {
493 uri := pURI.SpanURI()
495 // Not a file URI. Stop processing the request, but don't return an error.
496 return nil, nil, false, func() {}, nil
498 view, err := s.session.ViewOf(uri)
500 return nil, nil, false, func() {}, err
502 snapshot, release := view.Snapshot(ctx)
503 fh, err := snapshot.GetVersionedFile(ctx, uri)
506 return nil, nil, false, func() {}, err
508 if expectKind != source.UnknownKind && fh.Kind() != expectKind {
509 // Wrong kind of file. Nothing to do.
511 return nil, nil, false, func() {}, nil
513 return snapshot, fh, true, release, nil
516 func (s *Server) shutdown(ctx context.Context) error {
518 defer s.stateMu.Unlock()
519 if s.state < serverInitialized {
520 event.Log(ctx, "server shutdown without initialization")
522 if s.state != serverShutDown {
523 // drop all the active views
524 s.session.Shutdown(ctx)
525 s.state = serverShutDown
530 func (s *Server) exit(ctx context.Context) error {
532 defer s.stateMu.Unlock()
534 // TODO: We need a better way to find the conn close method.
535 s.client.(io.Closer).Close()
537 if s.state != serverShutDown {
538 // TODO: We should be able to do better than this.
541 // we don't terminate the process on a normal exit, we just allow it to
542 // close naturally if needed after the connection is closed.