Debian Codegraph @

gopls/internal/cache/mod.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 cache
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "regexp"
12 "slices"
13 "strings"
14
15 "golang.org/x/mod/modfile"
16 "golang.org/x/mod/module"
17 "golang.org/x/tools/go/packages"
18 "golang.org/x/tools/gopls/internal/file"
19 "golang.org/x/tools/gopls/internal/label"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/protocol/command"
22 "golang.org/x/tools/gopls/internal/util/memoize"
23 "golang.org/x/tools/internal/event"
24 )
25
26 // A ParsedModule contains the results of parsing a go.mod file.
27 type ParsedModule struct {
28 URI protocol.DocumentURI
29 File *modfile.File // maybe absent in case of error
30 ReplaceMap map[module.Version]module.Version
31 Mapper *protocol.Mapper
32 ParseErrors []*Diagnostic
33 }
34
35 // ParseMod parses a go.mod file, using a cache. It may return partial results and an error.
36 func (s *Snapshot) ParseMod(ctx context.Context, fh file.Handle) (*ParsedModule, error) {
37 uri := fh.URI()
38
39 s.mu.Lock()
40 entry, hit := s.parseModHandles.Get(uri)
41 s.mu.Unlock()
42
43 type parseModKey file.Identity
44 type parseModResult struct {
45 parsed *ParsedModule
46 err error
47 }
48
49 // cache miss?
50 if !hit {
51 promise, release := s.store.Promise(parseModKey(fh.Identity()), func(ctx context.Context, _ any) any {
52 parsed, err := parseModImpl(ctx, fh)
53 return parseModResult{parsed, err}
54 })
55
56 entry = promise
57 s.mu.Lock()
58 s.parseModHandles.Set(uri, entry, func(_, _ any) { release() })
59 s.mu.Unlock()
60 }
61
62 // Await result.
63 v, err := s.awaitPromise(ctx, entry)
64 if err != nil {
65 return nil, err
66 }
67 res := v.(parseModResult)
68 return res.parsed, res.err
69 }
70
71 // parseModImpl parses the go.mod file whose name and contents are in fh.
72 // It may return partial results and an error.
73 func parseModImpl(ctx context.Context, fh file.Handle) (*ParsedModule, error) {
74 _, done := event.Start(ctx, "cache.ParseMod", label.URI.Of(fh.URI()))
75 defer done()
76
77 contents, err := fh.Content()
78 if err != nil {
79 return nil, err
80 }
81 m := protocol.NewMapper(fh.URI(), contents)
82 file, parseErr := modfile.Parse(fh.URI().Path(), contents, nil)
83 // Attempt to convert the error to a standardized parse error.
84 var parseErrors []*Diagnostic
85 if parseErr != nil {
86 mfErrList, ok := parseErr.(modfile.ErrorList)
87 if !ok {
88 return nil, fmt.Errorf("unexpected parse error type %v", parseErr)
89 }
90 for _, mfErr := range mfErrList {
91 rng, err := m.OffsetRange(mfErr.Pos.Byte, mfErr.Pos.Byte)
92 if err != nil {
93 return nil, err
94 }
95 parseErrors = append(parseErrors, &Diagnostic{
96 URI: fh.URI(),
97 Range: rng,
98 Severity: protocol.SeverityError,
99 Source: ParseError,
100 Message: mfErr.Err.Error(),
101 })
102 }
103 }
104
105 replaceMap := make(map[module.Version]module.Version)
106 if parseErr == nil {
107 for _, rep := range file.Replace {
108 replaceMap[rep.Old] = rep.New
109 }
110 }
111
112 return &ParsedModule{
113 URI: fh.URI(),
114 Mapper: m,
115 File: file,
116 ReplaceMap: replaceMap,
117 ParseErrors: parseErrors,
118 }, parseErr
119 }
120
121 // A ParsedWorkFile contains the results of parsing a go.work file.
122 type ParsedWorkFile struct {
123 URI protocol.DocumentURI
124 File *modfile.WorkFile
125 Mapper *protocol.Mapper
126 ParseErrors []*Diagnostic
127 }
128
129 // ParseWork parses a go.work file, using a cache. It may return partial results and an error.
130 // TODO(adonovan): move to new work.go file.
131 func (s *Snapshot) ParseWork(ctx context.Context, fh file.Handle) (*ParsedWorkFile, error) {
132 uri := fh.URI()
133
134 s.mu.Lock()
135 entry, hit := s.parseWorkHandles.Get(uri)
136 s.mu.Unlock()
137
138 type parseWorkKey file.Identity
139 type parseWorkResult struct {
140 parsed *ParsedWorkFile
141 err error
142 }
143
144 // cache miss?
145 if !hit {
146 handle, release := s.store.Promise(parseWorkKey(fh.Identity()), func(ctx context.Context, _ any) any {
147 parsed, err := parseWorkImpl(ctx, fh)
148 return parseWorkResult{parsed, err}
149 })
150
151 entry = handle
152 s.mu.Lock()
153 s.parseWorkHandles.Set(uri, entry, func(_, _ any) { release() })
154 s.mu.Unlock()
155 }
156
157 // Await result.
158 v, err := s.awaitPromise(ctx, entry)
159 if err != nil {
160 return nil, err
161 }
162 res := v.(parseWorkResult)
163 return res.parsed, res.err
164 }
165
166 // parseWorkImpl parses a go.work file. It may return partial results and an error.
167 func parseWorkImpl(ctx context.Context, fh file.Handle) (*ParsedWorkFile, error) {
168 _, done := event.Start(ctx, "cache.ParseWork", label.URI.Of(fh.URI()))
169 defer done()
170
171 content, err := fh.Content()
172 if err != nil {
173 return nil, err
174 }
175 m := protocol.NewMapper(fh.URI(), content)
176 file, parseErr := modfile.ParseWork(fh.URI().Path(), content, nil)
177 // Attempt to convert the error to a standardized parse error.
178 var parseErrors []*Diagnostic
179 if parseErr != nil {
180 mfErrList, ok := parseErr.(modfile.ErrorList)
181 if !ok {
182 return nil, fmt.Errorf("unexpected parse error type %v", parseErr)
183 }
184 for _, mfErr := range mfErrList {
185 rng, err := m.OffsetRange(mfErr.Pos.Byte, mfErr.Pos.Byte)
186 if err != nil {
187 return nil, err
188 }
189 parseErrors = append(parseErrors, &Diagnostic{
190 URI: fh.URI(),
191 Range: rng,
192 Severity: protocol.SeverityError,
193 Source: ParseError,
194 Message: mfErr.Err.Error(),
195 })
196 }
197 }
198 return &ParsedWorkFile{
199 URI: fh.URI(),
200 Mapper: m,
201 File: file,
202 ParseErrors: parseErrors,
203 }, parseErr
204 }
205
206 // ModWhy returns the "go mod why" result for each module named in a
207 // require statement in the go.mod file.
208 // TODO(adonovan): move to new mod_why.go file.
209 func (s *Snapshot) ModWhy(ctx context.Context, fh file.Handle) (map[string]string, error) {
210 uri := fh.URI()
211
212 if s.FileKind(fh) != file.Mod {
213 return nil, fmt.Errorf("%s is not a go.mod file", uri)
214 }
215
216 s.mu.Lock()
217 entry, hit := s.modWhyHandles.Get(uri)
218 s.mu.Unlock()
219
220 type modWhyResult struct {
221 why map[string]string
222 err error
223 }
224
225 // cache miss?
226 if !hit {
227 handle := memoize.NewPromise("modWhy", func(ctx context.Context, arg any) any {
228 why, err := modWhyImpl(ctx, arg.(*Snapshot), fh)
229 return modWhyResult{why, err}
230 })
231
232 entry = handle
233 s.mu.Lock()
234 s.modWhyHandles.Set(uri, entry, nil)
235 s.mu.Unlock()
236 }
237
238 // Await result.
239 v, err := s.awaitPromise(ctx, entry)
240 if err != nil {
241 return nil, err
242 }
243 res := v.(modWhyResult)
244 return res.why, res.err
245 }
246
247 // modWhyImpl returns the result of "go mod why -m" on the specified go.mod file.
248 func modWhyImpl(ctx context.Context, snapshot *Snapshot, fh file.Handle) (map[string]string, error) {
249 ctx, done := event.Start(ctx, "cache.ModWhy", label.URI.Of(fh.URI()))
250 defer done()
251
252 pm, err := snapshot.ParseMod(ctx, fh)
253 if err != nil {
254 return nil, err
255 }
256 // No requires to explain.
257 if len(pm.File.Require) == 0 {
258 return nil, nil // empty result
259 }
260 // Run `go mod why` on all the dependencies.
261 args := []string{"why", "-m"}
262 for _, req := range pm.File.Require {
263 args = append(args, req.Mod.Path)
264 }
265 inv, cleanupInvocation, err := snapshot.GoCommandInvocation(NoNetwork, fh.URI().DirPath(), "mod", args)
266 if err != nil {
267 return nil, err
268 }
269 defer cleanupInvocation()
270 stdout, err := snapshot.View().GoCommandRunner().Run(ctx, *inv)
271 if err != nil {
272 return nil, err
273 }
274 whyList := strings.Split(stdout.String(), "\n\n")
275 if len(whyList) != len(pm.File.Require) {
276 return nil, fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require))
277 }
278 why := make(map[string]string, len(pm.File.Require))
279 for i, req := range pm.File.Require {
280 why[req.Mod.Path] = whyList[i]
281 }
282 return why, nil
283 }
284
285 // extractGoCommandErrors tries to parse errors that come from the go command
286 // and shape them into go.mod diagnostics.
287 // TODO: rename this to 'load errors'
288 func (s *Snapshot) extractGoCommandErrors(ctx context.Context, goCmdError error) []*Diagnostic {
289 if goCmdError == nil {
290 return nil
291 }
292
293 type locatedErr struct {
294 loc protocol.Location
295 msg string
296 }
297 diagLocations := map[*ParsedModule]locatedErr{}
298 backupDiagLocations := map[*ParsedModule]locatedErr{}
299
300 // If moduleErrs is non-nil, go command errors are scoped to specific
301 // modules.
302 var moduleErrs *moduleErrorMap
303 _ = errors.As(goCmdError, &moduleErrs)
304
305 // Match the error against all the mod files in the workspace.
306 for _, uri := range s.View().ModFiles() {
307 fh, err := s.ReadFile(ctx, uri)
308 if err != nil {
309 event.Error(ctx, "getting modfile for Go command error", err)
310 continue
311 }
312 pm, err := s.ParseMod(ctx, fh)
313 if err != nil {
314 // Parsing errors are reported elsewhere
315 return nil
316 }
317 var msgs []string // error messages to consider
318 if moduleErrs != nil {
319 if pm.File.Module != nil {
320 for _, mes := range moduleErrs.errs[pm.File.Module.Mod.Path] {
321 msgs = append(msgs, mes.Error())
322 }
323 }
324 } else {
325 msgs = append(msgs, goCmdError.Error())
326 }
327 for _, msg := range msgs {
328 if strings.Contains(goCmdError.Error(), "errors parsing go.mod") {
329 // The go command emits parse errors for completely invalid go.mod files.
330 // Those are reported by our own diagnostics and can be ignored here.
331 // As of writing, we are not aware of any other errors that include
332 // file/position information, so don't even try to find it.
333 continue
334 }
335 loc, found, err := s.matchErrorToModule(pm, msg)
336 if err != nil {
337 event.Error(ctx, "matching error to module", err)
338 continue
339 }
340 le := locatedErr{
341 loc: loc,
342 msg: msg,
343 }
344 if found {
345 diagLocations[pm] = le
346 } else {
347 backupDiagLocations[pm] = le
348 }
349 }
350 }
351
352 // If we didn't find any good matches, assign diagnostics to all go.mod files.
353 if len(diagLocations) == 0 {
354 diagLocations = backupDiagLocations
355 }
356
357 var srcErrs []*Diagnostic
358 for pm, le := range diagLocations {
359 diag, err := s.goCommandDiagnostic(pm, le.loc, le.msg)
360 if err != nil {
361 event.Error(ctx, "building go command diagnostic", err)
362 continue
363 }
364 srcErrs = append(srcErrs, diag)
365 }
366 return srcErrs
367 }
368
369 var moduleVersionInErrorRe = regexp.MustCompile(`[:\s]([+-._~0-9A-Za-z]+)@([+-._~0-9A-Za-z]+)[:\s]`)
370
371 // matchErrorToModule matches a go command error message to a go.mod file.
372 // Some examples:
373 //
374 // [email protected]: reading example.com/@v/v1.2.2.mod: no such file or directory
375 // go: github.com/cockroachdb/apd/[email protected]: reading github.com/cockroachdb/apd/go.mod at revision v2.0.72: unknown revision v2.0.72
376 // go: [email protected] requires\n\[email protected]: parsing go.mod:\n\tmodule declares its path as: bob.org\n\tbut was required as: random.org
377 //
378 // It returns the location of a reference to the one of the modules and true
379 // if one exists. If none is found it returns a fallback location and false.
380 func (s *Snapshot) matchErrorToModule(pm *ParsedModule, goCmdError string) (protocol.Location, bool, error) {
381 var reference *modfile.Line
382 matches := moduleVersionInErrorRe.FindAllStringSubmatch(goCmdError, -1)
383
384 for _, match := range slices.Backward(matches) {
385 ver := module.Version{Path: match[1], Version: match[2]}
386 if err := module.Check(ver.Path, ver.Version); err != nil {
387 continue
388 }
389 reference = findModuleReference(pm.File, ver)
390 if reference != nil {
391 break
392 }
393 }
394
395 if reference == nil {
396 // No match for the module path was found in the go.mod file.
397 // Show the error on the module declaration, if one exists, or
398 // just the first line of the file.
399 var start, end int
400 if pm.File.Module != nil && pm.File.Module.Syntax != nil {
401 syntax := pm.File.Module.Syntax
402 start, end = syntax.Start.Byte, syntax.End.Byte
403 }
404 loc, err := pm.Mapper.OffsetLocation(start, end)
405 return loc, false, err
406 }
407
408 loc, err := pm.Mapper.OffsetLocation(reference.Start.Byte, reference.End.Byte)
409 return loc, true, err
410 }
411
412 // goCommandDiagnostic creates a diagnostic for a given go command error.
413 func (s *Snapshot) goCommandDiagnostic(pm *ParsedModule, loc protocol.Location, goCmdError string) (*Diagnostic, error) {
414 matches := moduleVersionInErrorRe.FindAllStringSubmatch(goCmdError, -1)
415 var innermost *module.Version
416 for _, match := range slices.Backward(matches) {
417 ver := module.Version{Path: match[1], Version: match[2]}
418 if err := module.Check(ver.Path, ver.Version); err != nil {
419 continue
420 }
421 innermost = &ver
422 break
423 }
424
425 switch {
426 case strings.Contains(goCmdError, "inconsistent vendoring"):
427 cmd := command.NewVendorCommand("Run go mod vendor", command.URIArg{URI: pm.URI})
428 return &Diagnostic{
429 URI: pm.URI,
430 Range: loc.Range,
431 Severity: protocol.SeverityError,
432 Source: ListError,
433 Message: `Inconsistent vendoring detected. Please re-run "go mod vendor".
434 See https://github.com/golang/go/issues/39164 for more detail on this issue.`,
435 SuggestedFixes: []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)},
436 }, nil
437
438 case strings.Contains(goCmdError, "updates to go.sum needed"), strings.Contains(goCmdError, "missing go.sum entry"):
439 var args []protocol.DocumentURI
440 args = append(args, s.View().ModFiles()...)
441 tidyCmd := command.NewTidyCommand("Run go mod tidy", command.URIArgs{URIs: args})
442 updateCmd := command.NewUpdateGoSumCommand("Update go.sum", command.URIArgs{URIs: args})
443 msg := "go.sum is out of sync with go.mod. Please update it by applying the quick fix."
444 if innermost != nil {
445 msg = fmt.Sprintf("go.sum is out of sync with go.mod: entry for %v is missing. Please updating it by applying the quick fix.", innermost)
446 }
447 return &Diagnostic{
448 URI: pm.URI,
449 Range: loc.Range,
450 Severity: protocol.SeverityError,
451 Source: ListError,
452 Message: msg,
453 SuggestedFixes: []SuggestedFix{
454 SuggestedFixFromCommand(tidyCmd, protocol.QuickFix),
455 SuggestedFixFromCommand(updateCmd, protocol.QuickFix),
456 },
457 }, nil
458 case strings.Contains(goCmdError, "disabled by GOPROXY=off") && innermost != nil:
459 title := fmt.Sprintf("Download %v@%v", innermost.Path, innermost.Version)
460 cmd := command.NewAddDependencyCommand(title, command.DependencyArgs{
461 URI: pm.URI,
462 AddRequire: false,
463 GoCmdArgs: []string{fmt.Sprintf("%v@%v", innermost.Path, innermost.Version)},
464 })
465 return &Diagnostic{
466 URI: pm.URI,
467 Range: loc.Range,
468 Severity: protocol.SeverityError,
469 Message: fmt.Sprintf("%v@%v has not been downloaded", innermost.Path, innermost.Version),
470 Source: ListError,
471 SuggestedFixes: []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)},
472 }, nil
473 default:
474 return &Diagnostic{
475 URI: pm.URI,
476 Range: loc.Range,
477 Severity: protocol.SeverityError,
478 Source: ListError,
479 Message: goCmdError,
480 }, nil
481 }
482 }
483
484 func findModuleReference(mf *modfile.File, ver module.Version) *modfile.Line {
485 for _, req := range mf.Require {
486 if req.Mod == ver {
487 return req.Syntax
488 }
489 }
490 for _, ex := range mf.Exclude {
491 if ex.Mod == ver {
492 return ex.Syntax
493 }
494 }
495 for _, rep := range mf.Replace {
496 if rep.New == ver || rep.Old == ver {
497 return rep.Syntax
498 }
499 }
500 return nil
501 }
502
503 // ResolvedVersion returns the version used for a module, which considers replace directive.
504 func ResolvedVersion(module *packages.Module) string {
505 // don't visit replace recursively as src/cmd/go/internal/modinfo/info.go
506 // visits replace field only once.
507 if module.Replace != nil {
508 return module.Replace.Version
509 }
510 return module.Version
511 }
512
513 // ResolvedPath returns the module path, which considers replace directive.
514 func ResolvedPath(module *packages.Module) string {
515 if module.Replace != nil {
516 return module.Replace.Path
517 }
518 return module.Path
519 }
520
521 // ResolvedString returns a representation of the Version suitable for logging
522 // (Path@Version, or just Path if Version is empty),
523 // which considers replace directive.
524 func ResolvedString(module *packages.Module) string {
525 if ResolvedVersion(module) == "" {
526 ResolvedPath(module)
527 }
528 return ResolvedPath(module) + "@" + ResolvedVersion(module)
529 }