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/gocommand"
23 "golang.org/x/tools/internal/lsp/debug/tag"
24 "golang.org/x/tools/internal/lsp/protocol"
25 "golang.org/x/tools/internal/lsp/source"
26 "golang.org/x/tools/internal/memoize"
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 // goSum reads the go.sum file for the go.mod file at modURI, if it exists. If
102 // it doesn't exist, it returns nil.
103 func (s *snapshot) goSum(ctx context.Context, modURI span.URI) []byte {
104 // Get the go.sum file, either from the snapshot or directly from the
105 // cache. Avoid (*snapshot).GetFile here, as we don't want to add
106 // nonexistent file handles to the snapshot if the file does not exist.
107 sumURI := span.URIFromPath(sumFilename(modURI))
108 var sumFH source.FileHandle = s.FindFile(sumURI)
111 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
116 content, err := sumFH.Read()
123 func sumFilename(modURI span.URI) string {
124 return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
127 // extractModParseErrors processes the raw errors returned by modfile.Parse,
128 // extracting the filenames and line numbers that correspond to the errors.
129 func extractModParseErrors(uri span.URI, m *protocol.ColumnMapper, parseErr error, content []byte) (*source.Error, error) {
130 re := regexp.MustCompile(`.*:([\d]+): (.+)`)
131 matches := re.FindStringSubmatch(strings.TrimSpace(parseErr.Error()))
132 if len(matches) < 3 {
133 return nil, errors.Errorf("could not parse go.mod error message: %s", parseErr)
135 line, err := strconv.Atoi(matches[1])
139 lines := strings.Split(string(content), "\n")
140 if line > len(lines) {
141 return nil, errors.Errorf("could not parse go.mod error message %q, line number %v out of range", content, line)
143 // The error returned from the modfile package only returns a line number,
144 // so we assume that the diagnostic should be for the entire line.
145 endOfLine := len(lines[line-1])
146 sOffset, err := m.Converter.ToOffset(line, 0)
150 eOffset, err := m.Converter.ToOffset(line, endOfLine)
154 spn := span.New(uri, span.NewPoint(line, 0, sOffset), span.NewPoint(line, endOfLine, eOffset))
155 rng, err := m.Range(spn)
159 return &source.Error{
160 Category: SyntaxError,
167 // modKey is uniquely identifies cached data for `go mod why` or dependencies
170 sessionID, env, view string
171 mod source.FileIdentity
182 type modWhyHandle struct {
183 handle *memoize.Handle
186 type modWhyData struct {
187 // why keeps track of the `go mod why` results for each require statement
188 // in the go.mod file.
189 why map[string]string
194 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
195 v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
199 data := v.(*modWhyData)
200 return data.why, data.err
203 func (s *snapshot) ModWhy(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
204 if fh.Kind() != source.Mod {
205 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
207 if handle := s.getModWhyHandle(fh.URI()); handle != nil {
208 return handle.why(ctx, s)
211 sessionID: s.view.session.id,
213 mod: fh.FileIdentity(),
214 view: s.view.rootURI.Filename(),
217 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
218 ctx, done := event.Start(ctx, "cache.ModWhyHandle", tag.URI.Of(fh.URI()))
221 snapshot := arg.(*snapshot)
223 pm, err := snapshot.ParseMod(ctx, fh)
225 return &modWhyData{err: err}
227 // No requires to explain.
228 if len(pm.File.Require) == 0 {
231 // Run `go mod why` on all the dependencies.
232 inv := &gocommand.Invocation{
234 Args: []string{"why", "-m"},
235 WorkingDir: filepath.Dir(fh.URI().Filename()),
237 for _, req := range pm.File.Require {
238 inv.Args = append(inv.Args, req.Mod.Path)
240 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
242 return &modWhyData{err: err}
244 whyList := strings.Split(stdout.String(), "\n\n")
245 if len(whyList) != len(pm.File.Require) {
247 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
250 why := make(map[string]string, len(pm.File.Require))
251 for i, req := range pm.File.Require {
252 why[req.Mod.Path] = whyList[i]
254 return &modWhyData{why: why}
257 mwh := &modWhyHandle{handle: h}
259 s.modWhyHandles[fh.URI()] = mwh
262 return mwh.why(ctx, s)
265 type modUpgradeHandle struct {
266 handle *memoize.Handle
269 type modUpgradeData struct {
270 // upgrades maps modules to their latest versions.
271 upgrades map[string]string
276 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
277 v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
281 data := v.(*modUpgradeData)
282 return data.upgrades, data.err
285 // moduleUpgrade describes a module that can be upgraded to a particular
287 type moduleUpgrade struct {
294 func (s *snapshot) ModUpgrade(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
295 if fh.Kind() != source.Mod {
296 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
298 if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
299 return handle.upgrades(ctx, s)
302 sessionID: s.view.session.id,
304 mod: fh.FileIdentity(),
305 view: s.view.rootURI.Filename(),
308 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
309 ctx, done := event.Start(ctx, "cache.ModUpgradeHandle", tag.URI.Of(fh.URI()))
312 snapshot := arg.(*snapshot)
314 pm, err := snapshot.ParseMod(ctx, fh)
316 return &modUpgradeData{err: err}
319 // No requires to upgrade.
320 if len(pm.File.Require) == 0 {
321 return &modUpgradeData{}
323 // Run "go list -mod readonly -u -m all" to be able to see which deps can be
324 // upgraded without modifying mod file.
325 inv := &gocommand.Invocation{
327 Args: []string{"-u", "-m", "-json", "all"},
328 WorkingDir: filepath.Dir(fh.URI().Filename()),
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 inv.ModFlag = "readonly"
335 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
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)