Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / 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/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"
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         })
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 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)
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, err
112                 }
113         }
114         _, err := sumFH.Read()
115         if err != nil {
116                 return nil, err
117         }
118         return sumFH, nil
119 }
120
121 func sumFilename(modURI span.URI) string {
122         return strings.TrimSuffix(modURI.Filename(), ".mod") + ".sum"
123 }
124
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)
132         }
133         line, err := strconv.Atoi(matches[1])
134         if err != nil {
135                 return nil, err
136         }
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)
140         }
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)
145         if err != nil {
146                 return nil, err
147         }
148         eOffset, err := m.Converter.ToOffset(line, endOfLine)
149         if err != nil {
150                 return nil, err
151         }
152         spn := span.New(uri, span.NewPoint(line, 0, sOffset), span.NewPoint(line, endOfLine, eOffset))
153         rng, err := m.Range(spn)
154         if err != nil {
155                 return nil, err
156         }
157         return &source.Error{
158                 Category: SyntaxError,
159                 Message:  matches[2],
160                 Range:    rng,
161                 URI:      uri,
162         }, nil
163 }
164
165 // modKey is uniquely identifies cached data for `go mod why` or dependencies
166 // to upgrade.
167 type modKey struct {
168         sessionID, cfg, view string
169         mod                  source.FileIdentity
170         verb                 modAction
171 }
172
173 type modAction int
174
175 const (
176         why modAction = iota
177         upgrade
178 )
179
180 type modWhyHandle struct {
181         handle *memoize.Handle
182 }
183
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
188
189         err error
190 }
191
192 func (mwh *modWhyHandle) why(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
193         v, err := mwh.handle.Get(ctx, snapshot.generation, snapshot)
194         if err != nil {
195                 return nil, err
196         }
197         data := v.(*modWhyData)
198         return data.why, data.err
199 }
200
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())
204         }
205         if err := s.awaitLoaded(ctx); err != nil {
206                 return nil, err
207         }
208         if handle := s.getModWhyHandle(fh.URI()); handle != nil {
209                 return handle.why(ctx, s)
210         }
211         // Make sure to use the module root as the working directory.
212         cfg := s.config(ctx, filepath.Dir(fh.URI().Filename()))
213         key := modKey{
214                 sessionID: s.view.session.id,
215                 cfg:       hashConfig(cfg),
216                 mod:       fh.FileIdentity(),
217                 view:      s.view.rootURI.Filename(),
218                 verb:      why,
219         }
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()))
222                 defer done()
223
224                 snapshot := arg.(*snapshot)
225
226                 pm, err := snapshot.ParseMod(ctx, fh)
227                 if err != nil {
228                         return &modWhyData{err: err}
229                 }
230                 // No requires to explain.
231                 if len(pm.File.Require) == 0 {
232                         return &modWhyData{}
233                 }
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)
238                 }
239                 stdout, err := snapshot.runGoCommandWithConfig(ctx, cfg, "mod", args)
240                 if err != nil {
241                         return &modWhyData{err: err}
242                 }
243                 whyList := strings.Split(stdout.String(), "\n\n")
244                 if len(whyList) != len(pm.File.Require) {
245                         return &modWhyData{
246                                 err: fmt.Errorf("mismatched number of results: got %v, want %v", len(whyList), len(pm.File.Require)),
247                         }
248                 }
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]
252                 }
253                 return &modWhyData{why: why}
254         })
255
256         mwh := &modWhyHandle{handle: h}
257         s.mu.Lock()
258         s.modWhyHandles[fh.URI()] = mwh
259         s.mu.Unlock()
260
261         return mwh.why(ctx, s)
262 }
263
264 type modUpgradeHandle struct {
265         handle *memoize.Handle
266 }
267
268 type modUpgradeData struct {
269         // upgrades maps modules to their latest versions.
270         upgrades map[string]string
271
272         err error
273 }
274
275 func (muh *modUpgradeHandle) upgrades(ctx context.Context, snapshot *snapshot) (map[string]string, error) {
276         v, err := muh.handle.Get(ctx, snapshot.generation, snapshot)
277         if v == nil {
278                 return nil, err
279         }
280         data := v.(*modUpgradeData)
281         return data.upgrades, data.err
282 }
283
284 // moduleUpgrade describes a module that can be upgraded to a particular
285 // version.
286 type moduleUpgrade struct {
287         Path   string
288         Update struct {
289                 Version string
290         }
291 }
292
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())
296         }
297         if err := s.awaitLoaded(ctx); err != nil {
298                 return nil, err
299         }
300         if handle := s.getModUpgradeHandle(fh.URI()); handle != nil {
301                 return handle.upgrades(ctx, s)
302         }
303         // Use the module root as the working directory.
304         cfg := s.config(ctx, filepath.Dir(fh.URI().Filename()))
305         key := modKey{
306                 sessionID: s.view.session.id,
307                 cfg:       hashConfig(cfg),
308                 mod:       fh.FileIdentity(),
309                 view:      s.view.rootURI.Filename(),
310                 verb:      upgrade,
311         }
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()))
314                 defer done()
315
316                 snapshot := arg.(*snapshot)
317
318                 pm, err := snapshot.ParseMod(ctx, fh)
319                 if err != nil {
320                         return &modUpgradeData{err: err}
321                 }
322
323                 // No requires to upgrade.
324                 if len(pm.File.Require) == 0 {
325                         return &modUpgradeData{}
326                 }
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")
334                 }
335                 stdout, err := snapshot.runGoCommandWithConfig(ctx, cfg, "list", args)
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         })
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 }