Debian Codegraph @

gopls/internal/server/text_synchronization.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 import (
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "path/filepath"
13 "strings"
14 "sync"
15
16 "golang.org/x/tools/gopls/internal/cache"
17 "golang.org/x/tools/gopls/internal/file"
18 "golang.org/x/tools/gopls/internal/golang"
19 "golang.org/x/tools/gopls/internal/label"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/internal/event"
22 "golang.org/x/tools/internal/jsonrpc2"
23 )
24
25 // ModificationSource identifies the origin of a change.
26 type ModificationSource int
27
28 const (
29 // FromDidOpen is from a didOpen notification.
30 FromDidOpen = ModificationSource(iota)
31
32 // FromDidChange is from a didChange notification.
33 FromDidChange
34
35 // FromDidChangeWatchedFiles is from didChangeWatchedFiles notification.
36 FromDidChangeWatchedFiles
37
38 // FromDidSave is from a didSave notification.
39 FromDidSave
40
41 // FromDidClose is from a didClose notification.
42 FromDidClose
43
44 // FromDidChangeConfiguration is from a didChangeConfiguration notification.
45 FromDidChangeConfiguration
46
47 // FromRegenerateCgo refers to file modifications caused by regenerating
48 // the cgo sources for the workspace.
49 FromRegenerateCgo
50
51 // FromInitialWorkspaceLoad refers to the loading of all packages in the
52 // workspace when the view is first created.
53 FromInitialWorkspaceLoad
54
55 // FromCheckUpgrades refers to state changes resulting from the CheckUpgrades
56 // command, which queries module upgrades.
57 FromCheckUpgrades
58
59 // FromResetGoModDiagnostics refers to state changes resulting from the
60 // ResetGoModDiagnostics command.
61 FromResetGoModDiagnostics
62
63 // FromToggleCompilerOptDetails refers to state changes resulting from toggling
64 // a package's compiler optimization details flag.
65 FromToggleCompilerOptDetails
66 )
67
68 func (m ModificationSource) String() string {
69 switch m {
70 case FromDidOpen:
71 return "opened files"
72 case FromDidChange:
73 return "changed files"
74 case FromDidChangeWatchedFiles:
75 return "files changed on disk"
76 case FromDidSave:
77 return "saved files"
78 case FromDidClose:
79 return "close files"
80 case FromRegenerateCgo:
81 return "regenerate cgo"
82 case FromInitialWorkspaceLoad:
83 return "initial workspace load"
84 case FromCheckUpgrades:
85 return "from check upgrades"
86 case FromResetGoModDiagnostics:
87 return "from resetting go.mod diagnostics"
88 default:
89 return "unknown file modification"
90 }
91 }
92
93 func (s *server) DidOpen(ctx context.Context, params *protocol.DidOpenTextDocumentParams) error {
94 ctx, done := event.Start(ctx, "server.DidOpen", label.URI.Of(params.TextDocument.URI))
95 defer done()
96
97 uri := params.TextDocument.URI
98 // There may not be any matching view in the current session. If that's
99 // the case, try creating a new view based on the opened file path.
100 //
101 // TODO(golang/go#57979): revisit creating a folder here. We should separate
102 // the logic for managing folders from the logic for managing views. But it
103 // does make sense to ensure at least one workspace folder the first time a
104 // file is opened, and we can't do that inside didModifyFiles because we
105 // don't want to request configuration while holding a lock.
106 if len(s.session.Views()) == 0 {
107 dir := uri.DirPath()
108 s.addFolders(ctx, []protocol.WorkspaceFolder{{
109 URI: string(protocol.URIFromPath(dir)),
110 Name: filepath.Base(dir),
111 }})
112 }
113 return s.didModifyFiles(ctx, FromDidOpen, file.Modification{
114 URI: uri,
115 Action: file.Open,
116 Version: params.TextDocument.Version,
117 Text: []byte(params.TextDocument.Text),
118 LanguageID: params.TextDocument.LanguageID,
119 })
120 }
121
122 func (s *server) DidChange(ctx context.Context, params *protocol.DidChangeTextDocumentParams) error {
123 ctx, done := event.Start(ctx, "server.DidChange", label.URI.Of(params.TextDocument.URI))
124 defer done()
125
126 uri := params.TextDocument.URI
127 text, err := s.changedText(ctx, uri, params.ContentChanges)
128 if err != nil {
129 return err
130 }
131 return s.didModifyFiles(ctx, FromDidChange, file.Modification{
132 URI: uri,
133 Action: file.Change,
134 Version: params.TextDocument.Version,
135 Text: text,
136 })
137 }
138
139 // warnAboutModifyingGeneratedFiles shows a warning if a user tries to edit a
140 // generated file for the first time.
141 func (s *server) warnAboutModifyingGeneratedFiles(ctx context.Context, uri protocol.DocumentURI) error {
142 s.changedFilesMu.Lock()
143 _, ok := s.changedFiles[uri]
144 if !ok {
145 s.changedFiles[uri] = struct{}{}
146 }
147 s.changedFilesMu.Unlock()
148
149 // This file has already been edited before.
150 if ok {
151 return nil
152 }
153
154 // Warn the user that they are editing a generated file, but
155 // don't try to stop them: there are often good reasons to do
156 // so, such as adding temporary logging, or evaluating changes
157 // to the generated code without the trouble of modifying the
158 // generator logic (see #73959).
159 snapshot, release, err := s.session.SnapshotOf(ctx, uri)
160 if err != nil {
161 return err
162 }
163 isGenerated := golang.IsGenerated(ctx, snapshot, uri)
164 release()
165 if isGenerated {
166 msg := fmt.Sprintf("Warning: editing %s, a generated file.", uri.Base())
167 showMessage(ctx, s.client, protocol.Warning, msg)
168 }
169 return nil
170 }
171
172 func (s *server) DidChangeWatchedFiles(ctx context.Context, params *protocol.DidChangeWatchedFilesParams) error {
173 ctx, done := event.Start(ctx, "server.DidChangeWatchedFiles")
174 defer done()
175
176 modifications := make([]file.Modification, len(params.Changes))
177 for i, change := range params.Changes {
178 action := changeTypeToFileAction(change.Type)
179 modifications[i] = file.Modification{
180 URI: change.URI,
181 Action: action,
182 OnDisk: true,
183 }
184 }
185 return s.didModifyFiles(ctx, FromDidChangeWatchedFiles, modifications...)
186 }
187
188 func (s *server) DidSave(ctx context.Context, params *protocol.DidSaveTextDocumentParams) error {
189 ctx, done := event.Start(ctx, "server.DidSave", label.URI.Of(params.TextDocument.URI))
190 defer done()
191
192 var text []byte
193 if params.Text != nil {
194 text = []byte(*params.Text)
195 }
196 return s.didModifyFiles(ctx, FromDidSave, file.Modification{
197 URI: params.TextDocument.URI,
198 Action: file.Save,
199 Text: text,
200 })
201 }
202
203 func (s *server) DidClose(ctx context.Context, params *protocol.DidCloseTextDocumentParams) error {
204 ctx, done := event.Start(ctx, "server.DidClose", label.URI.Of(params.TextDocument.URI))
205 defer done()
206
207 return s.didModifyFiles(ctx, FromDidClose, file.Modification{
208 URI: params.TextDocument.URI,
209 Action: file.Close,
210 Version: -1,
211 Text: nil,
212 })
213 }
214
215 func (s *server) didModifyFiles(ctx context.Context, cause ModificationSource, modifications ...file.Modification) error {
216 // Something happened. Wake up a quiescent file watcher.
217 s.fileWatcherMu.Lock()
218 if s.fileWatcher != nil {
219 s.fileWatcher.Poke()
220 }
221 s.fileWatcherMu.Unlock()
222
223 // wg guards two conditions:
224 // 1. didModifyFiles is complete
225 // 2. the goroutine diagnosing changes on behalf of didModifyFiles is
226 // complete, if it was started
227 //
228 // Both conditions must be satisfied for the purpose of testing: we don't
229 // want to observe the completion of change processing until we have received
230 // all diagnostics as well as all server->client notifications done on behalf
231 // of this function.
232 var wg sync.WaitGroup
233 wg.Add(1)
234 defer wg.Done()
235
236 if s.Options().VerboseWorkDoneProgress {
237 work := s.progress.Start(ctx, DiagnosticWorkTitle(cause), "Calculating file diagnostics...", nil, nil)
238 go func() {
239 wg.Wait()
240 work.End(ctx, "Done.")
241 }()
242 }
243
244 s.stateMu.Lock()
245 if s.state >= serverShutDown {
246 // This state check does not prevent races below, and exists only to
247 // produce a better error message. The actual race to the cache should be
248 // guarded by Session.viewMu.
249 s.stateMu.Unlock()
250 return errors.New("server is shut down")
251 }
252 s.stateMu.Unlock()
253
254 // If the set of changes included directories, expand those directories
255 // to their files.
256 modifications = s.session.ExpandModificationsToDirectories(ctx, modifications)
257
258 s.handleModuleChanges(ctx, modifications, cause)
259
260 viewsToDiagnose, err := s.session.DidModifyFiles(ctx, modifications)
261 if err != nil {
262 return err
263 }
264
265 // golang/go#50267: diagnostics should be re-sent after each change.
266 for _, mod := range modifications {
267 s.mustPublishDiagnostics(mod.URI)
268
269 if cause == FromDidChange && mod.Action == file.Change {
270 if err := s.warnAboutModifyingGeneratedFiles(ctx, mod.URI); err != nil {
271 return err // e.g. failed to get snapshot
272 }
273 }
274 }
275
276 modCtx, modID := s.needsDiagnosis(ctx, viewsToDiagnose)
277
278 wg.Go(func() {
279 s.diagnoseChangedViews(modCtx, modID, viewsToDiagnose, cause)
280 })
281
282 // After any file modifications, we need to update our watched files,
283 // in case something changed. Compute the new set of directories to watch,
284 // and if it differs from the current set, send updated registrations.
285 return s.updateWatchedDirectories(ctx)
286 }
287
288 func (s *server) handleModuleChanges(ctx context.Context, modifications []file.Modification, cause ModificationSource) {
289 // If any change in this batch is not a module metadata file, gopls will treat
290 // the entire batch as a bulk operation (like a git branch switch). This is to
291 // avoid doing expensive dependency checks for every module file in a
292 // large change, which is redundant during a full workspace load.
293 //
294 // This also accounts for "atomic saves" in editors like Vim/Neovim,
295 // which may surface as a Delete + Create sequence in the file watcher
296 // rather than a single Save event.
297 if cause == FromDidChangeWatchedFiles {
298 for _, m := range modifications {
299 switch m.URI.Base() {
300 case "go.mod", "go.sum", "go.work", "go.work.sum":
301 // Module metadata file; continue checking.
302 default:
303 // Batch contains non-module files; skip dependency checks.
304 return
305 }
306 }
307 }
308
309 uris := make(map[protocol.DocumentURI]struct{})
310 for _, m := range modifications {
311 if (m.URI.Base() == "go.mod" || m.URI.Base() == "go.work") && (m.Action == file.Create || m.Action == file.Save) {
312 uris[m.URI] = struct{}{}
313 }
314 }
315
316 for uri := range uris {
317 go s.checkDependencyChanges(ctx, uri)
318 }
319 }
320
321 // needsDiagnosis records the given views as needing diagnosis, returning the
322 // context and modification id to use for said diagnosis.
323 //
324 // Only the keys of viewsToDiagnose are used; the changed files are irrelevant.
325 func (s *server) needsDiagnosis(ctx context.Context, viewsToDiagnose map[*cache.View][]protocol.DocumentURI) (context.Context, uint64) {
326 s.modificationMu.Lock()
327 defer s.modificationMu.Unlock()
328 if s.cancelPrevDiagnostics != nil {
329 s.cancelPrevDiagnostics()
330 }
331 modCtx := context.WithoutCancel(ctx)
332 modCtx, s.cancelPrevDiagnostics = context.WithCancel(modCtx)
333 s.lastModificationID++
334 modID := s.lastModificationID
335
336 for v := range viewsToDiagnose {
337 if needs, ok := s.viewsToDiagnose[v]; !ok || needs < modID {
338 s.viewsToDiagnose[v] = modID
339 }
340 }
341 return modCtx, modID
342 }
343
344 // DiagnosticWorkTitle returns the title of the diagnostic work resulting from a
345 // file change originating from the given cause.
346 func DiagnosticWorkTitle(cause ModificationSource) string {
347 return fmt.Sprintf("diagnosing %v", cause)
348 }
349
350 func (s *server) changedText(ctx context.Context, uri protocol.DocumentURI, changes []protocol.TextDocumentContentChangeEvent) ([]byte, error) {
351 if len(changes) == 0 {
352 return nil, fmt.Errorf("%w: no content changes provided", jsonrpc2.ErrInternal)
353 }
354
355 // Check if the client sent the full content of the file.
356 // We accept a full content change even if the server expected incremental changes.
357 if len(changes) == 1 && changes[0].Range == nil && changes[0].RangeLength == nil {
358 changeFull.Inc()
359 return []byte(changes[0].Text), nil
360 }
361 return s.applyIncrementalChanges(ctx, uri, changes)
362 }
363
364 func (s *server) applyIncrementalChanges(ctx context.Context, uri protocol.DocumentURI, changes []protocol.TextDocumentContentChangeEvent) ([]byte, error) {
365 fh, err := s.session.ReadFile(ctx, uri)
366 if err != nil {
367 return nil, err
368 }
369 content, err := fh.Content()
370 if err != nil {
371 return nil, fmt.Errorf("%w: file not found (%v)", jsonrpc2.ErrInternal, err)
372 }
373 for i, change := range changes {
374 // TODO(adonovan): refactor to use diff.Apply, which is robust w.r.t.
375 // out-of-order or overlapping changes---and much more efficient.
376
377 // Make sure to update mapper along with the content.
378 m := protocol.NewMapper(uri, content)
379 if change.Range == nil {
380 return nil, fmt.Errorf("%w: unexpected nil range for change", jsonrpc2.ErrInternal)
381 }
382 start, end, err := m.RangeOffsets(*change.Range)
383 if err != nil {
384 return nil, err
385 }
386 if end < start {
387 return nil, fmt.Errorf("%w: invalid range for content change", jsonrpc2.ErrInternal)
388 }
389 var buf bytes.Buffer
390 buf.Write(content[:start])
391 buf.WriteString(change.Text)
392 buf.Write(content[end:])
393 content = buf.Bytes()
394 if i == 0 { // only look at the first change if there are seversl
395 // TODO(pjw): understand multi-change)
396 s.checkEfficacy(fh.URI(), fh.Version(), change)
397 }
398 }
399 return content, nil
400 }
401
402 // increment counters if any of the completions look like there were used
403 func (s *server) checkEfficacy(uri protocol.DocumentURI, version int32, change protocol.TextDocumentContentChangePartial) {
404 s.efficacyMu.Lock()
405 defer s.efficacyMu.Unlock()
406 if s.efficacyURI != uri {
407 return
408 }
409 // gopls increments the version, the test client does not
410 if version != s.efficacyVersion && version != s.efficacyVersion+1 {
411 return
412 }
413 // does any change at pos match a proposed completion item?
414 for _, item := range s.efficacyItems {
415 if item.TextEdit == nil {
416 continue
417 }
418 // CompletionTextEdit may have both insert/replace mode ranges.
419 // According to the LSP spec, if an `InsertReplaceEdit` is returned
420 // the edit's insert range must be a prefix of the edit's replace range,
421 // that means it must be contained and starting at the same position.
422 // The efficacy computation uses only the start range, so it is not
423 // affected by whether the client applied the suggestion in insert
424 // or replace mode. Let's just use the replace mode that was the default
425 // in gopls for a while.
426 edit, err := protocol.SelectCompletionTextEdit(item, false)
427 if err != nil {
428 continue
429 }
430 if edit.Range.Start == change.Range.Start {
431 // the change and the proposed completion start at the same
432 if (change.RangeLength == nil || *change.RangeLength == 0) && len(change.Text) == 1 {
433 // a single character added it does not count as a completion
434 continue
435 }
436 ix := strings.Index(edit.NewText, "$")
437 if ix < 0 && strings.HasPrefix(change.Text, edit.NewText) {
438 // not a snippet, suggested completion is a prefix of the change
439 complUsed.Inc()
440 return
441 }
442 if ix > 1 && strings.HasPrefix(change.Text, edit.NewText[:ix]) {
443 // a snippet, suggested completion up to $ marker is a prefix of the change
444 complUsed.Inc()
445 return
446 }
447 }
448 }
449 complUnused.Inc()
450 }
451
452 func changeTypeToFileAction(ct protocol.FileChangeType) file.Action {
453 switch ct {
454 case protocol.Changed:
455 return file.Change
456 case protocol.Created:
457 return file.Create
458 case protocol.Deleted:
459 return file.Delete
460 }
461 return file.UnknownAction
462 }