Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201105173854-bc9fc8d8c4bc / 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         "strconv"
16         "strings"
17         "unicode"
18
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"
29 )
30
31 const (
32         SyntaxError = "syntax"
33 )
34
35 type parseModHandle struct {
36         handle *memoize.Handle
37 }
38
39 type parseModData struct {
40         parsed *source.ParsedModule
41
42         // err is any error encountered while parsing the file.
43         err error
44 }
45
46 func (mh *parseModHandle) parse(ctx context.Context, snapshot *snapshot) (*source.ParsedModule, error) {
47         v, err := mh.handle.Get(ctx, snapshot.generation, snapshot)
48         if err != nil {
49                 return nil, err
50         }
51         data := v.(*parseModData)
52         return data.parsed, data.err
53 }
54
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)
58         }
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()))
61                 defer done()
62
63                 contents, err := modFH.Read()
64                 if err != nil {
65                         return &parseModData{err: err}
66                 }
67                 m := &protocol.ColumnMapper{
68                         URI:       modFH.URI(),
69                         Converter: span.NewContentConverter(modFH.URI().Filename(), contents),
70                         Content:   contents,
71                 }
72                 data := &parseModData{
73                         parsed: &source.ParsedModule{
74                                 Mapper: m,
75                         },
76                 }
77                 data.parsed.File, data.err = modfile.Parse(modFH.URI().Filename(), contents, nil)
78                 if data.err != 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}
82                         }
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 {
87                                 data.err = nil
88                         }
89                 }
90                 return data
91         }, nil)
92
93         pmh := &parseModHandle{handle: h}
94         s.mu.Lock()
95         s.parseModHandles[modFH.URI()] = pmh
96         s.mu.Unlock()
97
98         return pmh.parse(ctx, s)
99 }
100
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)
109         if sumFH == nil {
110                 var err error
111                 sumFH, err = s.view.session.cache.getFile(ctx, sumURI)
112                 if err != nil {
113                         return nil
114                 }
115         }
116         content, err := sumFH.Read()
117         if err != nil {
118                 return nil
119         }
120         return content
121 }
122
123 func sumFilename(modURI span.URI) string {
124         return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
125 }
126
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)
134         }
135         line, err := strconv.Atoi(matches[1])
136         if err != nil {
137                 return nil, err
138         }
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)
142         }
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)
147         if err != nil {
148                 return nil, err
149         }
150         eOffset, err := m.Converter.ToOffset(line, endOfLine)
151         if err != nil {
152                 return nil, err
153         }
154         spn := span.New(uri, span.NewPoint(line, 0, sOffset), span.NewPoint(line, endOfLine, eOffset))
155         rng, err := m.Range(spn)
156         if err != nil {
157                 return nil, err
158         }
159         return &source.Error{
160                 Category: SyntaxError,
161                 Message:  matches[2],
162                 Range:    rng,
163                 URI:      uri,
164         }, nil
165 }
166
167 // modKey is uniquely identifies cached data for `go mod why` or dependencies
168 // to upgrade.
169 type modKey struct {
170         sessionID, env, view string
171         mod                  source.FileIdentity
172         verb                 modAction
173 }
174
175 type modAction int
176
177 const (
178         why modAction = iota
179         upgrade
180 )
181
182 type modWhyHandle struct {
183         handle *memoize.Handle
184 }
185
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
190
191         err error
192 }
193
194 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
195         v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
196         if err != nil {
197                 return nil, err
198         }
199         data := v.(*modWhyData)
200         return data.why, data.err
201 }
202
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())
206         }
207         if handle := s.getModWhyHandle(fh.URI()); handle != nil {
208                 return handle.why(ctx, s)
209         }
210         key := modKey{
211                 sessionID: s.view.session.id,
212                 env:       hashEnv(s),
213                 mod:       fh.FileIdentity(),
214                 view:      s.view.rootURI.Filename(),
215                 verb:      why,
216         }
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()))
219                 defer done()
220
221                 snapshot := arg.(*snapshot)
222
223                 pm, err := snapshot.ParseMod(ctx, fh)
224                 if err != nil {
225                         return &modWhyData{err: err}
226                 }
227                 // No requires to explain.
228                 if len(pm.File.Require) == 0 {
229                         return &modWhyData{}
230                 }
231                 // Run `go mod why` on all the dependencies.
232                 inv := &gocommand.Invocation{
233                         Verb:       "mod",
234                         Args:       []string{"why", "-m"},
235                         WorkingDir: filepath.Dir(fh.URI().Filename()),
236                 }
237                 for _, req := range pm.File.Require {
238                         inv.Args = append(inv.Args, req.Mod.Path)
239                 }
240                 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
241                 if err != nil {
242                         return &modWhyData{err: err}
243                 }
244                 whyList := strings.Split(stdout.String(), "\n\n")
245                 if len(whyList) != len(pm.File.Require) {
246                         return &modWhyData{
247                                 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
248                         }
249                 }
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]
253                 }
254                 return &modWhyData{why: why}
255         }, nil)
256
257         mwh := &modWhyHandle{handle: h}
258         s.mu.Lock()
259         s.modWhyHandles[fh.URI()] = mwh
260         s.mu.Unlock()
261
262         return mwh.why(ctx, s)
263 }
264
265 type modUpgradeHandle struct {
266         handle *memoize.Handle
267 }
268
269 type modUpgradeData struct {
270         // upgrades maps modules to their latest versions.
271         upgrades map[string]string
272
273         err error
274 }
275
276 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
277         v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
278         if v == nil {
279                 return nil, err
280         }
281         data := v.(*modUpgradeData)
282         return data.upgrades, data.err
283 }
284
285 // moduleUpgrade describes a module that can be upgraded to a particular
286 // version.
287 type moduleUpgrade struct {
288         Path   string
289         Update struct {
290                 Version string
291         }
292 }
293
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())
297         }
298         if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
299                 return handle.upgrades(ctx, s)
300         }
301         key := modKey{
302                 sessionID: s.view.session.id,
303                 env:       hashEnv(s),
304                 mod:       fh.FileIdentity(),
305                 view:      s.view.rootURI.Filename(),
306                 verb:      upgrade,
307         }
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()))
310                 defer done()
311
312                 snapshot := arg.(*snapshot)
313
314                 pm, err := snapshot.ParseMod(ctx, fh)
315                 if err != nil {
316                         return &modUpgradeData{err: err}
317                 }
318
319                 // No requires to upgrade.
320                 if len(pm.File.Require) == 0 {
321                         return &modUpgradeData{}
322                 }
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{
326                         Verb:       "list",
327                         Args:       []string{"-u", "-m", "-json", "all"},
328                         WorkingDir: filepath.Dir(fh.URI().Filename()),
329                 }
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"
334                 }
335                 stdout, err := snapshot.RunGoCommandDirect(ctx, source.Normal, inv)
336                 if err != nil {
337                         return &modUpgradeData{err: err}
338                 }
339                 var upgradeList []moduleUpgrade
340                 dec := json.NewDecoder(stdout)
341                 for {
342                         var m moduleUpgrade
343                         if err := dec.Decode(&m); err == io.EOF {
344                                 break
345                         } else if err != nil {
346                                 return &modUpgradeData{err: err}
347                         }
348                         upgradeList = append(upgradeList, m)
349                 }
350                 if len(upgradeList) <= 1 {
351                         return &modUpgradeData{}
352                 }
353                 upgrades := make(map[string]string)
354                 for _, upgrade := range upgradeList[1:] {
355                         if upgrade.Update.Version == "" {
356                                 continue
357                         }
358                         upgrades[upgrade.Path] = upgrade.Update.Version
359                 }
360                 return &modUpgradeData{
361                         upgrades: upgrades,
362                 }
363         }, nil)
364         muh := &modUpgradeHandle{handle: h}
365         s.mu.Lock()
366         s.modUpgradeHandles[fh.URI()] = muh
367         s.mu.Unlock()
368
369         return muh.upgrades(ctx, s)
370 }
371
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"))
376         if err != nil {
377                 return false
378         }
379         return f.IsDir()
380 }
381
382 var moduleAtVersionRe = regexp.MustCompile(`^(?P<module>.*)@(?P<version>.*)$`)
383
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:
388         //
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
392         //
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.
396         var v module.Version
397         fields := strings.FieldsFunc(loadErr.Error(), func(r rune) bool {
398                 return unicode.IsSpace(r) || r == ':'
399         })
400         for _, s := range fields {
401                 s = strings.TrimSpace(s)
402                 match := moduleAtVersionRe.FindStringSubmatch(s)
403                 if match == nil || len(match) < 3 {
404                         continue
405                 }
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) {
410                         continue
411                 }
412                 if err := module.Check(path, version); err != nil {
413                         continue
414                 }
415                 v.Path, v.Version = path, version
416                 break
417         }
418         pm, err := snapshot.ParseMod(ctx, fh)
419         if err != nil {
420                 return nil
421         }
422         toSourceError := func(line *modfile.Line) *source.Error {
423                 rng, err := rangeFromPositions(pm.Mapper, line.Start, line.End)
424                 if err != nil {
425                         return nil
426                 }
427                 return &source.Error{
428                         Message: loadErr.Error(),
429                         Range:   rng,
430                         URI:     fh.URI(),
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 }