Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201105173854-bc9fc8d8c4bc / internal / lsp / general.go
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 lsp
6
7 import (
8         "bytes"
9         "context"
10         "fmt"
11         "io"
12         "os"
13         "path"
14         "path/filepath"
15         "strings"
16         "sync"
17
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"
25 )
26
27 func (s *Server) initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) {
28         s.stateMu.Lock()
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)
32         }
33         s.state = serverInitializing
34         s.stateMu.Unlock()
35
36         s.clientPID = int(params.ProcessID)
37         s.progress.supportsWorkDoneProgress = params.Capabilities.Window.WorkDoneProgress
38
39         options := s.session.Options()
40         defer func() { s.session.SetOptions(options) }()
41
42         if err := s.handleOptionResults(ctx, source.SetOptions(options, params.InitializationOptions)); err != nil {
43                 return nil, err
44         }
45         options.ForClientCapabilities(params.Capabilities)
46
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()),
53                         }}
54                 }
55         }
56         for _, folder := range folders {
57                 uri := span.URIFromURI(folder.URI)
58                 if !uri.IsFile() {
59                         continue
60                 }
61                 s.pendingFolders = append(s.pendingFolders, folder)
62         }
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)
67         }
68
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.
73                 //
74                 // Using CodeActionOptions is only valid if codeActionLiteralSupport is set.
75                 codeActionProvider = &protocol.CodeActionOptions{
76                         CodeActionKinds: s.getSupportedCodeActions(),
77                 }
78         }
79         var renameOpts interface{} = true
80         if r := params.Capabilities.TextDocument.Rename; r.PrepareSupport {
81                 renameOpts = protocol.RenameOptions{
82                         PrepareProvider: r.PrepareSupport,
83                 }
84         }
85
86         goplsVer := &bytes.Buffer{}
87         debug.PrintVersionInfo(ctx, goplsVer, true, debug.PlainText)
88
89         return &protocol.InitializeResult{
90                 Capabilities: protocol.ServerCapabilities{
91                         CallHierarchyProvider: true,
92                         CodeActionProvider:    codeActionProvider,
93                         CompletionProvider: protocol.CompletionOptions{
94                                 TriggerCharacters: []string{"."},
95                         },
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,
104                         },
105                         FoldingRangeProvider:      true,
106                         HoverProvider:             true,
107                         DocumentHighlightProvider: true,
108                         DocumentLinkProvider:      protocol.DocumentLinkOptions{},
109                         ReferencesProvider:        true,
110                         RenameProvider:            renameOpts,
111                         SignatureHelpProvider: protocol.SignatureHelpOptions{
112                                 TriggerCharacters: []string{"(", ","},
113                         },
114                         TextDocumentSync: &protocol.TextDocumentSyncOptions{
115                                 Change:    protocol.Incremental,
116                                 OpenClose: true,
117                                 Save: protocol.SaveOptions{
118                                         IncludeText: false,
119                                 },
120                         },
121                         Workspace: protocol.WorkspaceGn{
122                                 WorkspaceFolders: protocol.WorkspaceFoldersGn{
123                                         Supported:           true,
124                                         ChangeNotifications: "workspace/didChangeWorkspaceFolders",
125                                 },
126                         },
127                 },
128                 ServerInfo: struct {
129                         Name    string `json:"name"`
130                         Version string `json:"version,omitempty"`
131                 }{
132                         Name:    "gopls",
133                         Version: goplsVer.String(),
134                 },
135         }, nil
136
137 }
138
139 func (s *Server) initialized(ctx context.Context, params *protocol.InitializedParams) error {
140         s.stateMu.Lock()
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)
144         }
145         s.state = serverInitialized
146         s.stateMu.Unlock()
147
148         for _, not := range s.notifications {
149                 s.client.ShowMessage(ctx, not)
150         }
151         s.notifications = nil
152
153         options := s.session.Options()
154         defer func() { s.session.SetOptions(options) }()
155
156         if err := s.addFolders(ctx, s.pendingFolders); err != nil {
157                 return err
158         }
159         s.pendingFolders = nil
160
161         if options.ConfigurationSupported && options.DynamicConfigurationSupported {
162                 registrations := []protocol.Registration{
163                         {
164                                 ID:     "workspace/didChangeConfiguration",
165                                 Method: "workspace/didChangeConfiguration",
166                         },
167                         {
168                                 ID:     "workspace/didChangeWorkspaceFolders",
169                                 Method: "workspace/didChangeWorkspaceFolders",
170                         },
171                 }
172                 if options.SemanticTokens {
173                         registrations = append(registrations, semanticTokenRegistrations()...)
174
175                 }
176                 if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
177                         Registrations: registrations,
178                 }); err != nil {
179                         return err
180                 }
181         }
182         return nil
183 }
184
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)
188
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)
192                 defer func() {
193                         go func() {
194                                 wg.Wait()
195                                 work.end("Done.")
196                         }()
197                 }()
198         }
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.
205                 if !uri.IsFile() {
206                         continue
207                 }
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.
213                         //
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
217                         //    which one).
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
223                 }
224                 snapshot, release, err := s.addView(ctx, folder.Name, uri, workspaceURI)
225                 if err != nil {
226                         viewErrors[uri] = err
227                         work.end(fmt.Sprintf("Error loading packages: %s", err))
228                         continue
229                 }
230                 var swg sync.WaitGroup
231                 swg.Add(1)
232                 go func() {
233                         defer swg.Done()
234                         snapshot.AwaitInitialized(ctx)
235                         work.end("Finished loading packages.")
236                 }()
237
238                 for _, dir := range snapshot.WorkspaceDirectories(ctx) {
239                         dirsToWatch[dir] = struct{}{}
240                 }
241
242                 // Print each view's environment.
243                 buf := &bytes.Buffer{}
244                 if err := snapshot.WriteEnv(ctx, buf); err != nil {
245                         viewErrors[uri] = err
246                         continue
247                 }
248                 event.Log(ctx, buf.String())
249
250                 // Diagnose the newly created view.
251                 wg.Add(1)
252                 go func() {
253                         s.diagnoseDetached(snapshot)
254                         swg.Wait()
255                         release()
256                         wg.Done()
257                 }()
258         }
259         // Register for file watching notifications, if they are supported.
260         s.watchedDirectoriesMu.Lock()
261         err := s.registerWatchedDirectoriesLocked(ctx, dirsToWatch)
262         s.watchedDirectoriesMu.Unlock()
263         if err != nil {
264                 return err
265         }
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)
270                 }
271                 return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
272                         Type:    protocol.Error,
273                         Message: errMsg,
274                 })
275         }
276         return nil
277 }
278
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{}{}
286
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{}{}
292                 }
293         }
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 {
297                         continue
298                 }
299                 snapshot, release := view.Snapshot(ctx)
300                 for _, dir := range snapshot.WorkspaceDirectories(ctx) {
301                         dirsToWatch[dir] = struct{}{}
302                 }
303                 release()
304         }
305
306         s.watchedDirectoriesMu.Lock()
307         defer s.watchedDirectoriesMu.Unlock()
308
309         // Nothing to do if the set of workspace directories is unchanged.
310         if equalURISet(s.watchedDirectories, dirsToWatch) {
311                 return nil
312         }
313
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
318         // directories.
319         if s.watchRegistrationCount > 0 {
320                 prevID := s.watchRegistrationCount - 1
321                 if err := s.registerWatchedDirectoriesLocked(ctx, dirsToWatch); err != nil {
322                         return err
323                 }
324                 return s.client.UnregisterCapability(ctx, &protocol.UnregistrationParams{
325                         Unregisterations: []protocol.Unregistration{{
326                                 ID:     watchedFilesCapabilityID(prevID),
327                                 Method: "workspace/didChangeWatchedFiles",
328                         }},
329                 })
330         }
331         return nil
332 }
333
334 func watchedFilesCapabilityID(id uint64) string {
335         return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id)
336 }
337
338 func equalURISet(m1, m2 map[span.URI]struct{}) bool {
339         if len(m1) != len(m2) {
340                 return false
341         }
342         for k := range m1 {
343                 _, ok := m2[k]
344                 if !ok {
345                         return false
346                 }
347         }
348         return true
349 }
350
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 {
355                 return nil
356         }
357         for k := range s.watchedDirectories {
358                 delete(s.watchedDirectories, k)
359         }
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),
366         }}
367         for dir := range dirs {
368                 filename := dir.Filename()
369
370                 // If the directory is within a workspace folder, we're already
371                 // watching it via the relative path above.
372                 var matched bool
373                 for _, view := range s.session.Views() {
374                         if source.InDir(view.Folder().Filename(), filename) {
375                                 matched = true
376                                 break
377                         }
378                 }
379                 if matched {
380                         continue
381                 }
382
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),
389                 })
390         }
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{
396                                 Watchers: watchers,
397                         },
398                 }},
399         }); err != nil {
400                 return err
401         }
402         s.watchRegistrationCount++
403
404         for dir := range dirs {
405                 s.watchedDirectories[dir] = struct{}{}
406         }
407         return nil
408 }
409
410 func isSubdirectory(root, leaf string) bool {
411         rel, err := filepath.Rel(root, leaf)
412         return err == nil && !strings.HasPrefix(rel, "..")
413 }
414
415 func (s *Server) fetchConfig(ctx context.Context, name string, folder span.URI, o *source.Options) error {
416         if !s.session.Options().ConfigurationSupported {
417                 return nil
418         }
419         v := protocol.ParamConfiguration{
420                 ConfigurationParams: protocol.ConfigurationParams{
421                         Items: []protocol.ConfigurationItem{{
422                                 ScopeURI: string(folder),
423                                 Section:  "gopls",
424                         }, {
425                                 ScopeURI: string(folder),
426                                 Section:  fmt.Sprintf("gopls-%s", name),
427                         }},
428                 },
429         }
430         configs, err := s.client.Configuration(ctx, &v)
431         if err != nil {
432                 return fmt.Errorf("failed to get workspace configuration from client (%s): %v", folder, err)
433         }
434         for _, config := range configs {
435                 if err := s.handleOptionResults(ctx, source.SetOptions(o, config)); err != nil {
436                         return err
437                 }
438         }
439         return nil
440 }
441
442 func (s *Server) eventuallyShowMessage(ctx context.Context, msg *protocol.ShowMessageParams) error {
443         s.stateMu.Lock()
444         defer s.stateMu.Unlock()
445         if s.state == serverInitialized {
446                 return s.client.ShowMessage(ctx, msg)
447         }
448         s.notifications = append(s.notifications, msg)
449         return nil
450 }
451
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(),
458                         }
459                         if err := s.eventuallyShowMessage(ctx, msg); err != nil {
460                                 return err
461                         }
462                 }
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),
468                         }
469                         if err := s.eventuallyShowMessage(ctx, msg); err != nil {
470                                 return err
471                         }
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)
476                         }
477                         if err := s.eventuallyShowMessage(ctx, &protocol.ShowMessageParams{
478                                 Type:    protocol.Warning,
479                                 Message: msg,
480                         }); err != nil {
481                                 return err
482                         }
483                 }
484         }
485         return nil
486 }
487
488 // beginFileRequest checks preconditions for a file-oriented request and routes
489 // it to a snapshot.
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()
494         if !uri.IsFile() {
495                 // Not a file URI. Stop processing the request, but don't return an error.
496                 return nil, nil, false, func() {}, nil
497         }
498         view, err := s.session.ViewOf(uri)
499         if err != nil {
500                 return nil, nil, false, func() {}, err
501         }
502         snapshot, release := view.Snapshot(ctx)
503         fh, err := snapshot.GetVersionedFile(ctx, uri)
504         if err != nil {
505                 release()
506                 return nil, nil, false, func() {}, err
507         }
508         if expectKind != source.UnknownKind && fh.Kind() != expectKind {
509                 // Wrong kind of file. Nothing to do.
510                 release()
511                 return nil, nil, false, func() {}, nil
512         }
513         return snapshot, fh, true, release, nil
514 }
515
516 func (s *Server) shutdown(ctx context.Context) error {
517         s.stateMu.Lock()
518         defer s.stateMu.Unlock()
519         if s.state < serverInitialized {
520                 event.Log(ctx, "server shutdown without initialization")
521         }
522         if s.state != serverShutDown {
523                 // drop all the active views
524                 s.session.Shutdown(ctx)
525                 s.state = serverShutDown
526         }
527         return nil
528 }
529
530 func (s *Server) exit(ctx context.Context) error {
531         s.stateMu.Lock()
532         defer s.stateMu.Unlock()
533
534         // TODO: We need a better way to find the conn close method.
535         s.client.(io.Closer).Close()
536
537         if s.state != serverShutDown {
538                 // TODO: We should be able to do better than this.
539                 os.Exit(1)
540         }
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.
543         return nil
544 }