Debian Codegraph @

gopls/internal/server/link.go

raw symbols SCIP
1 // Copyright 2018 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 server
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "go/ast"
12 "go/token"
13 "net/url"
14 "path/filepath"
15 "regexp"
16 "strings"
17 "sync"
18
19 "golang.org/x/mod/modfile"
20 "golang.org/x/mod/module"
21 "golang.org/x/tools/gopls/internal/cache"
22 "golang.org/x/tools/gopls/internal/cache/metadata"
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/file"
25 "golang.org/x/tools/gopls/internal/golang"
26 "golang.org/x/tools/gopls/internal/label"
27 "golang.org/x/tools/gopls/internal/protocol"
28 "golang.org/x/tools/gopls/internal/util/safetoken"
29 "golang.org/x/tools/internal/event"
30 "mvdan.cc/xurls/v2"
31 )
32
33 func (s *server) DocumentLink(ctx context.Context, params *protocol.DocumentLinkParams) (links []protocol.DocumentLink, err error) {
34 ctx, done := event.Start(ctx, "server.DocumentLink")
35 defer done()
36
37 fh, snapshot, release, err := s.session.FileOf(ctx, params.TextDocument.URI)
38 if err != nil {
39 return nil, err
40 }
41 defer release()
42
43 switch snapshot.FileKind(fh) {
44 case file.Mod:
45 links, err = modLinks(ctx, snapshot, fh)
46 case file.Go:
47 links, err = goLinks(ctx, snapshot, fh)
48 }
49 // Don't return errors for document links.
50 if err != nil {
51 event.Error(ctx, "failed to compute document links", err, label.URI.Of(fh.URI()))
52 return nil, nil // empty result
53 }
54 return links, nil // may be empty (for other file types)
55 }
56
57 func modLinks(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.DocumentLink, error) {
58 pm, err := snapshot.ParseMod(ctx, fh)
59 if err != nil {
60 return nil, err
61 }
62
63 var links []protocol.DocumentLink
64 for _, rep := range pm.File.Replace {
65 if modfile.IsDirectoryPath(rep.New.Path) {
66 // Have local replacement, such as 'replace A => ../'.
67 dep := []byte(rep.New.Path)
68 start, end := rep.Syntax.Start.Byte, rep.Syntax.End.Byte
69 i := bytes.Index(pm.Mapper.Content[start:end], dep)
70 if i < 0 {
71 continue
72 }
73 path := rep.New.Path
74 if !filepath.IsAbs(path) {
75 path = filepath.Join(fh.URI().DirPath(), path)
76 }
77 // jump to the go.mod file of replaced module.
78 path = filepath.Join(filepath.Clean(path), "go.mod")
79 l, err := toProtocolLink(pm.Mapper, protocol.URIFromPath(path).Path(), start+i, start+i+len(dep))
80 if err != nil {
81 return nil, err
82 }
83 links = append(links, l)
84 continue
85 }
86 }
87
88 for _, req := range pm.File.Require {
89 if req.Syntax == nil {
90 continue
91 }
92 // See golang/go#36998: don't link to modules matching GOPRIVATE.
93 if snapshot.IsGoPrivatePath(req.Mod.Path) {
94 continue
95 }
96 dep := []byte(req.Mod.Path)
97 start, end := req.Syntax.Start.Byte, req.Syntax.End.Byte
98 i := bytes.Index(pm.Mapper.Content[start:end], dep)
99 if i == -1 {
100 continue
101 }
102
103 mod := req.Mod
104 // respect the replacement when constructing a module link.
105 if m, ok := pm.ReplaceMap[req.Mod]; ok {
106 // Have: 'replace A v1.2.3 => A vx.x.x' or 'replace A v1.2.3 => B vx.x.x'.
107 mod = m
108 } else if m, ok := pm.ReplaceMap[module.Version{Path: req.Mod.Path}]; ok &&
109 !modfile.IsDirectoryPath(m.Path) { // exclude local replacement.
110 // Have: 'replace A => A vx.x.x' or 'replace A => B vx.x.x'.
111 mod = m
112 }
113
114 // Shift the start position to the location of the
115 // dependency within the require statement.
116 target := cache.BuildLink(snapshot.Options().LinkTarget, "mod/"+mod.String(), "")
117 l, err := toProtocolLink(pm.Mapper, target, start+i, start+i+len(dep))
118 if err != nil {
119 return nil, err
120 }
121 links = append(links, l)
122 }
123 // TODO(ridersofrohan): handle links for replace and exclude directives.
124 if syntax := pm.File.Syntax; syntax == nil {
125 return links, nil
126 }
127
128 // Get all the links that are contained in the comments of the file.
129 urlRegexp := xurls.Relaxed()
130 for _, expr := range pm.File.Syntax.Stmt {
131 comments := expr.Comment()
132 if comments == nil {
133 continue
134 }
135 for _, section := range [][]modfile.Comment{comments.Before, comments.Suffix, comments.After} {
136 for _, comment := range section {
137 l, err := findLinksInString(urlRegexp, comment.Token, comment.Start.Byte, pm.Mapper)
138 if err != nil {
139 return nil, err
140 }
141 links = append(links, l...)
142 }
143 }
144 }
145 return links, nil
146 }
147
148 // goLinks returns the set of hyperlink annotations for the specified Go file.
149 func goLinks(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.DocumentLink, error) {
150
151 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
152 if err != nil {
153 return nil, err
154 }
155
156 var links []protocol.DocumentLink
157
158 // Create links for import specs.
159 if snapshot.Options().ImportShortcut.ShowLinks() {
160
161 // If links are to pkg.go.dev, append module version suffixes.
162 // This requires the import map from the package metadata. Ignore errors.
163 var depsByImpPath map[golang.ImportPath]golang.PackageID
164 if strings.ToLower(snapshot.Options().LinkTarget) == "pkg.go.dev" {
165 if meta, err := snapshot.NarrowestMetadataForFile(ctx, fh.URI()); err == nil {
166 depsByImpPath = meta.DepsByImpPath
167 }
168 }
169
170 for _, imp := range pgf.File.Imports {
171 importPath := metadata.UnquoteImportPath(imp)
172 if importPath == "" {
173 continue // bad import
174 }
175 // See golang/go#36998: don't link to modules matching GOPRIVATE.
176 if snapshot.IsGoPrivatePath(string(importPath)) {
177 continue
178 }
179
180 urlPath := string(importPath)
181
182 // For pkg.go.dev, append module version suffix to package import path.
183 if mp := snapshot.Metadata(depsByImpPath[importPath]); mp != nil && mp.Module != nil && cache.ResolvedPath(mp.Module) != "" && cache.ResolvedVersion(mp.Module) != "" {
184 urlPath = strings.Replace(urlPath, mp.Module.Path, cache.ResolvedString(mp.Module), 1)
185 }
186
187 start, end, err := safetoken.Offsets(pgf.Tok, imp.Path.Pos(), imp.Path.End())
188 if err != nil {
189 return nil, err
190 }
191 targetURL := cache.BuildLink(snapshot.Options().LinkTarget, urlPath, "")
192 // Account for the quotation marks in the positions.
193 l, err := toProtocolLink(pgf.Mapper, targetURL, start+len(`"`), end-len(`"`))
194 if err != nil {
195 return nil, err
196 }
197 links = append(links, l)
198 }
199 }
200
201 urlRegexp := xurls.Relaxed()
202
203 // Gather links found in string literals.
204 var str []*ast.BasicLit
205 for curLit := range pgf.Cursor().Preorder((*ast.BasicLit)(nil)) {
206 lit := curLit.Node().(*ast.BasicLit)
207 if lit.Kind == token.STRING {
208 if _, ok := curLit.Parent().Node().(*ast.ImportSpec); ok {
209 continue // ignore import strings
210 }
211 str = append(str, lit)
212 }
213 }
214 for _, s := range str {
215 strOffset, err := safetoken.Offset(pgf.Tok, s.Pos())
216 if err != nil {
217 return nil, err
218 }
219 l, err := findLinksInString(urlRegexp, s.Value, strOffset, pgf.Mapper)
220 if err != nil {
221 return nil, err
222 }
223 links = append(links, l...)
224 }
225
226 // Gather links found in comments.
227 for _, commentGroup := range pgf.File.Comments {
228 for _, comment := range commentGroup.List {
229 commentOffset, err := safetoken.Offset(pgf.Tok, comment.Pos())
230 if err != nil {
231 return nil, err
232 }
233 l, err := findLinksInString(urlRegexp, comment.Text, commentOffset, pgf.Mapper)
234 if err != nil {
235 return nil, err
236 }
237 links = append(links, l...)
238 }
239 }
240
241 return links, nil
242 }
243
244 // acceptedSchemes controls the schemes that URLs must have to be shown to the
245 // user. Other schemes can't be opened by LSP clients, so linkifying them is
246 // distracting. See golang/go#43990.
247 var acceptedSchemes = map[string]bool{
248 "http": true,
249 "https": true,
250 }
251
252 // findLinksInString is the user-supplied regular expression to match URL.
253 // srcOffset is the start offset of 'src' within m's file.
254 func findLinksInString(urlRegexp *regexp.Regexp, src string, srcOffset int, m *protocol.Mapper) ([]protocol.DocumentLink, error) {
255 var links []protocol.DocumentLink
256 for _, index := range urlRegexp.FindAllIndex([]byte(src), -1) {
257 start, end := index[0], index[1]
258 link := src[start:end]
259 linkURL, err := url.Parse(link)
260 // Fallback: Linkify IP addresses as suggested in golang/go#18824.
261 if err != nil {
262 linkURL, err = url.Parse("//" + link)
263 // Not all potential links will be valid, so don't return this error.
264 if err != nil {
265 continue
266 }
267 }
268 // If the URL has no scheme, use https.
269 if linkURL.Scheme == "" {
270 linkURL.Scheme = "https"
271 }
272 if !acceptedSchemes[linkURL.Scheme] {
273 continue
274 }
275
276 l, err := toProtocolLink(m, linkURL.String(), srcOffset+start, srcOffset+end)
277 if err != nil {
278 return nil, err
279 }
280 links = append(links, l)
281 }
282 // Handle golang/go#1234-style links.
283 r := getIssueRegexp()
284 for _, index := range r.FindAllIndex([]byte(src), -1) {
285 start, end := index[0], index[1]
286 matches := r.FindStringSubmatch(src)
287 if len(matches) < 4 {
288 continue
289 }
290 org, repo, number := matches[1], matches[2], matches[3]
291 targetURL := fmt.Sprintf("https://github.com/%s/%s/issues/%s", org, repo, number)
292 l, err := toProtocolLink(m, targetURL, srcOffset+start, srcOffset+end)
293 if err != nil {
294 return nil, err
295 }
296 links = append(links, l)
297 }
298 return links, nil
299 }
300
301 func getIssueRegexp() *regexp.Regexp {
302 once.Do(func() {
303 issueRegexp = regexp.MustCompile(`(\w+)/([\w-]+)#([0-9]+)`)
304 })
305 return issueRegexp
306 }
307
308 var (
309 once sync.Once
310 issueRegexp *regexp.Regexp
311 )
312
313 func toProtocolLink(m *protocol.Mapper, targetURL string, start, end int) (protocol.DocumentLink, error) {
314 rng, err := m.OffsetRange(start, end)
315 if err != nil {
316 return protocol.DocumentLink{}, err
317 }
318 return protocol.DocumentLink{
319 Range: rng,
320 Target: &targetURL,
321 }, nil
322 }