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.
19 "golang.org/x/mod/modfile"
20 "golang.org/x/mod/module"
21 "golang.org/x/tools/internal/event"
22 "golang.org/x/tools/internal/lsp/debug/tag"
23 "golang.org/x/tools/internal/lsp/protocol"
24 "golang.org/x/tools/internal/lsp/source"
25 "golang.org/x/tools/internal/memoize"
26 "golang.org/x/tools/internal/packagesinternal"
27 "golang.org/x/tools/internal/span"
28 errors "golang.org/x/xerrors"
32 SyntaxError = "syntax"
35 type parseModHandle struct {
36 handle *memoize.Handle
39 type parseModData struct {
40 parsed *source.ParsedModule
42 // err is any error encountered while parsing the file.
46 func (mh *parseModHandle) parse(ctx context.Context, snapshot *snapshot) (*source.ParsedModule, error) {
47 v, err := mh.handle.Get(ctx, snapshot.generation, snapshot)
51 data := v.(*parseModData)
52 return data.parsed, data.err
55 func (s *snapshot) ParseMod(ctx context.Context, modFH source.FileHandle) (*source.ParsedModule, error) {
56 if handle := s.getParseModHandle(modFH.URI()); handle != nil {
57 return handle.parse(ctx, s)
59 h := s.generation.Bind(modFH.FileIdentity(), func(ctx context.Context, _ memoize.Arg) interface{} {
60 _, done := event.Start(ctx, "cache.ParseModHandle", tag.URI.Of(modFH.URI()))
63 contents, err := modFH.Read()
65 return &parseModData{err: err}
67 m := &protocol.ColumnMapper{
69 Converter: span.NewContentConverter(modFH.URI().Filename(), contents),
72 data := &parseModData{
73 parsed: &source.ParsedModule{
77 data.parsed.File, data.err = modfile.Parse(modFH.URI().Filename(), contents, nil)
79 // Attempt to convert the error to a standardized parse error.
80 if parseErr, extractErr := extractModParseErrors(modFH.URI(), m, data.err, contents); extractErr == nil {
81 data.parsed.ParseErrors = []source.Error{*parseErr}
83 // If the file was still parsed, we don't want to treat this as a
84 // fatal error. Note: This currently cannot happen as modfile.Parse
85 // always returns an error when the file is nil.
86 if data.parsed.File != nil {
93 pmh := &parseModHandle{handle: h}
95 s.parseModHandles[modFH.URI()] = pmh
98 return pmh.parse(ctx, s)
101 func (s *snapshot) sumFH(ctx context.Context, modFH source.FileHandle) (source.FileHandle, error) {
102 // Get the go.sum file, either from the snapshot or directly from the
103 // cache. Avoid (*snapshot).GetFile here, as we don't want to add
104 // nonexistent file handles to the snapshot if the file does not exist.
105 sumURI := span.URIFromPath(sumFilename(modFH.URI()))
106 var sumFH source.FileHandle = s.FindFile(sumURI)
109 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
114 _, err := sumFH.Read()
121 func sumFilename(modURI span.URI) string {
122 return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
125 // extractModParseErrors processes the raw errors returned by modfile.Parse,
126 // extracting the filenames and line numbers that correspond to the errors.
127 func extractModParseErrors(uri span.URI, m *protocol.ColumnMapper, parseErr error, content []byte) (*source.Error, error) {
128 re := regexp.MustCompile(`.*:([\d]+): (.+)`)
129 matches := re.FindStringSubmatch(strings.TrimSpace(parseErr.Error()))
130 if len(matches) < 3 {
131 return nil, errors.Errorf("could not parse go.mod error message: %s", parseErr)
133 line, err := strconv.Atoi(matches[1])
137 lines := strings.Split(string(content), "\n")
138 if line > len(lines) {
139 return nil, errors.Errorf("could not parse go.mod error message %q, line number %v out of range", content, line)
141 // The error returned from the modfile package only returns a line number,
142 // so we assume that the diagnostic should be for the entire line.
143 endOfLine := len(lines[line-1])
144 sOffset, err := m.Converter.ToOffset(line, 0)
148 eOffset, err := m.Converter.ToOffset(line, endOfLine)
152 spn := span.New(uri, span.NewPoint(line, 0, sOffset), span.NewPoint(line, endOfLine, eOffset))
153 rng, err := m.Range(spn)
157 return &source.Error{
158 Category: SyntaxError,
165 // modKey is uniquely identifies cached data for `go mod why` or dependencies
168 sessionID, cfg, view string
169 mod source.FileIdentity
180 type modWhyHandle struct {
181 handle *memoize.Handle
184 type modWhyData struct {
185 // why keeps track of the `go mod why` results for each require statement
186 // in the go.mod file.
187 why map[string]string
192 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
193 v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
197 data := v.(*modWhyData)
198 return data.why, data.err
201 func (s *snapshot) ModWhy(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
202 if fh.Kind() != source.Mod {
203 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
205 if err := s.awaitLoaded(ctx); err != nil {
208 if handle := s.getModWhyHandle(fh.URI()); handle != nil {
209 return handle.why(ctx, s)
211 // Make sure to use the module root as the working directory.
212 cfg := s.config(ctx, filepath.Dir(fh.URI().Filename()))
214 sessionID: s.view.session.id,
215 cfg: hashConfig(cfg),
216 mod: fh.FileIdentity(),
217 view: s.view.rootURI.Filename(),
220 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
221 ctx, done := event.Start(ctx, "cache.ModWhyHandle", tag.URI.Of(fh.URI()))
224 snapshot := arg.(*snapshot)
226 pm, err := snapshot.ParseMod(ctx, fh)
228 return &modWhyData{err: err}
230 // No requires to explain.
231 if len(pm.File.Require) == 0 {
234 // Run `go mod why` on all the dependencies.
235 args := []string{"why", "-m"}
236 for _, req := range pm.File.Require {
237 args = append(args, req.Mod.Path)
239 stdout, err := snapshot.runGoCommandWithConfig(ctx, cfg, "mod", args)
241 return &modWhyData{err: err}
243 whyList := strings.Split(stdout.String(), "\n\n")
244 if len(whyList) != len(pm.File.Require) {
246 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
249 why := make(map[string]string, len(pm.File.Require))
250 for i, req := range pm.File.Require {
251 why[req.Mod.Path] = whyList[i]
253 return &modWhyData{why: why}
256 mwh := &modWhyHandle{handle: h}
258 s.modWhyHandles[fh.URI()] = mwh
261 return mwh.why(ctx, s)
264 type modUpgradeHandle struct {
265 handle *memoize.Handle
268 type modUpgradeData struct {
269 // upgrades maps modules to their latest versions.
270 upgrades map[string]string
275 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
276 v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
280 data := v.(*modUpgradeData)
281 return data.upgrades, data.err
284 // moduleUpgrade describes a module that can be upgraded to a particular
286 type moduleUpgrade struct {
293 func (s *snapshot) ModUpgrade(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
294 if fh.Kind() != source.Mod {
295 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
297 if err := s.awaitLoaded(ctx); err != nil {
300 if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
301 return handle.upgrades(ctx, s)
303 // Use the module root as the working directory.
304 cfg := s.config(ctx, filepath.Dir(fh.URI().Filename()))
306 sessionID: s.view.session.id,
307 cfg: hashConfig(cfg),
308 mod: fh.FileIdentity(),
309 view: s.view.rootURI.Filename(),
312 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
313 ctx, done := event.Start(ctx, "cache.ModUpgradeHandle", tag.URI.Of(fh.URI()))
316 snapshot := arg.(*snapshot)
318 pm, err := snapshot.ParseMod(ctx, fh)
320 return &modUpgradeData{err: err}
323 // No requires to upgrade.
324 if len(pm.File.Require) == 0 {
325 return &modUpgradeData{}
327 // Run "go list -mod readonly -u -m all" to be able to see which deps can be
328 // upgraded without modifying mod file.
329 args := []string{"-u", "-m", "-json", "all"}
330 if s.workspaceMode()&tempModfile == 0 || containsVendor(fh.URI()) {
331 // Use -mod=readonly if the module contains a vendor directory
332 // (see golang/go#38711).
333 packagesinternal.SetModFlag(cfg, "readonly")
335 stdout, err := snapshot.runGoCommandWithConfig(ctx, cfg, "list", args)
337 return &modUpgradeData{err: err}
339 var upgradeList []moduleUpgrade
340 dec := json.NewDecoder(stdout)
343 if err := dec.Decode(&m); err == io.EOF {
345 } else if err != nil {
346 return &modUpgradeData{err: err}
348 upgradeList = append(upgradeList, m)
350 if len(upgradeList) <= 1 {
351 return &modUpgradeData{}
353 upgrades := make(map[string]string)
354 for _, upgrade := range upgradeList[1:] {
355 if upgrade.Update.Version == "" {
358 upgrades[upgrade.Path] = upgrade.Update.Version
360 return &modUpgradeData{
364 muh := &modUpgradeHandle{handle: h}
366 s.modUpgradeHandles[fh.URI()] = muh
369 return muh.upgrades(ctx, s)
372 // containsVendor reports whether the module has a vendor folder.
373 func containsVendor(modURI span.URI) bool {
374 dir := filepath.Dir(modURI.Filename())
375 f, err := os.Stat(filepath.Join(dir, "vendor"))
382 var moduleAtVersionRe = regexp.MustCompile(`^(?P<module>.*)@(?P<version>.*)$`)
384 // ExtractGoCommandError tries to parse errors that come from the go command
385 // and shape them into go.mod diagnostics.
386 func extractGoCommandError(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, loadErr error) *source.Error {
387 // We try to match module versions in error messages. Some examples:
389 // example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
390 // 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
391 // 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
393 // We split on colons and whitespace, and attempt to match on something
394 // that matches module@version. If we're able to find a match, we try to
395 // find anything that matches it in the go.mod file.
397 fields := strings.FieldsFunc(loadErr.Error(), func(r rune) bool {
398 return unicode.IsSpace(r) || r == ':'
400 for _, s := range fields {
401 s = strings.TrimSpace(s)
402 match := moduleAtVersionRe.FindStringSubmatch(s)
403 if match == nil || len(match) < 3 {
406 path, version := match[1], match[2]
407 // Any module versions that come from the workspace module should not
408 // be shown to the user.
409 if source.IsWorkspaceModuleVersion(version) {
412 if err := module.Check(path, version); err != nil {
415 v.Path, v.Version = path, version
418 pm, err := snapshot.ParseMod(ctx, fh)
422 toSourceError := func(line *modfile.Line) *source.Error {
423 rng, err := rangeFromPositions(pm.Mapper, line.Start, line.End)
427 return &source.Error{
428 Message: loadErr.Error(),
433 // Check if there are any require, exclude, or replace statements that
434 // match this module version.
435 for _, req := range pm.File.Require {
439 return toSourceError(req.Syntax)
441 for _, ex := range pm.File.Exclude {
445 return toSourceError(ex.Syntax)
447 for _, rep := range pm.File.Replace {
448 if rep.New != v && rep.Old != v {
451 return toSourceError(rep.Syntax)
453 // No match for the module path was found in the go.mod file.
454 // Show the error on the module declaration, if one exists.
455 if pm.File.Module == nil {
458 return toSourceError(pm.File.Module.Syntax)