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