.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.1.0 / internal / lsp / cache / mod.go
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         "encoding/json"
10         "fmt"
11         "io"
12         "os"
13         "path/filepath"
14         "regexp"
15         "strings"
16         "unicode"
17
18         "golang.org/x/mod/modfile"
19         "golang.org/x/mod/module"
20         "golang.org/x/tools/internal/event"
21         "golang.org/x/tools/internal/gocommand"
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/span"
27 )
28
29 const (
30         SyntaxError    = "syntax"
31         GoCommandError = "go command"
32 )
33
34 type parseModHandle struct {
35         handle *memoize.Handle
36 }
37
38 type parseModData struct {
39         parsed *source.ParsedModule
40
41         // err is any error encountered while parsing the file.
42         err error
43 }
44
45 func (mh *parseModHandle) parse(ctx context.Context, snapshot *snapshot) (*source.ParsedModule, error) {
46         v, err := mh.handle.Get(ctx, snapshot.generation, snapshot)
47         if err != nil {
48                 return nil, err
49         }
50         data := v.(*parseModData)
51         return data.parsed, data.err
52 }
53
54 func (s *snapshot) ParseMod(ctx context.Context, modFH source.FileHandle) (*source.ParsedModule, error) {
55         if handle := s.getParseModHandle(modFH.URI()); handle != nil {
56                 return handle.parse(ctx, s)
57         }
58         h := s.generation.Bind(modFH.FileIdentity(), func(ctx context.Context, _ memoize.Arg) interface{} {
59                 _, done := event.Start(ctx, "cache.ParseModHandle", tag.URI.Of(modFH.URI()))
60                 defer done()
61
62                 contents, err := modFH.Read()
63                 if err != nil {
64                         return &parseModData{err: err}
65                 }
66                 m := &protocol.ColumnMapper{
67                         URI:       modFH.URI(),
68                         Converter: span.NewContentConverter(modFH.URI().Filename(), contents),
69                         Content:   contents,
70                 }
71                 file, err := modfile.Parse(modFH.URI().Filename(), contents, nil)
72
73                 // Attempt to convert the error to a standardized parse error.
74                 var parseErrors []*source.Error
75                 if err != nil {
76                         if parseErr := extractErrorWithPosition(ctx, err.Error(), s); parseErr != nil {
77                                 parseErrors = []*source.Error{parseErr}
78                         }
79                 }
80                 return &parseModData{
81                         parsed: &source.ParsedModule{
82                                 URI:         modFH.URI(),
83                                 Mapper:      m,
84                                 File:        file,
85                                 ParseErrors: parseErrors,
86                         },
87                         err: err,
88                 }
89         }, nil)
90
91         pmh := &parseModHandle{handle: h}
92         s.mu.Lock()
93         s.parseModHandles[modFH.URI()] = pmh
94         s.mu.Unlock()
95
96         return pmh.parse(ctx, s)
97 }
98
99 // goSum reads the go.sum file for the go.mod file at modURI, if it exists. If
100 // it doesn't exist, it returns nil.
101 func (s *snapshot) goSum(ctx context.Context, modURI span.URI) []byte {
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(modURI))
106         var sumFH source.FileHandle = s.FindFile(sumURI)
107         if sumFH == nil {
108                 var err error
109                 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
110                 if err != nil {
111                         return nil
112                 }
113         }
114         content, err := sumFH.Read()
115         if err != nil {
116                 return nil
117         }
118         return content
119 }
120
121 func sumFilename(modURI span.URI) string {
122         return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
123 }
124
125 // modKey is uniquely identifies cached data for `go mod why` or dependencies
126 // to upgrade.
127 type modKey struct {
128         sessionID, env, view string
129         mod                  source.FileIdentity
130         verb                 modAction
131 }
132
133 type modAction int
134
135 const (
136         why modAction = iota
137         upgrade
138 )
139
140 type modWhyHandle struct {
141         handle *memoize.Handle
142 }
143
144 type modWhyData struct {
145         // why keeps track of the `go mod why` results for each require statement
146         // in the go.mod file.
147         why map[string]string
148
149         err error
150 }
151
152 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
153         v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
154         if err != nil {
155                 return nil, err
156         }
157         data := v.(*modWhyData)
158         return data.why, data.err
159 }
160
161 func (s *snapshot) ModWhy(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
162         if fh.Kind() != source.Mod {
163                 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
164         }
165         if handle := s.getModWhyHandle(fh.URI()); handle != nil {
166                 return handle.why(ctx, s)
167         }
168         key := modKey{
169                 sessionID: s.view.session.id,
170                 env:       hashEnv(s),
171                 mod:       fh.FileIdentity(),
172                 view:      s.view.rootURI.Filename(),
173                 verb:      why,
174         }
175         h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
176                 ctx, done := event.Start(ctx, "cache.ModWhyHandle", tag.URI.Of(fh.URI()))
177                 defer done()
178
179                 snapshot := arg.(*snapshot)
180
181                 pm, err := snapshot.ParseMod(ctx, fh)
182                 if err != nil {
183                         return &modWhyData{err: err}
184                 }
185                 // No requires to explain.
186                 if len(pm.File.Require) == 0 {
187                         return &modWhyData{}
188                 }
189                 // Run `go mod why` on all the dependencies.
190                 inv := &gocommand.Invocation{
191                         Verb:       "mod",
192                         Args:       []string{"why", "-m"},
193                         WorkingDir: filepath.Dir(fh.URI().Filename()),
194                 }
195                 for _, req := range pm.File.Require {
196                         inv.Args = append(inv.Args, req.Mod.Path)
197                 }
198                 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
199                 if err != nil {
200                         return &modWhyData{err: err}
201                 }
202                 whyList := strings.Split(stdout.String(), "\n\n")
203                 if len(whyList) != len(pm.File.Require) {
204                         return &modWhyData{
205                                 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
206                         }
207                 }
208                 why := make(map[string]string, len(pm.File.Require))
209                 for i, req := range pm.File.Require {
210                         why[req.Mod.Path] = whyList[i]
211                 }
212                 return &modWhyData{why: why}
213         }, nil)
214
215         mwh := &modWhyHandle{handle: h}
216         s.mu.Lock()
217         s.modWhyHandles[fh.URI()] = mwh
218         s.mu.Unlock()
219
220         return mwh.why(ctx, s)
221 }
222
223 type modUpgradeHandle struct {
224         handle *memoize.Handle
225 }
226
227 type modUpgradeData struct {
228         // upgrades maps modules to their latest versions.
229         upgrades map[string]string
230
231         err error
232 }
233
234 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
235         v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
236         if v == nil {
237                 return nil, err
238         }
239         data := v.(*modUpgradeData)
240         return data.upgrades, data.err
241 }
242
243 // moduleUpgrade describes a module that can be upgraded to a particular
244 // version.
245 type moduleUpgrade struct {
246         Path   string
247         Update struct {
248                 Version string
249         }
250 }
251
252 func (s *snapshot) ModUpgrade(ctx context.Context, fh source.FileHandle) (map[string]string, error) {
253         if fh.Kind() != source.Mod {
254                 return nil, fmt.Errorf("%s is not a go.mod file", fh.URI())
255         }
256         if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
257                 return handle.upgrades(ctx, s)
258         }
259         key := modKey{
260                 sessionID: s.view.session.id,
261                 env:       hashEnv(s),
262                 mod:       fh.FileIdentity(),
263                 view:      s.view.rootURI.Filename(),
264                 verb:      upgrade,
265         }
266         h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
267                 ctx, done := event.Start(ctx, "cache.ModUpgradeHandle", tag.URI.Of(fh.URI()))
268                 defer done()
269
270                 snapshot := arg.(*snapshot)
271
272                 pm, err := snapshot.ParseMod(ctx, fh)
273                 if err != nil {
274                         return &modUpgradeData{err: err}
275                 }
276
277                 // No requires to upgrade.
278                 if len(pm.File.Require) == 0 {
279                         return &modUpgradeData{}
280                 }
281                 // Run "go list -mod readonly -u -m all" to be able to see which deps can be
282                 // upgraded without modifying mod file.
283                 inv := &gocommand.Invocation{
284                         Verb:       "list",
285                         Args:       []string{"-u", "-m", "-json", "all"},
286                         WorkingDir: filepath.Dir(fh.URI().Filename()),
287                 }
288                 if s.workspaceMode()&tempModfile == 0 || containsVendor(fh.URI()) {
289                         // Use -mod=readonly if the module contains a vendor directory
290                         // (see golang/go#38711).
291                         inv.ModFlag = "readonly"
292                 }
293                 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal|source.AllowNetwork, inv)
294                 if err != nil {
295                         return &modUpgradeData{err: err}
296                 }
297                 var upgradeList []moduleUpgrade
298                 dec := json.NewDecoder(stdout)
299                 for {
300                         var m moduleUpgrade
301                         if err := dec.Decode(&m); err == io.EOF {
302                                 break
303                         } else if err != nil {
304                                 return &modUpgradeData{err: err}
305                         }
306                         upgradeList = append(upgradeList, m)
307                 }
308                 if len(upgradeList) <= 1 {
309                         return &modUpgradeData{}
310                 }
311                 upgrades := make(map[string]string)
312                 for _, upgrade := range upgradeList[1:] {
313                         if upgrade.Update.Version == "" {
314                                 continue
315                         }
316                         upgrades[upgrade.Path] = upgrade.Update.Version
317                 }
318                 return &modUpgradeData{
319                         upgrades: upgrades,
320                 }
321         }, nil)
322         muh := &modUpgradeHandle{handle: h}
323         s.mu.Lock()
324         s.modUpgradeHandles[fh.URI()] = muh
325         s.mu.Unlock()
326
327         return muh.upgrades(ctx, s)
328 }
329
330 // containsVendor reports whether the module has a vendor folder.
331 func containsVendor(modURI span.URI) bool {
332         dir := filepath.Dir(modURI.Filename())
333         f, err := os.Stat(filepath.Join(dir, "vendor"))
334         if err != nil {
335                 return false
336         }
337         return f.IsDir()
338 }
339
340 var moduleAtVersionRe = regexp.MustCompile(`^(?P<module>.*)@(?P<version>.*)$`)
341
342 // extractGoCommandError tries to parse errors that come from the go command
343 // and shape them into go.mod diagnostics.
344 func (s *snapshot) extractGoCommandErrors(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, goCmdError string) []*source.Error {
345         var srcErrs []*source.Error
346         if srcErr := s.parseModError(ctx, fh, goCmdError); srcErr != nil {
347                 srcErrs = append(srcErrs, srcErr)
348         }
349         // If the error message contains a position, use that. Don't pass a file
350         // handle in, as it might not be the file associated with the error.
351         if srcErr := extractErrorWithPosition(ctx, goCmdError, s); srcErr != nil {
352                 srcErrs = append(srcErrs, srcErr)
353         } else if srcErr := s.matchErrorToModule(ctx, fh, goCmdError); srcErr != nil {
354                 srcErrs = append(srcErrs, srcErr)
355         }
356         return srcErrs
357 }
358
359 // matchErrorToModule attempts to match module version in error messages.
360 // Some examples:
361 //
362 //    example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
363 //    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
364 //    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
365 //
366 // We split on colons and whitespace, and attempt to match on something
367 // that matches module@version. If we're able to find a match, we try to
368 // find anything that matches it in the go.mod file.
369 func (s *snapshot) matchErrorToModule(ctx context.Context, fh source.FileHandle, goCmdError string) *source.Error {
370         var v module.Version
371         fields := strings.FieldsFunc(goCmdError, func(r rune) bool {
372                 return unicode.IsSpace(r) || r == ':'
373         })
374         for _, field := range fields {
375                 match := moduleAtVersionRe.FindStringSubmatch(field)
376                 if match == nil {
377                         continue
378                 }
379                 path, version := match[1], match[2]
380                 // Any module versions that come from the workspace module should not
381                 // be shown to the user.
382                 if source.IsWorkspaceModuleVersion(version) {
383                         continue
384                 }
385                 if err := module.Check(path, version); err != nil {
386                         continue
387                 }
388                 v.Path, v.Version = path, version
389                 break
390         }
391         pm, err := s.ParseMod(ctx, fh)
392         if err != nil {
393                 return nil
394         }
395         toSourceError := func(line *modfile.Line) *source.Error {
396                 rng, err := rangeFromPositions(pm.Mapper, line.Start, line.End)
397                 if err != nil {
398                         return nil
399                 }
400                 disabledByGOPROXY := strings.Contains(goCmdError, "disabled by GOPROXY=off")
401                 shouldAddDep := strings.Contains(goCmdError, "to add it")
402                 if v.Path != "" && (disabledByGOPROXY || shouldAddDep) {
403                         args, err := source.MarshalArgs(fh.URI(), false, []string{fmt.Sprintf("%v@%v", v.Path, v.Version)})
404                         if err != nil {
405                                 return nil
406                         }
407                         msg := goCmdError
408                         if disabledByGOPROXY {
409                                 msg = fmt.Sprintf("%v@%v has not been downloaded", v.Path, v.Version)
410                         }
411                         return &source.Error{
412                                 Message: msg,
413                                 Kind:    source.ListError,
414                                 Range:   rng,
415                                 URI:     fh.URI(),
416                                 SuggestedFixes: []source.SuggestedFix{{
417                                         Title: fmt.Sprintf("Download %v@%v", v.Path, v.Version),
418                                         Command: &protocol.Command{
419                                                 Title:     source.CommandAddDependency.Title,
420                                                 Command:   source.CommandAddDependency.ID(),
421                                                 Arguments: args,
422                                         },
423                                 }},
424                         }
425                 }
426                 return &source.Error{
427                         Message: goCmdError,
428                         Range:   rng,
429                         URI:     fh.URI(),
430                         Kind:    source.ListError,
431                 }
432         }
433         // Check if there are any require, exclude, or replace statements that
434         // match this module version.
435         for _, req := range pm.File.Require {
436                 if req.Mod != v {
437                         continue
438                 }
439                 return toSourceError(req.Syntax)
440         }
441         for _, ex := range pm.File.Exclude {
442                 if ex.Mod != v {
443                         continue
444                 }
445                 return toSourceError(ex.Syntax)
446         }
447         for _, rep := range pm.File.Replace {
448                 if rep.New != v && rep.Old != v {
449                         continue
450                 }
451                 return toSourceError(rep.Syntax)
452         }
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 {
456                 return nil
457         }
458         return toSourceError(pm.File.Module.Syntax)
459 }
460
461 // errorPositionRe matches errors messages of the form <filename>:<line>:<col>,
462 // where the <col> is optional.
463 var errorPositionRe = regexp.MustCompile(`(?P<pos>.*:([\d]+)(:([\d]+))?): (?P<msg>.+)`)
464
465 // extractErrorWithPosition returns a structured error with position
466 // information for the given unstructured error. If a file handle is provided,
467 // the error position will be on that file. This is useful for parse errors,
468 // where we already know the file with the error.
469 func extractErrorWithPosition(ctx context.Context, goCmdError string, src source.FileSource) *source.Error {
470         matches := errorPositionRe.FindStringSubmatch(strings.TrimSpace(goCmdError))
471         if len(matches) == 0 {
472                 return nil
473         }
474         var pos, msg string
475         for i, name := range errorPositionRe.SubexpNames() {
476                 if name == "pos" {
477                         pos = matches[i]
478                 }
479                 if name == "msg" {
480                         msg = matches[i]
481                 }
482         }
483         spn := span.Parse(pos)
484         fh, err := src.GetFile(ctx, spn.URI())
485         if err != nil {
486                 return nil
487         }
488         content, err := fh.Read()
489         if err != nil {
490                 return nil
491         }
492         m := &protocol.ColumnMapper{
493                 URI:       spn.URI(),
494                 Converter: span.NewContentConverter(spn.URI().Filename(), content),
495                 Content:   content,
496         }
497         rng, err := m.Range(spn)
498         if err != nil {
499                 return nil
500         }
501         category := GoCommandError
502         if fh != nil {
503                 category = SyntaxError
504         }
505         return &source.Error{
506                 Category: category,
507                 Message:  msg,
508                 Range:    rng,
509                 URI:      spn.URI(),
510         }
511 }