Debian Codegraph @

gopls/internal/golang/util.go

raw symbols SCIP
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 golang
6
7 import (
8 "context"
9 "go/ast"
10 "go/printer"
11 "go/token"
12 "go/types"
13 "regexp"
14 "slices"
15 "strings"
16 "unicode"
17
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/cache/metadata"
20 "golang.org/x/tools/gopls/internal/cache/parsego"
21 "golang.org/x/tools/gopls/internal/protocol"
22 "golang.org/x/tools/gopls/internal/util/bug"
23 "golang.org/x/tools/gopls/internal/util/tokeninternal"
24 )
25
26 // IsGenerated reads and parses the header of the file denoted by uri
27 // and reports whether it [ast.IsGenerated].
28 func IsGenerated(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) bool {
29 fh, err := snapshot.ReadFile(ctx, uri)
30 if err != nil {
31 return false
32 }
33 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
34 if err != nil {
35 return false
36 }
37 return ast.IsGenerated(pgf.File)
38 }
39
40 // FormatNode returns the "pretty-print" output for an ast node.
41 func FormatNode(fset *token.FileSet, n ast.Node) string {
42 var buf strings.Builder
43 if err := printer.Fprint(&buf, fset, n); err != nil {
44 // TODO(rfindley): we should use bug.Reportf here.
45 // We encounter this during completion.resolveInvalid.
46 return ""
47 }
48 return buf.String()
49 }
50
51 // formatNodeFile is like FormatNode, but requires only the token.File for the
52 // syntax containing the given ast node.
53 func formatNodeFile(file *token.File, n ast.Node) string {
54 fset := tokeninternal.FileSetFor(file)
55 return FormatNode(fset, n)
56 }
57
58 // findFileInDeps finds package metadata containing URI in the transitive
59 // dependencies of m. When using the Go command, the answer is unique.
60 func findFileInDeps(s metadata.Source, mp *metadata.Package, uri protocol.DocumentURI) *metadata.Package {
61 seen := make(map[PackageID]bool)
62 var search func(*metadata.Package) *metadata.Package
63 search = func(mp *metadata.Package) *metadata.Package {
64 if seen[mp.ID] {
65 return nil
66 }
67 seen[mp.ID] = true
68 if slices.Contains(mp.CompiledGoFiles, uri) {
69 return mp
70 }
71 for _, dep := range mp.DepsByPkgPath {
72 mp := s.Metadata(dep)
73 if mp == nil {
74 bug.Reportf("nil metadata for %q", dep)
75 continue
76 }
77 if found := search(mp); found != nil {
78 return found
79 }
80 }
81 return nil
82 }
83 return search(mp)
84 }
85
86 // requalifier returns a function that re-qualifies identifiers and qualified
87 // identifiers contained in targetFile using the given metadata qualifier.
88 func requalifier(s metadata.Source, targetFile *ast.File, targetMeta *metadata.Package, mq MetadataQualifier) func(string) string {
89 qm := map[string]string{
90 "": mq(targetMeta.Name, "", targetMeta.PkgPath),
91 }
92
93 // Construct mapping of import paths to their defined or implicit names.
94 for _, imp := range targetFile.Imports {
95 name, pkgName, impPath, pkgPath := importInfo(s, imp, targetMeta)
96
97 // Re-map the target name for the source file.
98 qm[name] = mq(pkgName, impPath, pkgPath)
99 }
100
101 return func(name string) string {
102 if newName, ok := qm[name]; ok {
103 return newName
104 }
105 return name
106 }
107 }
108
109 // A MetadataQualifier is a function that qualifies an identifier declared in a
110 // package with the given package name, import path, and package path.
111 //
112 // In scenarios where metadata is missing the provided PackageName and
113 // PackagePath may be empty, but ImportPath must always be non-empty.
114 type MetadataQualifier func(PackageName, ImportPath, PackagePath) string
115
116 // MetadataQualifierForFile returns a metadata qualifier that chooses the best
117 // qualification of an imported package relative to the file f in package with
118 // metadata m.
119 func MetadataQualifierForFile(s metadata.Source, f *ast.File, mp *metadata.Package) MetadataQualifier {
120 // Record local names for import paths.
121 localNames := make(map[ImportPath]string) // local names for imports in f
122 for _, imp := range f.Imports {
123 name, _, impPath, _ := importInfo(s, imp, mp)
124 localNames[impPath] = name
125 }
126
127 // Record a package path -> import path mapping.
128 inverseDeps := make(map[PackageID]PackagePath)
129 for path, id := range mp.DepsByPkgPath {
130 inverseDeps[id] = path
131 }
132 importsByPkgPath := make(map[PackagePath]ImportPath) // best import paths by pkgPath
133 for impPath, id := range mp.DepsByImpPath {
134 if id == "" {
135 continue
136 }
137 pkgPath := inverseDeps[id]
138 _, hasPath := importsByPkgPath[pkgPath]
139 _, hasImp := localNames[impPath]
140 // In rare cases, there may be multiple import paths with the same package
141 // path. In such scenarios, prefer an import path that already exists in
142 // the file.
143 if !hasPath || hasImp {
144 importsByPkgPath[pkgPath] = impPath
145 }
146 }
147
148 return func(pkgName PackageName, impPath ImportPath, pkgPath PackagePath) string {
149 // If supplied, translate the package path to an import path in the source
150 // package.
151 if pkgPath != "" {
152 if srcImp := importsByPkgPath[pkgPath]; srcImp != "" {
153 impPath = srcImp
154 }
155 if pkgPath == mp.PkgPath {
156 return ""
157 }
158 }
159 if localName, ok := localNames[impPath]; ok && impPath != "" {
160 return localName
161 }
162 if pkgName != "" {
163 return string(pkgName)
164 }
165 idx := strings.LastIndexByte(string(impPath), '/')
166 return string(impPath[idx+1:])
167 }
168 }
169
170 // importInfo collects information about the import specified by imp,
171 // extracting its file-local name, package name, import path, and package path.
172 //
173 // If metadata is missing for the import, the resulting package name and
174 // package path may be empty, and the file local name may be guessed based on
175 // the import path.
176 //
177 // Note: previous versions of this helper used a PackageID->PackagePath map
178 // extracted from m, for extracting package path even in the case where
179 // metadata for a dep was missing. This should not be necessary, as we should
180 // always have metadata for IDs contained in DepsByPkgPath.
181 func importInfo(s metadata.Source, imp *ast.ImportSpec, mp *metadata.Package) (string, PackageName, ImportPath, PackagePath) {
182 var (
183 name string // local name
184 pkgName PackageName
185 impPath = metadata.UnquoteImportPath(imp)
186 pkgPath PackagePath
187 )
188
189 // If the import has a local name, use it.
190 if imp.Name != nil {
191 name = imp.Name.Name
192 }
193
194 // Try to find metadata for the import. If successful and there is no local
195 // name, the package name is the local name.
196 if depID := mp.DepsByImpPath[impPath]; depID != "" {
197 if depMP := s.Metadata(depID); depMP != nil {
198 if name == "" {
199 name = string(depMP.Name)
200 }
201 pkgName = depMP.Name
202 pkgPath = depMP.PkgPath
203 }
204 }
205
206 // If the local name is still unknown, guess it based on the import path.
207 if name == "" {
208 idx := strings.LastIndexByte(string(impPath), '/')
209 name = string(impPath[idx+1:])
210 }
211 return name, pkgName, impPath, pkgPath
212 }
213
214 // isDirective reports whether c is a comment directive.
215 //
216 // Copied and adapted from go/src/go/ast/ast.go.
217 func isDirective(c string) bool {
218 if len(c) < 3 {
219 return false
220 }
221 if c[1] != '/' {
222 return false
223 }
224 //-style comment (no newline at the end)
225 c = c[2:]
226 if len(c) == 0 {
227 // empty line
228 return false
229 }
230 // "//line " is a line directive.
231 // (The // has been removed.)
232 if strings.HasPrefix(c, "line ") {
233 return true
234 }
235
236 // "//[a-z0-9]+:[a-z0-9]"
237 // (The // has been removed.)
238 colon := strings.Index(c, ":")
239 if colon <= 0 || colon+1 >= len(c) {
240 return false
241 }
242 for i := 0; i <= colon+1; i++ {
243 if i == colon {
244 continue
245 }
246 b := c[i]
247 if !('a' <= b && b <= 'z' || '0' <= b && b <= '9') {
248 return false
249 }
250 }
251 return true
252 }
253
254 // embeddedIdent returns the type name identifier for an embedding x, if x in a
255 // valid embedding. Otherwise, it returns nil.
256 //
257 // Spec: An embedded field must be specified as a type name T or as a pointer
258 // to a non-interface type name *T
259 func embeddedIdent(x ast.Expr) *ast.Ident {
260 if star, ok := x.(*ast.StarExpr); ok {
261 x = star.X
262 }
263 switch ix := x.(type) { // check for instantiated receivers
264 case *ast.IndexExpr:
265 x = ix.X
266 case *ast.IndexListExpr:
267 x = ix.X
268 }
269 switch x := x.(type) {
270 case *ast.Ident:
271 return x
272 case *ast.SelectorExpr:
273 if _, ok := x.X.(*ast.Ident); ok {
274 return x.Sel
275 }
276 }
277 return nil
278 }
279
280 // An importFunc is an implementation of the single-method
281 // types.Importer interface based on a function value.
282 type ImporterFunc func(path string) (*types.Package, error)
283
284 func (f ImporterFunc) Import(path string) (*types.Package, error) { return f(path) }
285
286 // isBuiltin reports whether obj is a built-in symbol (e.g. append, iota, error.Error, unsafe.Slice).
287 // All other symbols have a valid position and a valid package.
288 func isBuiltin(obj types.Object) bool { return !obj.Pos().IsValid() }
289
290 // btoi returns int(b) as proposed in #64825.
291 func btoi(b bool) int {
292 if b {
293 return 1
294 } else {
295 return 0
296 }
297 }
298
299 // boolCompare is a comparison function for booleans, returning -1 if x < y, 0
300 // if x == y, and 1 if x > y, where false < true.
301 func boolCompare(x, y bool) int {
302 return btoi(x) - btoi(y)
303 }
304
305 // AbbreviateVarName returns an abbreviated var name based on the given full
306 // name (which may be a type name, for example).
307 //
308 // See the simple heuristics documented in line.
309 func AbbreviateVarName(s string) string {
310 var (
311 b strings.Builder
312 useNextUpper bool
313 )
314 for i, r := range s {
315 // Stop if we encounter a non-identifier rune.
316 if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
317 break
318 }
319
320 // Otherwise, take the first letter from word boundaries, assuming
321 // camelCase.
322 if i == 0 {
323 b.WriteRune(unicode.ToLower(r))
324 }
325
326 if unicode.IsUpper(r) {
327 if useNextUpper {
328 b.WriteRune(unicode.ToLower(r))
329 useNextUpper = false
330 }
331 } else {
332 useNextUpper = true
333 }
334 }
335 return b.String()
336 }
337
338 // CopyrightComment returns the copyright comment group from the input file, or
339 // nil if not found.
340 func CopyrightComment(file *ast.File) *ast.CommentGroup {
341 if len(file.Comments) == 0 {
342 return nil
343 }
344
345 // Copyright should appear before package decl and must be the first
346 // comment group.
347 if c := file.Comments[0]; c.Pos() < file.Package && c != file.Doc &&
348 !isDirective(c.List[0].Text) &&
349 strings.Contains(strings.ToLower(c.List[0].Text), "copyright") {
350 return c
351 }
352
353 return nil
354 }
355
356 var buildConstraintRe = regexp.MustCompile(`^//(go:build|\s*\+build).*`)
357
358 // buildConstraintComment returns the build constraint comment from the input
359 // file.
360 // Returns nil if not found.
361 func buildConstraintComment(file *ast.File) *ast.Comment {
362 for _, cg := range file.Comments {
363 // In Go files a build constraint must appear before the package clause.
364 // See https://pkg.go.dev/cmd/go#hdr-Build_constraints
365 if cg.Pos() > file.Package {
366 return nil
367 }
368
369 for _, c := range cg.List {
370 // TODO: use ast.ParseDirective when available (#68021).
371 if buildConstraintRe.MatchString(c.Text) {
372 return c
373 }
374 }
375 }
376
377 return nil
378 }