github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/general.go (about)

     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  	"encoding/json"
    11  	"fmt"
    12  	"os"
    13  	"path"
    14  	"path/filepath"
    15  	"sync"
    16  
    17  	"github.com/powerman/golang-tools/internal/event"
    18  	"github.com/powerman/golang-tools/internal/jsonrpc2"
    19  	"github.com/powerman/golang-tools/internal/lsp/debug"
    20  	"github.com/powerman/golang-tools/internal/lsp/protocol"
    21  	"github.com/powerman/golang-tools/internal/lsp/source"
    22  	"github.com/powerman/golang-tools/internal/span"
    23  	errors "golang.org/x/xerrors"
    24  )
    25  
    26  func (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.
   106  Please reinstall gopls by running 'GO111MODULE=on go install github.com/powerman/golang-tools/gopls@latest'.
   107  See 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.Workspace6Gn{
   153  				WorkspaceFolders: protocol.WorkspaceFolders5Gn{
   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  
   169  func (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  	var registrations []protocol.Registration
   192  	if options.ConfigurationSupported && options.DynamicConfigurationSupported {
   193  		registrations = append(registrations, protocol.Registration{
   194  			ID:     "workspace/didChangeConfiguration",
   195  			Method: "workspace/didChangeConfiguration",
   196  		})
   197  	}
   198  	if options.SemanticTokens && options.DynamicRegistrationSemanticTokensSupported {
   199  		registrations = append(registrations, semanticTokenRegistration(options.SemanticTypes, options.SemanticMods))
   200  	}
   201  	if len(registrations) > 0 {
   202  		if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{
   203  			Registrations: registrations,
   204  		}); err != nil {
   205  			return err
   206  		}
   207  	}
   208  	return nil
   209  }
   210  
   211  func (s *Server) addFolders(ctx context.Context, folders []protocol.WorkspaceFolder) error {
   212  	originalViews := len(s.session.Views())
   213  	viewErrors := make(map[span.URI]error)
   214  
   215  	var wg sync.WaitGroup
   216  	if s.session.Options().VerboseWorkDoneProgress {
   217  		work := s.progress.Start(ctx, DiagnosticWorkTitle(FromInitialWorkspaceLoad), "Calculating diagnostics for initial workspace load...", nil, nil)
   218  		defer func() {
   219  			go func() {
   220  				wg.Wait()
   221  				work.End("Done.")
   222  			}()
   223  		}()
   224  	}
   225  	// Only one view gets to have a workspace.
   226  	var allFoldersWg sync.WaitGroup
   227  	for _, folder := range folders {
   228  		uri := span.URIFromURI(folder.URI)
   229  		// Ignore non-file URIs.
   230  		if !uri.IsFile() {
   231  			continue
   232  		}
   233  		work := s.progress.Start(ctx, "Setting up workspace", "Loading packages...", nil, nil)
   234  		snapshot, release, err := s.addView(ctx, folder.Name, uri)
   235  		if err == source.ErrViewExists {
   236  			continue
   237  		}
   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.
   296  func (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  
   327  func watchedFilesCapabilityID(id int) string {
   328  	return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id)
   329  }
   330  
   331  func 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.
   346  func (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  
   380  func (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  
   403  func (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  
   413  func (s *Server) handleOptionResults(ctx context.Context, results source.OptionResults) error {
   414  	for _, result := range results {
   415  		var msg *protocol.ShowMessageParams
   416  		switch result.Error.(type) {
   417  		case nil:
   418  			// nothing to do
   419  		case *source.SoftError:
   420  			msg = &protocol.ShowMessageParams{
   421  				Type:    protocol.Warning,
   422  				Message: result.Error.Error(),
   423  			}
   424  		default:
   425  			msg = &protocol.ShowMessageParams{
   426  				Type:    protocol.Error,
   427  				Message: result.Error.Error(),
   428  			}
   429  		}
   430  		if msg != nil {
   431  			if err := s.eventuallyShowMessage(ctx, msg); err != nil {
   432  				return err
   433  			}
   434  		}
   435  	}
   436  	return nil
   437  }
   438  
   439  // beginFileRequest checks preconditions for a file-oriented request and routes
   440  // it to a snapshot.
   441  // We don't want to return errors for benign conditions like wrong file type,
   442  // so callers should do if !ok { return err } rather than if err != nil.
   443  func (s *Server) beginFileRequest(ctx context.Context, pURI protocol.DocumentURI, expectKind source.FileKind) (source.Snapshot, source.VersionedFileHandle, bool, func(), error) {
   444  	uri := pURI.SpanURI()
   445  	if !uri.IsFile() {
   446  		// Not a file URI. Stop processing the request, but don't return an error.
   447  		return nil, nil, false, func() {}, nil
   448  	}
   449  	view, err := s.session.ViewOf(uri)
   450  	if err != nil {
   451  		return nil, nil, false, func() {}, err
   452  	}
   453  	snapshot, release := view.Snapshot(ctx)
   454  	fh, err := snapshot.GetVersionedFile(ctx, uri)
   455  	if err != nil {
   456  		release()
   457  		return nil, nil, false, func() {}, err
   458  	}
   459  	kind := snapshot.View().FileKind(fh)
   460  	if expectKind != source.UnknownKind && kind != expectKind {
   461  		// Wrong kind of file. Nothing to do.
   462  		release()
   463  		return nil, nil, false, func() {}, nil
   464  	}
   465  	return snapshot, fh, true, release, nil
   466  }
   467  
   468  func (s *Server) shutdown(ctx context.Context) error {
   469  	s.stateMu.Lock()
   470  	defer s.stateMu.Unlock()
   471  	if s.state < serverInitialized {
   472  		event.Log(ctx, "server shutdown without initialization")
   473  	}
   474  	if s.state != serverShutDown {
   475  		// drop all the active views
   476  		s.session.Shutdown(ctx)
   477  		s.state = serverShutDown
   478  		if s.tempDir != "" {
   479  			if err := os.RemoveAll(s.tempDir); err != nil {
   480  				event.Error(ctx, "removing temp dir", err)
   481  			}
   482  		}
   483  	}
   484  	return nil
   485  }
   486  
   487  func (s *Server) exit(ctx context.Context) error {
   488  	s.stateMu.Lock()
   489  	defer s.stateMu.Unlock()
   490  
   491  	s.client.Close()
   492  
   493  	if s.state != serverShutDown {
   494  		// TODO: We should be able to do better than this.
   495  		os.Exit(1)
   496  	}
   497  	// we don't terminate the process on a normal exit, we just allow it to
   498  	// close naturally if needed after the connection is closed.
   499  	return nil
   500  }