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.
14 "golang.org/x/mod/modfile"
15 "golang.org/x/mod/module"
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/gocommand"
18 "golang.org/x/tools/internal/lsp/command"
19 "golang.org/x/tools/internal/lsp/debug/tag"
20 "golang.org/x/tools/internal/lsp/protocol"
21 "golang.org/x/tools/internal/lsp/source"
22 "golang.org/x/tools/internal/memoize"
23 "golang.org/x/tools/internal/span"
26 type parseModHandle struct {
27 handle *memoize.Handle
30 type parseModData struct {
31 parsed *source.ParsedModule
33 // err is any error encountered while parsing the file.
37 func (mh *parseModHandle) parse(ctx context.Context, snapshot *snapshot) (*source.ParsedModule, error) {
38 v, err := mh.handle.Get(ctx, snapshot.generation, snapshot)
42 data := v.(*parseModData)
43 return data.parsed, data.err
46 func (s *snapshot) ParseMod(ctx context.Context, modFH source.FileHandle) (*source.ParsedModule, error) {
47 if handle := s.getParseModHandle(modFH.URI()); handle != nil {
48 return handle.parse(ctx, s)
50 h := s.generation.Bind(modFH.FileIdentity(), func(ctx context.Context, _ memoize.Arg) interface{} {
51 _, done := event.Start(ctx, "cache.ParseModHandle", tag.URI.Of(modFH.URI()))
54 contents, err := modFH.Read()
56 return &parseModData{err: err}
58 m := &protocol.ColumnMapper{
60 Converter: span.NewContentConverter(modFH.URI().Filename(), contents),
63 file, parseErr := modfile.Parse(modFH.URI().Filename(), contents, nil)
64 // Attempt to convert the error to a standardized parse error.
65 var parseErrors []*source.Diagnostic
67 mfErrList, ok := parseErr.(modfile.ErrorList)
69 return &parseModData{err: fmt.Errorf("unexpected parse error type %v", parseErr)}
71 for _, mfErr := range mfErrList {
72 rng, err := rangeFromPositions(m, mfErr.Pos, mfErr.Pos)
74 return &parseModData{err: err}
76 parseErrors = []*source.Diagnostic{{
79 Severity: protocol.SeverityError,
80 Source: source.ParseError,
81 Message: mfErr.Err.Error(),
86 parsed: &source.ParsedModule{
90 ParseErrors: parseErrors,
96 pmh := &parseModHandle{handle: h}
98 s.parseModHandles[modFH.URI()] = pmh
101 return pmh.parse(ctx, s)
104 // goSum reads the go.sum file for the go.mod file at modURI, if it exists. If
105 // it doesn't exist, it returns nil.
106 func (s *snapshot) goSum(ctx context.Context, modURI span.URI) []byte {
107 // Get the go.sum file, either from the snapshot or directly from the
108 // cache. Avoid (*snapshot).GetFile here, as we don't want to add
109 // nonexistent file handles to the snapshot if the file does not exist.
110 sumURI := span.URIFromPath(sumFilename(modURI))
111 var sumFH source.FileHandle = s.FindFile(sumURI)
114 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
119 content, err := sumFH.Read()
126 func sumFilename(modURI span.URI) string {
127 return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
130 // modKey is uniquely identifies cached data for `go mod why` or dependencies
133 sessionID, env, view string
134 mod source.FileIdentity
145 type modWhyHandle struct {
146 handle *memoize.Handle
149 type modWhyData struct {
150 // why keeps track of the `go mod why` results for each require statement
151 // in the go.mod file.
152 why map[string]string
157 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
158 v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
162 data := v.(*modWhyData)
163 return data.why, data.err
166 func (s *snapshot) ModWhy(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
167 if fh.Kind() != source.Mod {
168 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
170 if handle := s.getModWhyHandle(fh.URI()); handle != nil {
171 return handle.why(ctx, s)
174 sessionID: s.view.session.id,
176 mod: fh.FileIdentity(),
177 view: s.view.rootURI.Filename(),
180 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
181 ctx, done := event.Start(ctx, "cache.ModWhyHandle", tag.URI.Of(fh.URI()))
184 snapshot := arg.(*snapshot)
186 pm, err := snapshot.ParseMod(ctx, fh)
188 return &modWhyData{err: err}
190 // No requires to explain.
191 if len(pm.File.Require) == 0 {
194 // Run `go mod why` on all the dependencies.
195 inv := &gocommand.Invocation{
197 Args: []string{"why", "-m"},
198 WorkingDir: filepath.Dir(fh.URI().Filename()),
200 for _, req := range pm.File.Require {
201 inv.Args = append(inv.Args, req.Mod.Path)
203 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
205 return &modWhyData{err: err}
207 whyList := strings.Split(stdout.String(), "\n\n")
208 if len(whyList) != len(pm.File.Require) {
210 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
213 why := make(map[string]string, len(pm.File.Require))
214 for i, req := range pm.File.Require {
215 why[req.Mod.Path] = whyList[i]
217 return &modWhyData{why: why}
220 mwh := &modWhyHandle{handle: h}
222 s.modWhyHandles[fh.URI()] = mwh
225 return mwh.why(ctx, s)
228 // extractGoCommandError tries to parse errors that come from the go command
229 // and shape them into go.mod diagnostics.
230 func (s *snapshot) extractGoCommandErrors(ctx context.Context, goCmdError string) ([]*source.Diagnostic, error) {
231 diagLocations := map[*source.ParsedModule]span.Span{}
232 backupDiagLocations := map[*source.ParsedModule]span.Span{}
234 // The go command emits parse errors for completely invalid go.mod files.
235 // Those are reported by our own diagnostics and can be ignored here.
236 // As of writing, we are not aware of any other errors that include
237 // file/position information, so don't even try to find it.
238 if strings.Contains(goCmdError, "errors parsing go.mod") {
242 // Match the error against all the mod files in the workspace.
243 for _, uri := range s.ModFiles() {
244 fh, err := s.GetFile(ctx, uri)
248 pm, err := s.ParseMod(ctx, fh)
252 spn, found, err := s.matchErrorToModule(ctx, pm, goCmdError)
257 diagLocations[pm] = spn
259 backupDiagLocations[pm] = spn
263 // If we didn't find any good matches, assign diagnostics to all go.mod files.
264 if len(diagLocations) == 0 {
265 diagLocations = backupDiagLocations
268 var srcErrs []*source.Diagnostic
269 for pm, spn := range diagLocations {
270 diag, err := s.goCommandDiagnostic(pm, spn, goCmdError)
274 srcErrs = append(srcErrs, diag)
279 var moduleVersionInErrorRe = regexp.MustCompile(`[:\s]([+-._~0-9A-Za-z]+)@([+-._~0-9A-Za-z]+)[:\s]`)
281 // matchErrorToModule matches a go command error message to a go.mod file.
284 // example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
285 // go: github.com/cockroachdb/apd/v2@v2.0.72: reading github.com/cockroachdb/apd/go.mod at revision v2.0.72: unknown revision v2.0.72
286 // go: example.com@v1.2.3 requires\n\trandom.org@v1.2.3: parsing go.mod:\n\tmodule declares its path as: bob.org\n\tbut was required as: random.org
288 // It returns the location of a reference to the one of the modules and true
289 // if one exists. If none is found it returns a fallback location and false.
290 func (s *snapshot) matchErrorToModule(ctx context.Context, pm *source.ParsedModule, goCmdError string) (span.Span, bool, error) {
291 var reference *modfile.Line
292 matches := moduleVersionInErrorRe.FindAllStringSubmatch(goCmdError, -1)
294 for i := len(matches) - 1; i >= 0; i-- {
295 ver := module.Version{Path: matches[i][1], Version: matches[i][2]}
296 // Any module versions that come from the workspace module should not
297 // be shown to the user.
298 if source.IsWorkspaceModuleVersion(ver.Version) {
301 if err := module.Check(ver.Path, ver.Version); err != nil {
304 reference = findModuleReference(pm.File, ver)
305 if reference != nil {
310 if reference == nil {
311 // No match for the module path was found in the go.mod file.
312 // Show the error on the module declaration, if one exists, or
313 // just the first line of the file.
314 if pm.File.Module == nil {
315 return span.New(pm.URI, span.NewPoint(1, 1, 0), span.Point{}), false, nil
317 spn, err := spanFromPositions(pm.Mapper, pm.File.Module.Syntax.Start, pm.File.Module.Syntax.End)
318 return spn, false, err
321 spn, err := spanFromPositions(pm.Mapper, reference.Start, reference.End)
322 return spn, true, err
325 // goCommandDiagnostic creates a diagnostic for a given go command error.
326 func (s *snapshot) goCommandDiagnostic(pm *source.ParsedModule, spn span.Span, goCmdError string) (*source.Diagnostic, error) {
327 rng, err := pm.Mapper.Range(spn)
332 matches := moduleVersionInErrorRe.FindAllStringSubmatch(goCmdError, -1)
333 var innermost *module.Version
334 for i := len(matches) - 1; i >= 0; i-- {
335 ver := module.Version{Path: matches[i][1], Version: matches[i][2]}
336 // Any module versions that come from the workspace module should not
337 // be shown to the user.
338 if source.IsWorkspaceModuleVersion(ver.Version) {
341 if err := module.Check(ver.Path, ver.Version); err != nil {
349 case strings.Contains(goCmdError, "inconsistent vendoring"):
350 cmd, err := command.NewVendorCommand("Run go mod vendor", command.URIArg{URI: protocol.URIFromSpanURI(pm.URI)})
354 return &source.Diagnostic{
357 Severity: protocol.SeverityError,
358 Source: source.ListError,
359 Message: `Inconsistent vendoring detected. Please re-run "go mod vendor".
360 See https://github.com/golang/go/issues/39164 for more detail on this issue.`,
361 SuggestedFixes: []source.SuggestedFix{source.SuggestedFixFromCommand(cmd)},
364 case strings.Contains(goCmdError, "updates to go.sum needed"), strings.Contains(goCmdError, "missing go.sum entry"):
365 var args []protocol.DocumentURI
366 for _, uri := range s.ModFiles() {
367 args = append(args, protocol.URIFromSpanURI(uri))
369 tidyCmd, err := command.NewTidyCommand("Run go mod tidy", command.URIArgs{URIs: args})
373 updateCmd, err := command.NewUpdateGoSumCommand("Update go.sum", command.URIArgs{URIs: args})
377 msg := "go.sum is out of sync with go.mod. Please update it by applying the quick fix."
378 if innermost != nil {
379 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)
381 return &source.Diagnostic{
384 Severity: protocol.SeverityError,
385 Source: source.ListError,
387 SuggestedFixes: []source.SuggestedFix{
388 source.SuggestedFixFromCommand(tidyCmd),
389 source.SuggestedFixFromCommand(updateCmd),
392 case strings.Contains(goCmdError, "disabled by GOPROXY=off") && innermost != nil:
393 title := fmt.Sprintf("Download %v@%v", innermost.Path, innermost.Version)
394 cmd, err := command.NewAddDependencyCommand(title, command.DependencyArgs{
395 URI: protocol.URIFromSpanURI(pm.URI),
397 GoCmdArgs: []string{fmt.Sprintf("%v@%v", innermost.Path, innermost.Version)},
402 return &source.Diagnostic{
405 Severity: protocol.SeverityError,
406 Message: fmt.Sprintf("%v@%v has not been downloaded", innermost.Path, innermost.Version),
407 Source: source.ListError,
408 SuggestedFixes: []source.SuggestedFix{source.SuggestedFixFromCommand(cmd)},
411 return &source.Diagnostic{
414 Severity: protocol.SeverityError,
415 Source: source.ListError,
421 func findModuleReference(mf *modfile.File, ver module.Version) *modfile.Line {
422 for _, req := range mf.Require {
427 for _, ex := range mf.Exclude {
432 for _, rep := range mf.Replace {
433 if rep.New == ver || rep.Old == ver {