Debian Codegraph @

go/ssa/source_test.go

raw symbols SCIP
1 // Copyright 2013 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 ssa_test
6
7 // This file defines tests of source-level debugging utilities.
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 "go/types"
15 "os"
16 "runtime"
17 "strings"
18 "testing"
19
20 "golang.org/x/tools/go/ast/astutil"
21 "golang.org/x/tools/go/ssa"
22 "golang.org/x/tools/internal/expect"
23 "golang.org/x/tools/internal/testenv"
24 )
25
26 func TestObjValueLookup(t *testing.T) {
27 if runtime.GOOS == "android" {
28 t.Skipf("no testdata directory on %s", runtime.GOOS)
29 }
30
31 src, err := os.ReadFile("testdata/objlookup.go")
32 if err != nil {
33 t.Fatal(err)
34 }
35 readFile := func(filename string) ([]byte, error) { return src, nil }
36
37 var (
38 mode = ssa.GlobalDebug /*|ssa.PrintFunctions*/
39 mainPkg, ppkg = buildPackage(t, string(src), mode)
40 f = ppkg.Syntax[0]
41 tokFile = ppkg.Fset.File(f.Pos())
42 )
43
44 // Maps each var Ident (represented "name:linenum") to the
45 // kind of ssa.Value we expect (represented "Constant", "&Alloc").
46 expectations := make(map[string]string)
47
48 // Each note of the form @ssa(x, "BinOp") in testdata/objlookup.go
49 // specifies an expectation that an object named x declared on the
50 // same line is associated with an ssa.Value of type *ssa.BinOp.
51 notes, err := expect.ExtractGo(tokFile, f)
52 if err != nil {
53 t.Fatal(err)
54 }
55 for _, n := range notes {
56 if n.Name != "ssa" {
57 t.Errorf("%v: unexpected note type %q, want \"ssa\"", tokFile.Position(n.Pos), n.Name)
58 continue
59 }
60 if len(n.Args) != 2 {
61 t.Errorf("%v: ssa has %d args, want 2", tokFile.Position(n.Pos), len(n.Args))
62 continue
63 }
64 ident, ok := n.Args[0].(expect.Identifier)
65 if !ok {
66 t.Errorf("%v: got %v for arg 1, want identifier", tokFile.Position(n.Pos), n.Args[0])
67 continue
68 }
69 exp, ok := n.Args[1].(string)
70 if !ok {
71 t.Errorf("%v: got %v for arg 2, want string", tokFile.Position(n.Pos), n.Args[1])
72 continue
73 }
74 p, _, err := expect.MatchBefore(tokFile, readFile, n.Pos, string(ident))
75 if err != nil {
76 t.Error(err)
77 continue
78 }
79 pos := tokFile.Position(p)
80 key := fmt.Sprintf("%s:%d", ident, pos.Line)
81 expectations[key] = exp
82 }
83
84 var varIds []*ast.Ident
85 var varObjs []*types.Var
86 for id, obj := range ppkg.TypesInfo.Defs {
87 // Check invariants for func and const objects.
88 switch obj := obj.(type) {
89 case *types.Func:
90 checkFuncValue(t, mainPkg.Prog, obj)
91
92 case *types.Const:
93 checkConstValue(t, mainPkg.Prog, obj)
94
95 case *types.Var:
96 if id.Name == "_" {
97 continue
98 }
99 varIds = append(varIds, id)
100 varObjs = append(varObjs, obj)
101 }
102 }
103 for id, obj := range ppkg.TypesInfo.Uses {
104 if obj, ok := obj.(*types.Var); ok {
105 varIds = append(varIds, id)
106 varObjs = append(varObjs, obj)
107 }
108 }
109
110 // Check invariants for var objects.
111 // The result varies based on the specific Ident.
112 for i, id := range varIds {
113 obj := varObjs[i]
114 ref, _ := astutil.PathEnclosingInterval(f, id.Pos(), id.Pos())
115 pos := tokFile.Position(id.Pos())
116 exp := expectations[fmt.Sprintf("%s:%d", id.Name, pos.Line)]
117 if exp == "" {
118 t.Errorf("%s: no expectation for var ident %s ", pos, id.Name)
119 continue
120 }
121 wantAddr := false
122 if exp[0] == '&' {
123 wantAddr = true
124 exp = exp[1:]
125 }
126 checkVarValue(t, mainPkg, ref, obj, exp, wantAddr)
127 }
128 }
129
130 func checkFuncValue(t *testing.T, prog *ssa.Program, obj *types.Func) {
131 fn := prog.FuncValue(obj)
132 // fmt.Printf("FuncValue(%s) = %s\n", obj, fn) // debugging
133 if fn == nil {
134 if obj.Name() != "interfaceMethod" {
135 t.Errorf("FuncValue(%s) == nil", obj)
136 }
137 return
138 }
139 if fnobj := fn.Object(); fnobj != obj {
140 t.Errorf("FuncValue(%s).Object() == %s; value was %s",
141 obj, fnobj, fn.Name())
142 return
143 }
144 if !types.Identical(fn.Type(), obj.Type()) {
145 t.Errorf("FuncValue(%s).Type() == %s", obj, fn.Type())
146 return
147 }
148 }
149
150 func checkConstValue(t *testing.T, prog *ssa.Program, obj *types.Const) {
151 c := prog.ConstValue(obj)
152 // fmt.Printf("ConstValue(%s) = %s\n", obj, c) // debugging
153 if c == nil {
154 t.Errorf("ConstValue(%s) == nil", obj)
155 return
156 }
157 if !types.Identical(c.Type(), obj.Type()) {
158 t.Errorf("ConstValue(%s).Type() == %s", obj, c.Type())
159 return
160 }
161 if obj.Name() != "nil" {
162 if !constant.Compare(c.Value, token.EQL, obj.Val()) {
163 t.Errorf("ConstValue(%s).Value (%s) != %s",
164 obj, c.Value, obj.Val())
165 return
166 }
167 }
168 }
169
170 func checkVarValue(t *testing.T, pkg *ssa.Package, ref []ast.Node, obj *types.Var, expKind string, wantAddr bool) {
171 // The prefix of all assertions messages.
172 prefix := fmt.Sprintf("VarValue(%s @ L%d)",
173 obj, pkg.Prog.Fset.Position(ref[0].Pos()).Line)
174
175 v, gotAddr := pkg.Prog.VarValue(obj, pkg, ref)
176
177 // Kind is the concrete type of the ssa Value.
178 gotKind := "nil"
179 if v != nil {
180 gotKind = fmt.Sprintf("%T", v)[len("*ssa."):]
181 }
182
183 // fmt.Printf("%s = %v (kind %q; expect %q) wantAddr=%t gotAddr=%t\n", prefix, v, gotKind, expKind, wantAddr, gotAddr) // debugging
184
185 // Check the kinds match.
186 // "nil" indicates expected failure (e.g. optimized away).
187 if expKind != gotKind {
188 t.Errorf("%s concrete type == %s, want %s", prefix, gotKind, expKind)
189 }
190
191 // Check the types match.
192 // If wantAddr, the expected type is the object's address.
193 if v != nil {
194 expType := obj.Type()
195 if wantAddr {
196 expType = types.NewPointer(expType)
197 if !gotAddr {
198 t.Errorf("%s: got value, want address", prefix)
199 }
200 } else if gotAddr {
201 t.Errorf("%s: got address, want value", prefix)
202 }
203 if !types.Identical(v.Type(), expType) {
204 t.Errorf("%s.Type() == %s, want %s", prefix, v.Type(), expType)
205 }
206 }
207 }
208
209 // Ensure that, in debug mode, we can determine the ssa.Value
210 // corresponding to every ast.Expr.
211 func TestValueForExpr(t *testing.T) {
212 testValueForExpr(t, "testdata/valueforexpr.go")
213 }
214
215 func TestValueForExprStructConv(t *testing.T) {
216 testValueForExpr(t, "testdata/structconv.go")
217 }
218
219 func testValueForExpr(t *testing.T, testfile string) {
220 if runtime.GOOS == "android" {
221 t.Skipf("no testdata dir on %s", runtime.GOOS)
222 }
223
224 src, err := os.ReadFile(testfile)
225 if err != nil {
226 t.Fatal(err)
227 }
228
229 var (
230 mode = ssa.GlobalDebug /*|ssa.PrintFunctions*/
231 mainPkg, ppkg = buildPackage(t, string(src), mode)
232 file = ppkg.Syntax[0]
233 tokFile = ppkg.Fset.File(file.Pos())
234 )
235
236 if false {
237 // debugging
238 for _, mem := range mainPkg.Members {
239 if fn, ok := mem.(*ssa.Function); ok {
240 fn.WriteTo(os.Stderr)
241 }
242 }
243 }
244
245 var parenExprs []*ast.ParenExpr
246 ast.Inspect(file, func(n ast.Node) bool {
247 if n != nil {
248 if e, ok := n.(*ast.ParenExpr); ok {
249 parenExprs = append(parenExprs, e)
250 }
251 }
252 return true
253 })
254
255 notes, err := expect.ExtractGo(tokFile, file)
256 if err != nil {
257 t.Fatal(err)
258 }
259 for _, n := range notes {
260 want := n.Name
261 if want == "nil" {
262 want = "<nil>"
263 }
264 position := tokFile.Position(n.Pos)
265 var e ast.Expr
266 for _, paren := range parenExprs {
267 if paren.Pos() > n.Pos {
268 e = paren.X
269 break
270 }
271 }
272 if e == nil {
273 t.Errorf("%s: note doesn't precede ParenExpr: %q", position, want)
274 continue
275 }
276
277 path, _ := astutil.PathEnclosingInterval(file, n.Pos, n.Pos)
278 if path == nil {
279 t.Errorf("%s: can't find AST path from root to comment: %s", position, want)
280 continue
281 }
282
283 fn := ssa.EnclosingFunction(mainPkg, path)
284 if fn == nil {
285 t.Errorf("%s: can't find enclosing function", position)
286 continue
287 }
288
289 v, gotAddr := fn.ValueForExpr(e) // (may be nil)
290 got := strings.TrimPrefix(fmt.Sprintf("%T", v), "*ssa.")
291 if got != want {
292 t.Errorf("%s: got value %q, want %q", position, got, want)
293 }
294 if v != nil {
295 T := v.Type()
296 if gotAddr {
297 T = T.Underlying().(*types.Pointer).Elem() // deref
298 }
299 if etyp := ppkg.TypesInfo.TypeOf(e); !types.Identical(T, etyp) {
300 t.Errorf("%s: got type %s, want %s", position, etyp, T)
301 }
302 }
303 }
304 }
305
306 func TestEnclosingFunction(t *testing.T) {
307 type testcase struct {
308 desc string
309 input string // the input file
310 substr string // first occurrence of this string denotes interval
311 fn string // name of expected containing function
312 }
313 tests := []testcase{
314 // We use distinctive numbers as syntactic landmarks.
315 {"Ordinary function", `
316 package main
317 func f() { println(1003) }`,
318 "100", "main.f"},
319 {"Methods", `
320 package main
321 type T int
322 func (t T) f() { println(200) }`,
323 "200", "(main.T).f"},
324 {"Function literal", `
325 package main
326 func f() { println(func() { print(300) }) }`,
327 "300", "main.f$1"},
328 {"Doubly nested", `
329 package main
330 func f() { println(func() { print(func() { print(350) })})}`,
331 "350", "main.f$1$1"},
332 {"Implicit init for package-level var initializer", `
333 package main; var a = 400`,
334 "400", "main.init"},
335 {"No code for constants", "package main; const a = 500", "500", "(none)"},
336 {" Explicit init", "package main; func init() { println(600) }", "600", "main.init#1"},
337 {"Multiple explicit init functions", `
338 package main
339 func init() { println("foo") }
340 func init() { println(800) }`,
341 "800", "main.init#2"},
342 {"init containing FuncLit", `
343 package main
344 func init() { println(func(){print(900)}) }`,
345 "900", "main.init#1$1"},
346 {"generic", `
347 package main
348 type S[T any] struct{}
349 func (*S[T]) Foo() { println(1000) }
350 type P[T any] struct{ *S[T] }`,
351 "1000", "(*main.S[T]).Foo",
352 },
353 }
354 if testenv.Go1Point() >= 27 {
355 tests = append(tests, testcase{
356 "generic method", `
357 package main
358 type S struct{}
359 func (S) Foo[T any]() { println(1100) }
360 type P[T any] struct{ S }`,
361 "1100", "(main.S).Foo",
362 })
363 }
364 for _, test := range tests {
365 t.Run(test.desc, func(t *testing.T) {
366 pkg, ppkg := buildPackage(t, test.input, ssa.BuilderMode(0))
367 fset, file := ppkg.Fset, ppkg.Syntax[0]
368
369 // Find [start,end) positions of the first occurrence of substr in file.
370 index := strings.Index(test.input, test.substr)
371 if index < 0 {
372 t.Fatalf("%q is not a substring of input", test.substr)
373 }
374 filePos := fset.File(file.Package)
375 start, end := filePos.Pos(index), filePos.Pos(index+len(test.substr))
376
377 path, exact := astutil.PathEnclosingInterval(file, start, end)
378 if !exact {
379 t.Fatalf("PathEnclosingInterval(%q) not exact", test.substr)
380 }
381
382 name := "(none)"
383 fn := ssa.EnclosingFunction(pkg, path)
384 if fn != nil {
385 name = fn.String()
386 }
387
388 if name != test.fn {
389 t.Errorf("EnclosingFunction(%q in %q) got %s, want %s",
390 test.substr, test.input, name, test.fn)
391 }
392
393 // While we're here: test HasEnclosingFunction.
394 if has := ssa.HasEnclosingFunction(pkg, path); has != (fn != nil) {
395 t.Errorf("HasEnclosingFunction(%q in %q) got %v, want %v",
396 test.substr, test.input, has, fn != nil)
397 }
398 })
399 }
400 }