Debian Codegraph @

gopls/internal/cache/parsego/resolver_test.go

raw symbols SCIP
1 // Copyright 2024 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 parsego
6
7 import (
8 "go/ast"
9 "go/types"
10 "os"
11 "strings"
12 "testing"
13
14 "golang.org/x/tools/go/ast/astutil"
15 "golang.org/x/tools/go/packages"
16 "golang.org/x/tools/gopls/internal/util/safetoken"
17 "golang.org/x/tools/internal/testenv"
18 )
19
20 // TestGoplsSourceDoesNotUseObjectResolution verifies that gopls does not
21 // read fields that are set during syntactic object resolution, except in
22 // locations where we can guarantee that object resolution has occurred. This
23 // is achieved via static analysis of gopls source code to find references to
24 // the legacy Object symbols, checking the results against an allowlist
25 //
26 // Reading these fields would introduce a data race, due to the lazy
27 // resolution implemented by File.Resolve.
28 func TestGoplsSourceDoesNotUseObjectResolution(t *testing.T) {
29
30 testenv.NeedsGoPackages(t)
31 testenv.NeedsLocalXTools(t)
32
33 cfg := &packages.Config{
34 Mode: packages.NeedName | packages.NeedModule | packages.NeedCompiledGoFiles | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedImports | packages.NeedDeps,
35 }
36 cfg.Env = os.Environ()
37 cfg.Env = append(cfg.Env,
38 "GOPACKAGESDRIVER=off",
39 "GOWORK=off", // necessary for -mod=mod below
40 "GOFLAGS=-mod=mod",
41 )
42
43 pkgs, err := packages.Load(cfg,
44 "go/ast",
45 "golang.org/x/tools/go/ast/astutil",
46 "golang.org/x/tools/gopls/...")
47
48 if err != nil {
49 t.Fatal(err)
50 }
51 var astPkg, astutilPkg *packages.Package
52 for _, pkg := range pkgs {
53 switch pkg.PkgPath {
54 case "go/ast":
55 astPkg = pkg
56 case "golang.org/x/tools/go/ast/astutil":
57 astutilPkg = pkg
58 }
59 }
60 if astPkg == nil {
61 t.Fatal("missing package go/ast")
62 }
63 if astutilPkg == nil {
64 t.Fatal("missing package golang.org/x/tools/go/ast/astutil")
65 }
66
67 File := astPkg.Types.Scope().Lookup("File").Type()
68 Ident := astPkg.Types.Scope().Lookup("Ident").Type()
69
70 Scope, _, _ := types.LookupFieldOrMethod(File, true, astPkg.Types, "Scope")
71 assert(Scope != nil, "nil Scope")
72 Unresolved, _, _ := types.LookupFieldOrMethod(File, true, astPkg.Types, "Unresolved")
73 assert(Unresolved != nil, "nil unresolved")
74 Obj, _, _ := types.LookupFieldOrMethod(Ident, true, astPkg.Types, "Obj")
75 assert(Obj != nil, "nil Obj")
76 UsesImport := astutilPkg.Types.Scope().Lookup("UsesImport")
77 assert(UsesImport != nil, "nil UsesImport")
78
79 disallowed := map[types.Object]bool{
80 Scope: true,
81 Unresolved: true,
82 Obj: true,
83 UsesImport: true,
84 }
85
86 // exceptions catalogues packages or declarations that are allowed to use
87 // forbidden symbols, with a rationale.
88 //
89 // - If the exception ends with '/', it is a prefix.
90 // - If it ends with a qualified name, it is a declaration.
91 // - Otherwise, it is an exact package path.
92 //
93 // TODO(rfindley): some sort of callgraph analysis would make these
94 // exceptions much easier to maintain.
95 exceptions := []string{
96 "golang.org/x/tools/go/analysis/passes/", // analyzers may rely on object resolution
97 "golang.org/x/tools/gopls/internal/analysis/simplifyslice", // restrict ourselves to one blessed analyzer
98 "golang.org/x/tools/gopls/internal/cache/parsego", // used by parsego.File.Resolve, of course
99 "golang.org/x/tools/gopls/internal/golang.builtinDecl", // the builtin file is resolved
100 "golang.org/x/tools/gopls/internal/golang.NewBuiltinSignature", // ditto
101 "golang.org/x/tools/gopls/internal/golang/completion.builtinArgKind", // ditto
102 "golang.org/x/tools/internal/imports", // goimports does its own parsing
103 "golang.org/x/tools/go/ast/astutil.UsesImport", // disallowed
104 "golang.org/x/tools/go/ast/astutil.isTopName", // only reached from astutil.UsesImport
105 "go/ast",
106 "go/parser",
107 "go/doc", // manually verified that our usage is safe
108 }
109
110 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
111 for _, exception := range exceptions {
112 if strings.HasSuffix(exception, "/") {
113 if strings.HasPrefix(pkg.PkgPath, exception) {
114 return
115 }
116 } else if pkg.PkgPath == exception {
117 return
118 }
119 }
120
121 searchUses:
122 for ident, obj := range pkg.TypesInfo.Uses {
123 if disallowed[obj] {
124 decl := findEnclosingFuncDecl(ident, pkg)
125 if decl == "" {
126 posn := safetoken.Position(pkg.Fset.File(ident.Pos()), ident.Pos())
127 t.Fatalf("%s: couldn't find enclosing decl for use of %s", posn, ident.Name)
128 }
129 qualified := pkg.PkgPath + "." + decl
130 for _, exception := range exceptions {
131 if exception == qualified {
132 continue searchUses
133 }
134 }
135 posn := safetoken.StartPosition(pkg.Fset, ident.Pos())
136 t.Errorf("%s: forbidden use of %v in %s", posn, obj, qualified)
137 }
138 }
139 })
140 }
141
142 // findEnclosingFuncDecl finds the name of the func decl enclosing the usage,
143 // or "".
144 //
145 // (Usage could theoretically exist in e.g. var initializers, but that would be
146 // odd.)
147 func findEnclosingFuncDecl(ident *ast.Ident, pkg *packages.Package) string {
148 for _, file := range pkg.Syntax {
149 if file.FileStart <= ident.Pos() && ident.Pos() < file.FileEnd {
150 path, _ := astutil.PathEnclosingInterval(file, ident.Pos(), ident.End())
151 decl, ok := path[len(path)-2].(*ast.FuncDecl)
152 if ok {
153 return decl.Name.Name
154 }
155 }
156 }
157 return ""
158 }