File: link.go

package info (click to toggle)
golang-golang-x-tools 1%3A0.5.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports
  • size: 16,592 kB
  • sloc: javascript: 2,011; asm: 1,635; sh: 192; yacc: 155; makefile: 52; ansic: 8
file content (282 lines) | stat: -rw-r--r-- 8,327 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package lsp

import (
	"bytes"
	"context"
	"fmt"
	"go/ast"
	"go/token"
	"net/url"
	"regexp"
	"strings"
	"sync"

	"golang.org/x/mod/modfile"
	"golang.org/x/tools/gopls/internal/lsp/protocol"
	"golang.org/x/tools/gopls/internal/lsp/source"
	"golang.org/x/tools/gopls/internal/span"
	"golang.org/x/tools/internal/event"
	"golang.org/x/tools/internal/event/tag"
)

func (s *Server) documentLink(ctx context.Context, params *protocol.DocumentLinkParams) (links []protocol.DocumentLink, err error) {
	snapshot, fh, ok, release, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
	defer release()
	if !ok {
		return nil, err
	}
	switch snapshot.View().FileKind(fh) {
	case source.Mod:
		links, err = modLinks(ctx, snapshot, fh)
	case source.Go:
		links, err = goLinks(ctx, snapshot, fh)
	}
	// Don't return errors for document links.
	if err != nil {
		event.Error(ctx, "failed to compute document links", err, tag.URI.Of(fh.URI()))
		return nil, nil
	}
	return links, nil
}

func modLinks(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle) ([]protocol.DocumentLink, error) {
	pm, err := snapshot.ParseMod(ctx, fh)
	if err != nil {
		return nil, err
	}
	tokFile := pm.Mapper.TokFile

	var links []protocol.DocumentLink
	for _, req := range pm.File.Require {
		if req.Syntax == nil {
			continue
		}
		// See golang/go#36998: don't link to modules matching GOPRIVATE.
		if snapshot.View().IsGoPrivatePath(req.Mod.Path) {
			continue
		}
		dep := []byte(req.Mod.Path)
		s, e := req.Syntax.Start.Byte, req.Syntax.End.Byte
		i := bytes.Index(pm.Mapper.Content[s:e], dep)
		if i == -1 {
			continue
		}
		// Shift the start position to the location of the
		// dependency within the require statement.
		start, end := tokFile.Pos(s+i), tokFile.Pos(s+i+len(dep))
		target := source.BuildLink(snapshot.View().Options().LinkTarget, "mod/"+req.Mod.String(), "")
		l, err := toProtocolLink(tokFile, pm.Mapper, target, start, end)
		if err != nil {
			return nil, err
		}
		links = append(links, l)
	}
	// TODO(ridersofrohan): handle links for replace and exclude directives.
	if syntax := pm.File.Syntax; syntax == nil {
		return links, nil
	}

	// Get all the links that are contained in the comments of the file.
	urlRegexp := snapshot.View().Options().URLRegexp
	for _, expr := range pm.File.Syntax.Stmt {
		comments := expr.Comment()
		if comments == nil {
			continue
		}
		for _, section := range [][]modfile.Comment{comments.Before, comments.Suffix, comments.After} {
			for _, comment := range section {
				start := tokFile.Pos(comment.Start.Byte)
				l, err := findLinksInString(urlRegexp, comment.Token, start, tokFile, pm.Mapper)
				if err != nil {
					return nil, err
				}
				links = append(links, l...)
			}
		}
	}
	return links, nil
}

// goLinks returns the set of hyperlink annotations for the specified Go file.
func goLinks(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle) ([]protocol.DocumentLink, error) {
	view := snapshot.View()

	pgf, err := snapshot.ParseGo(ctx, fh, source.ParseFull)
	if err != nil {
		return nil, err
	}

	var links []protocol.DocumentLink

	// Create links for import specs.
	if view.Options().ImportShortcut.ShowLinks() {

		// If links are to pkg.go.dev, append module version suffixes.
		// This requires the import map from the package metadata. Ignore errors.
		var depsByImpPath map[source.ImportPath]source.PackageID
		if strings.ToLower(view.Options().LinkTarget) == "pkg.go.dev" {
			if metas, _ := snapshot.MetadataForFile(ctx, fh.URI()); len(metas) > 0 {
				depsByImpPath = metas[0].DepsByImpPath // 0 => narrowest package
			}
		}

		for _, imp := range pgf.File.Imports {
			importPath := source.UnquoteImportPath(imp)
			if importPath == "" {
				continue // bad import
			}
			// See golang/go#36998: don't link to modules matching GOPRIVATE.
			if view.IsGoPrivatePath(string(importPath)) {
				continue
			}

			urlPath := string(importPath)

			// For pkg.go.dev, append module version suffix to package import path.
			if m := snapshot.Metadata(depsByImpPath[importPath]); m != nil &&
				m.Module != nil &&
				m.Module.Path != "" &&
				m.Module.Version != "" &&
				!source.IsWorkspaceModuleVersion(m.Module.Version) {
				urlPath = strings.Replace(urlPath, m.Module.Path, m.Module.Path+"@"+m.Module.Version, 1)
			}

			// Account for the quotation marks in the positions.
			start := imp.Path.Pos() + 1
			end := imp.Path.End() - 1
			targetURL := source.BuildLink(view.Options().LinkTarget, urlPath, "")
			l, err := toProtocolLink(pgf.Tok, pgf.Mapper, targetURL, start, end)
			if err != nil {
				return nil, err
			}
			links = append(links, l)
		}
	}

	urlRegexp := snapshot.View().Options().URLRegexp

	// Gather links found in string literals.
	var str []*ast.BasicLit
	ast.Inspect(pgf.File, func(node ast.Node) bool {
		switch n := node.(type) {
		case *ast.ImportSpec:
			return false // don't process import strings again
		case *ast.BasicLit:
			if n.Kind == token.STRING {
				str = append(str, n)
			}
		}
		return true
	})
	for _, s := range str {
		l, err := findLinksInString(urlRegexp, s.Value, s.Pos(), pgf.Tok, pgf.Mapper)
		if err != nil {
			return nil, err
		}
		links = append(links, l...)
	}

	// Gather links found in comments.
	for _, commentGroup := range pgf.File.Comments {
		for _, comment := range commentGroup.List {
			l, err := findLinksInString(urlRegexp, comment.Text, comment.Pos(), pgf.Tok, pgf.Mapper)
			if err != nil {
				return nil, err
			}
			links = append(links, l...)
		}
	}

	return links, nil
}

// acceptedSchemes controls the schemes that URLs must have to be shown to the
// user. Other schemes can't be opened by LSP clients, so linkifying them is
// distracting. See golang/go#43990.
var acceptedSchemes = map[string]bool{
	"http":  true,
	"https": true,
}

// urlRegexp is the user-supplied regular expression to match URL.
// tokFile may be a throwaway File for non-Go files.
func findLinksInString(urlRegexp *regexp.Regexp, src string, pos token.Pos, tokFile *token.File, m *protocol.ColumnMapper) ([]protocol.DocumentLink, error) {
	var links []protocol.DocumentLink
	for _, index := range urlRegexp.FindAllIndex([]byte(src), -1) {
		start, end := index[0], index[1]
		startPos := token.Pos(int(pos) + start)
		endPos := token.Pos(int(pos) + end)
		link := src[start:end]
		linkURL, err := url.Parse(link)
		// Fallback: Linkify IP addresses as suggested in golang/go#18824.
		if err != nil {
			linkURL, err = url.Parse("//" + link)
			// Not all potential links will be valid, so don't return this error.
			if err != nil {
				continue
			}
		}
		// If the URL has no scheme, use https.
		if linkURL.Scheme == "" {
			linkURL.Scheme = "https"
		}
		if !acceptedSchemes[linkURL.Scheme] {
			continue
		}
		l, err := toProtocolLink(tokFile, m, linkURL.String(), startPos, endPos)
		if err != nil {
			return nil, err
		}
		links = append(links, l)
	}
	// Handle golang/go#1234-style links.
	r := getIssueRegexp()
	for _, index := range r.FindAllIndex([]byte(src), -1) {
		start, end := index[0], index[1]
		startPos := token.Pos(int(pos) + start)
		endPos := token.Pos(int(pos) + end)
		matches := r.FindStringSubmatch(src)
		if len(matches) < 4 {
			continue
		}
		org, repo, number := matches[1], matches[2], matches[3]
		targetURL := fmt.Sprintf("https://github.com/%s/%s/issues/%s", org, repo, number)
		l, err := toProtocolLink(tokFile, m, targetURL, startPos, endPos)
		if err != nil {
			return nil, err
		}
		links = append(links, l)
	}
	return links, nil
}

func getIssueRegexp() *regexp.Regexp {
	once.Do(func() {
		issueRegexp = regexp.MustCompile(`(\w+)/([\w-]+)#([0-9]+)`)
	})
	return issueRegexp
}

var (
	once        sync.Once
	issueRegexp *regexp.Regexp
)

func toProtocolLink(tokFile *token.File, m *protocol.ColumnMapper, targetURL string, start, end token.Pos) (protocol.DocumentLink, error) {
	spn, err := span.NewRange(tokFile, start, end).Span()
	if err != nil {
		return protocol.DocumentLink{}, err
	}
	rng, err := m.Range(spn)
	if err != nil {
		return protocol.DocumentLink{}, err
	}
	return protocol.DocumentLink{
		Range:  rng,
		Target: targetURL,
	}, nil
}