Debian Codegraph @

gopls/internal/cache/constraints.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 cache
6
7 import (
8 "go/ast"
9 "go/build/constraint"
10 "go/parser"
11 "go/token"
12 "slices"
13 )
14
15 // isStandaloneFile reports whether a file with the given contents should be
16 // considered a 'standalone main file', meaning a package that consists of only
17 // a single file.
18 func isStandaloneFile(src []byte, standaloneTags []string) bool {
19 f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.PackageClauseOnly|parser.ParseComments)
20 if err != nil {
21 return false
22 }
23
24 if f.Name == nil || f.Name.Name != "main" {
25 return false
26 }
27
28 found := false
29 walkConstraints(f, func(c constraint.Expr) bool {
30 if tag, ok := c.(*constraint.TagExpr); ok {
31 if slices.Contains(standaloneTags, tag.Tag) {
32 found = true
33 return false
34 }
35 }
36 return true
37 })
38
39 return found
40 }
41
42 // walkConstraints calls f for each constraint expression in the file, until
43 // all constraints are exhausted or f returns false.
44 func walkConstraints(file *ast.File, f func(constraint.Expr) bool) {
45 for _, cg := range file.Comments {
46 // Even with PackageClauseOnly the parser consumes the semicolon following
47 // the package clause, so we must guard against comments that come after
48 // the package name.
49 if cg.Pos() > file.Name.Pos() {
50 continue
51 }
52 for _, comment := range cg.List {
53 if c, err := constraint.Parse(comment.Text); err == nil {
54 if !f(c) {
55 return
56 }
57 }
58 }
59 }
60 }