Debian Codegraph @

gopls/internal/golang/comment.go

raw symbols SCIP
1 // Copyright 2022 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 golang
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/doc/comment"
13 "go/token"
14 "go/types"
15 "iter"
16 pathpkg "path"
17 "strings"
18
19 "golang.org/x/tools/gopls/internal/cache"
20 "golang.org/x/tools/gopls/internal/cache/parsego"
21 "golang.org/x/tools/gopls/internal/protocol"
22 "golang.org/x/tools/gopls/internal/settings"
23 "golang.org/x/tools/internal/astutil"
24 )
25
26 var errNoCommentReference = errors.New("no comment reference found")
27
28 // DocCommentToMarkdown converts the text of a [doc comment] to Markdown.
29 //
30 // TODO(adonovan): provide a package (or file imports) as context for
31 // proper rendering of doc links; see [newDocCommentParser] and golang/go#61677.
32 //
33 // [doc comment]: https://go.dev/doc/comment
34 func DocCommentToMarkdown(text string, options *settings.Options) string {
35 var parser comment.Parser
36 doc := parser.Parse(text)
37
38 var printer comment.Printer
39 // The default produces {#Hdr-...} tags for headings.
40 // vscode displays them, which is undesirable.
41 // The godoc for comment.Printer says the tags
42 // avoid a security problem.
43 printer.HeadingID = func(*comment.Heading) string { return "" }
44 printer.DocLinkURL = func(link *comment.DocLink) string {
45 msg := fmt.Sprintf("https://%s/%s", options.LinkTarget, link.ImportPath)
46 if link.Name != "" {
47 msg += "#"
48 if link.Recv != "" {
49 msg += link.Recv + "."
50 }
51 msg += link.Name
52 }
53 return msg
54 }
55
56 return string(printer.Markdown(doc))
57 }
58
59 // docLinkDefinition finds the definition of the doc link in comments at pos.
60 // If there is no reference at pos, returns errNoCommentReference.
61 //
62 // TODO(hxjiang): simplify the error handling.
63 func docLinkDefinition(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) ([]protocol.Location, error) {
64 obj, _, err := resolveDocLink(pkg, pgf, astutil.RangeOf(start, end))
65 if err != nil {
66 return nil, err
67 }
68 loc, err := ObjectLocation(ctx, pkg.FileSet(), snapshot, obj)
69 if err != nil {
70 return nil, err
71 }
72 return []protocol.Location{loc}, nil
73 }
74
75 // resolveDocLink parses a doc link in a comment such as [fmt.Println]
76 // and returns the symbol at pos, along with the link's range.
77 func resolveDocLink(pkg *cache.Package, pgf *parsego.File, rng astutil.Range) (types.Object, protocol.Range, error) {
78 var comment *ast.CommentGroup
79 for _, c := range pgf.File.Comments {
80 if astutil.NodeContains(c, rng) {
81 comment = c
82 break
83 }
84 }
85
86 if comment == nil {
87 return nil, protocol.Range{}, errNoCommentReference
88 }
89
90 for docLink := range commentDocLinks(comment) {
91 if astutil.NodeContains(docLink.partRange, rng) {
92 if obj := lookupDocLinkSymbol(pkg, pgf, docLink.nameText); obj != nil {
93 rng, err := pgf.NodeRange(docLink.partRange)
94 if err != nil {
95 return nil, protocol.Range{}, err
96 }
97 return obj, rng, nil
98 }
99 break
100 }
101 }
102
103 return nil, protocol.Range{}, errNoCommentReference
104 }
105
106 // A docLink holds the parsed information for a single resolution step of a
107 // documentation link. For a link like "[fmt.Scanner.Scan]", the parser will
108 // yield three docLink values, one for each progressively resolved part:
109 // "fmt", "fmt.Scanner", and "fmt.Scanner.Scan".
110 type docLink struct {
111 // The text of the right-most component of the name for this step.
112 // For the name "fmt.Scanner", this is "Scanner".
113 partText string
114 partRange astutil.Range
115
116 // The text of the fully-qualified symbol path resolved in this step.
117 // For example, "fmt.Scanner". Used for symbol lookups.
118 nameText string
119
120 // The text of the entire, original doc link expression, including brackets.
121 // For example, "[fmt.Scanner.Scan]".
122 bracketText string
123 }
124
125 // commentDocLinks returns the sequence of Go doc links in the comment group.
126 // TODO(hxjiang): move to [parsego] package.
127 func commentDocLinks(cg *ast.CommentGroup) iter.Seq[docLink] {
128 return func(yield func(docLink) bool) {
129 for _, comment := range cg.List {
130 // The canonical parsing algorithm is defined by go/doc/comment, but
131 // unfortunately its API provides no way to reliably reconstruct the
132 // position of each doc link from the parsed result.
133
134 for _, idx := range findDocLinkIndices(comment.Text) {
135 // [mstart, mend) identifies the first submatch, which is the
136 // reference name in the doc link (sans '*').
137 // e.g. The "[fmt.Println]" reference name is "fmt.Println".
138 mstart, mend := idx[2], idx[3]
139
140 // idx[0], idx[1] matches the full pattern. idx[0] corresponds
141 // to the opening bracket. idx[1] may include trailing
142 // whitespace or punctuation, so we need to use "mend" to
143 // capture the exact location of the closing bracket, which must
144 // be one space after the end of the reference name.
145 bracketText := comment.Text[idx[0] : mend+1]
146
147 match := comment.Text[mstart:mend]
148
149 if strings.Contains(match, "\n") {
150 continue
151 }
152
153 // [namePos.Start, namePos.End) identifies the start and end
154 // position of a name. e.g. "fmt", "fmt.Scanner", "fmt.Scanner.Scan".
155 var name string
156
157 namePos := astutil.RangeOf(comment.Pos()+token.Pos(mstart), comment.Pos()+token.Pos(mstart-1))
158 // [partPos.Start, partPos.End) identifies the start and end
159 // position of a part. e.g. "fmt", "Scanner", "Scan".
160 partPos := namePos
161 for part := range strings.SplitSeq(match, ".") {
162 if name != "" {
163 name += "."
164 }
165 name += part
166
167 partPos.Start = partPos.EndPos + token.Pos(len(".")) // Move start to the first char of next part
168 partPos.EndPos = partPos.Start + token.Pos(len(part)) // Move end to next char of current part
169
170 namePos.EndPos = partPos.EndPos
171
172 if !yield(docLink{
173 partRange: partPos,
174 partText: part,
175 nameText: name,
176 bracketText: bracketText,
177 }) {
178 return
179 }
180 }
181 }
182 }
183 }
184 }
185
186 // lookupDocLinkSymbol returns the symbol denoted by a doc link such
187 // as "fmt.Println" or "bytes.Buffer.Write" in the specified file.
188 func lookupDocLinkSymbol(pkg *cache.Package, pgf *parsego.File, name string) types.Object {
189 scope := pkg.Types().Scope()
190
191 prefix, suffix, _ := strings.Cut(name, ".")
192
193 // Try treating the prefix as a package name,
194 // allowing for non-renaming and renaming imports.
195 fileScope := pkg.TypesInfo().Scopes[pgf.File]
196 if fileScope == nil {
197 // As we learned in golang/go#69616, any file may not be Scopes!
198 // - A non-compiled Go file (such as unsafe.go) won't be in Scopes.
199 // - A (technically) compiled go file with the wrong package name won't be
200 // in Scopes, as it will be skipped by go/types.
201 return nil
202 }
203 pkgname, ok := fileScope.Lookup(prefix).(*types.PkgName) // ok => prefix is imported name
204 if !ok {
205 // Handle renaming import, e.g.
206 // [path.Join] after import pathpkg "path".
207 // (Should we look at all files of the package?)
208 for _, imp := range pgf.File.Imports {
209 pkgname2 := pkg.TypesInfo().PkgNameOf(imp)
210 if pkgname2 != nil && pkgname2.Imported().Name() == prefix {
211 pkgname = pkgname2
212 break
213 }
214 }
215 }
216 if pkgname != nil {
217 scope = pkgname.Imported().Scope()
218 if suffix == "" {
219 return pkgname // not really a valid doc link
220 }
221 name = suffix
222 }
223
224 // TODO(adonovan): try searching the forward closure for packages
225 // that define the symbol but are not directly imported;
226 // see https://github.com/golang/go/issues/61677
227
228 // Field or sel?
229 recv, sel, ok := strings.Cut(name, ".")
230 if ok {
231 obj := scope.Lookup(recv) // package scope
232 if obj == nil {
233 obj = types.Universe.Lookup(recv)
234 }
235 obj, ok := obj.(*types.TypeName)
236 if !ok {
237 return nil
238 }
239 m, _, _ := types.LookupFieldOrMethod(obj.Type(), true, obj.Pkg(), sel)
240 return m
241 }
242
243 if obj := scope.Lookup(name); obj != nil {
244 return obj // package-level symbol
245 }
246 return types.Universe.Lookup(name) // built-in symbol
247 }
248
249 // newDocCommentParser returns a function that parses [doc comments],
250 // with context for Doc Links supplied by the specified package.
251 //
252 // Imported symbols are rendered using the import mapping for the file
253 // that encloses fileNode.
254 //
255 // The resulting function is not concurrency safe.
256 //
257 // See issue #61677 for how this might be generalized to support
258 // correct contextual parsing of doc comments in Hover too.
259 //
260 // [doc comment]: https://go.dev/doc/comment
261 func newDocCommentParser(pkg *cache.Package) func(fileNode ast.Node, text string) *comment.Doc {
262 var currentFilePos token.Pos // pos whose enclosing file's import mapping should be used
263 parser := &comment.Parser{
264 LookupPackage: func(name string) (importPath string, ok bool) {
265 for _, f := range pkg.Syntax() {
266 // Different files in the same package have
267 // different import mappings. Use the provided
268 // syntax node to find the correct file.
269 if astutil.NodeContainsPos(f, currentFilePos) {
270 // First try each actual imported package name.
271 for _, imp := range f.Imports {
272 pkgName := pkg.TypesInfo().PkgNameOf(imp)
273 if pkgName != nil && pkgName.Name() == name {
274 return pkgName.Imported().Path(), true
275 }
276 }
277
278 // Then try each imported package's declared name,
279 // as some packages are typically imported under a
280 // non-default name (e.g. pathpkg "path") but
281 // may be referred to in doc links using their
282 // canonical name.
283 for _, imp := range f.Imports {
284 pkgName := pkg.TypesInfo().PkgNameOf(imp)
285 if pkgName != nil && pkgName.Imported().Name() == name {
286 return pkgName.Imported().Path(), true
287 }
288 }
289
290 // Finally try matching the last segment of each import
291 // path imported by any file in the package, as the
292 // doc comment may appear in a different file from the
293 // import.
294 //
295 // Ideally we would look up the DepsByPkgPath value
296 // (a PackageID) in the metadata graph and use the
297 // package's declared name instead of this heuristic,
298 // but we don't have access to the graph here.
299 for path := range pkg.Metadata().DepsByPkgPath {
300 if pathpkg.Base(trimVersionSuffix(string(path))) == name {
301 return string(path), true
302 }
303 }
304
305 break
306 }
307 }
308 return "", false
309 },
310 LookupSym: func(recv, name string) (ok bool) {
311 // package-level decl?
312 if recv == "" {
313 return pkg.Types().Scope().Lookup(name) != nil
314 }
315
316 // method?
317 tname, ok := pkg.Types().Scope().Lookup(recv).(*types.TypeName)
318 if !ok {
319 return false
320 }
321 m, _, _ := types.LookupFieldOrMethod(tname.Type(), true, pkg.Types(), name)
322 return is[*types.Func](m)
323 },
324 }
325 return func(fileNode ast.Node, text string) *comment.Doc {
326 currentFilePos = fileNode.Pos()
327 return parser.Parse(text)
328 }
329 }