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.
7 // This file defines tests of source-level debugging utilities.
22 "golang.org/x/tools/go/ast/astutil"
23 "golang.org/x/tools/go/expect"
24 "golang.org/x/tools/go/loader"
25 "golang.org/x/tools/go/ssa"
26 "golang.org/x/tools/go/ssa/ssautil"
29 func TestObjValueLookup(t *testing.T) {
30 if runtime.GOOS == "android" {
31 t.Skipf("no testdata directory on %s", runtime.GOOS)
34 conf := loader.Config{ParserMode: parser.ParseComments}
35 src, err := ioutil.ReadFile("testdata/objlookup.go")
39 readFile := func(filename string) ([]byte, error) { return src, nil }
40 f, err := conf.ParseFile("testdata/objlookup.go", src)
44 conf.CreateFromFiles("main", f)
46 // Maps each var Ident (represented "name:linenum") to the
47 // kind of ssa.Value we expect (represented "Constant", "&Alloc").
48 expectations := make(map[string]string)
50 // Each note of the form @ssa(x, "BinOp") in testdata/objlookup.go
51 // specifies an expectation that an object named x declared on the
52 // same line is associated with an an ssa.Value of type *ssa.BinOp.
53 notes, err := expect.ExtractGo(conf.Fset, f)
57 for _, n := range notes {
59 t.Errorf("%v: unexpected note type %q, want \"ssa\"", conf.Fset.Position(n.Pos), n.Name)
63 t.Errorf("%v: ssa has %d args, want 2", conf.Fset.Position(n.Pos), len(n.Args))
66 ident, ok := n.Args[0].(expect.Identifier)
68 t.Errorf("%v: got %v for arg 1, want identifier", conf.Fset.Position(n.Pos), n.Args[0])
71 exp, ok := n.Args[1].(string)
73 t.Errorf("%v: got %v for arg 2, want string", conf.Fset.Position(n.Pos), n.Args[1])
76 p, _, err := expect.MatchBefore(conf.Fset, readFile, n.Pos, string(ident))
81 pos := conf.Fset.Position(p)
82 key := fmt.Sprintf("%s:%d", ident, pos.Line)
83 expectations[key] = exp
86 iprog, err := conf.Load()
92 prog := ssautil.CreateProgram(iprog, 0 /*|ssa.PrintFunctions*/)
93 mainInfo := iprog.Created[0]
94 mainPkg := prog.Package(mainInfo.Pkg)
95 mainPkg.SetDebugMode(true)
98 var varIds []*ast.Ident
99 var varObjs []*types.Var
100 for id, obj := range mainInfo.Defs {
101 // Check invariants for func and const objects.
102 switch obj := obj.(type) {
104 checkFuncValue(t, prog, obj)
107 checkConstValue(t, prog, obj)
113 varIds = append(varIds, id)
114 varObjs = append(varObjs, obj)
117 for id, obj := range mainInfo.Uses {
118 if obj, ok := obj.(*types.Var); ok {
119 varIds = append(varIds, id)
120 varObjs = append(varObjs, obj)
124 // Check invariants for var objects.
125 // The result varies based on the specific Ident.
126 for i, id := range varIds {
128 ref, _ := astutil.PathEnclosingInterval(f, id.Pos(), id.Pos())
129 pos := prog.Fset.Position(id.Pos())
130 exp := expectations[fmt.Sprintf("%s:%d", id.Name, pos.Line)]
132 t.Errorf("%s: no expectation for var ident %s ", pos, id.Name)
140 checkVarValue(t, prog, mainPkg, ref, obj, exp, wantAddr)
144 func checkFuncValue(t *testing.T, prog *ssa.Program, obj *types.Func) {
145 fn := prog.FuncValue(obj)
146 // fmt.Printf("FuncValue(%s) = %s\n", obj, fn) // debugging
148 if obj.Name() != "interfaceMethod" {
149 t.Errorf("FuncValue(%s) == nil", obj)
153 if fnobj := fn.Object(); fnobj != obj {
154 t.Errorf("FuncValue(%s).Object() == %s; value was %s",
155 obj, fnobj, fn.Name())
158 if !types.Identical(fn.Type(), obj.Type()) {
159 t.Errorf("FuncValue(%s).Type() == %s", obj, fn.Type())
164 func checkConstValue(t *testing.T, prog *ssa.Program, obj *types.Const) {
165 c := prog.ConstValue(obj)
166 // fmt.Printf("ConstValue(%s) = %s\n", obj, c) // debugging
168 t.Errorf("ConstValue(%s) == nil", obj)
171 if !types.Identical(c.Type(), obj.Type()) {
172 t.Errorf("ConstValue(%s).Type() == %s", obj, c.Type())
175 if obj.Name() != "nil" {
176 if !constant.Compare(c.Value, token.EQL, obj.Val()) {
177 t.Errorf("ConstValue(%s).Value (%s) != %s",
178 obj, c.Value, obj.Val())
184 func checkVarValue(t *testing.T, prog *ssa.Program, pkg *ssa.Package, ref []ast.Node, obj *types.Var, expKind string, wantAddr bool) {
185 // The prefix of all assertions messages.
186 prefix := fmt.Sprintf("VarValue(%s @ L%d)",
187 obj, prog.Fset.Position(ref[0].Pos()).Line)
189 v, gotAddr := prog.VarValue(obj, pkg, ref)
191 // Kind is the concrete type of the ssa Value.
194 gotKind = fmt.Sprintf("%T", v)[len("*ssa."):]
197 // fmt.Printf("%s = %v (kind %q; expect %q) wantAddr=%t gotAddr=%t\n", prefix, v, gotKind, expKind, wantAddr, gotAddr) // debugging
199 // Check the kinds match.
200 // "nil" indicates expected failure (e.g. optimized away).
201 if expKind != gotKind {
202 t.Errorf("%s concrete type == %s, want %s", prefix, gotKind, expKind)
205 // Check the types match.
206 // If wantAddr, the expected type is the object's address.
208 expType := obj.Type()
210 expType = types.NewPointer(expType)
212 t.Errorf("%s: got value, want address", prefix)
215 t.Errorf("%s: got address, want value", prefix)
217 if !types.Identical(v.Type(), expType) {
218 t.Errorf("%s.Type() == %s, want %s", prefix, v.Type(), expType)
223 // Ensure that, in debug mode, we can determine the ssa.Value
224 // corresponding to every ast.Expr.
225 func TestValueForExpr(t *testing.T) {
226 testValueForExpr(t, "testdata/valueforexpr.go")
229 func testValueForExpr(t *testing.T, testfile string) {
230 if runtime.GOOS == "android" {
231 t.Skipf("no testdata dir on %s", runtime.GOOS)
234 conf := loader.Config{ParserMode: parser.ParseComments}
235 f, err := conf.ParseFile(testfile, nil)
240 conf.CreateFromFiles("main", f)
242 iprog, err := conf.Load()
248 mainInfo := iprog.Created[0]
250 prog := ssautil.CreateProgram(iprog, 0)
251 mainPkg := prog.Package(mainInfo.Pkg)
252 mainPkg.SetDebugMode(true)
257 for _, mem := range mainPkg.Members {
258 if fn, ok := mem.(*ssa.Function); ok {
259 fn.WriteTo(os.Stderr)
264 var parenExprs []*ast.ParenExpr
265 ast.Inspect(f, func(n ast.Node) bool {
267 if e, ok := n.(*ast.ParenExpr); ok {
268 parenExprs = append(parenExprs, e)
274 notes, err := expect.ExtractGo(prog.Fset, f)
278 for _, n := range notes {
283 position := prog.Fset.Position(n.Pos)
285 for _, paren := range parenExprs {
286 if paren.Pos() > n.Pos {
292 t.Errorf("%s: note doesn't precede ParenExpr: %q", position, want)
296 path, _ := astutil.PathEnclosingInterval(f, n.Pos, n.Pos)
298 t.Errorf("%s: can't find AST path from root to comment: %s", position, want)
302 fn := ssa.EnclosingFunction(mainPkg, path)
304 t.Errorf("%s: can't find enclosing function", position)
308 v, gotAddr := fn.ValueForExpr(e) // (may be nil)
309 got := strings.TrimPrefix(fmt.Sprintf("%T", v), "*ssa.")
311 t.Errorf("%s: got value %q, want %q", position, got, want)
316 T = T.Underlying().(*types.Pointer).Elem() // deref
318 if !types.Identical(T, mainInfo.TypeOf(e)) {
319 t.Errorf("%s: got type %s, want %s", position, mainInfo.TypeOf(e), T)
325 // findInterval parses input and returns the [start, end) positions of
326 // the first occurrence of substr in input. f==nil indicates failure;
327 // an error has already been reported in that case.
329 func findInterval(t *testing.T, fset *token.FileSet, input, substr string) (f *ast.File, start, end token.Pos) {
330 f, err := parser.ParseFile(fset, "<input>", input, 0)
332 t.Errorf("parse error: %s", err)
336 i := strings.Index(input, substr)
338 t.Errorf("%q is not a substring of input", substr)
343 filePos := fset.File(f.Package)
344 return f, filePos.Pos(i), filePos.Pos(i + len(substr))
347 func TestEnclosingFunction(t *testing.T) {
349 input string // the input file
350 substr string // first occurrence of this string denotes interval
351 fn string // name of expected containing function
353 // We use distinctive numbers as syntactic landmarks.
355 // Ordinary function:
357 func f() { println(1003) }`,
362 func (t T) f() { println(200) }`,
363 "200", "(main.T).f"},
366 func f() { println(func() { print(300) }) }`,
370 func f() { println(func() { print(func() { print(350) })})}`,
371 "350", "main.f$1$1"},
372 // Implicit init for package-level var initializer.
373 {"package main; var a = 400", "400", "main.init"},
374 // No code for constants:
375 {"package main; const a = 500", "500", "(none)"},
377 {"package main; func init() { println(600) }", "600", "main.init#1"},
378 // Multiple explicit init functions:
380 func init() { println("foo") }
381 func init() { println(800) }`,
382 "800", "main.init#2"},
383 // init() containing FuncLit.
385 func init() { println(func(){print(900)}) }`,
386 "900", "main.init#1$1"},
388 for _, test := range tests {
389 conf := loader.Config{Fset: token.NewFileSet()}
390 f, start, end := findInterval(t, conf.Fset, test.input, test.substr)
394 path, exact := astutil.PathEnclosingInterval(f, start, end)
396 t.Errorf("EnclosingFunction(%q) not exact", test.substr)
400 conf.CreateFromFiles("main", f)
402 iprog, err := conf.Load()
407 prog := ssautil.CreateProgram(iprog, 0)
408 pkg := prog.Package(iprog.Created[0].Pkg)
412 fn := ssa.EnclosingFunction(pkg, path)
418 t.Errorf("EnclosingFunction(%q in %q) got %s, want %s",
419 test.substr, test.input, name, test.fn)
423 // While we're here: test HasEnclosingFunction.
424 if has := ssa.HasEnclosingFunction(pkg, path); has != (fn != nil) {
425 t.Errorf("HasEnclosingFunction(%q in %q) got %v, want %v",
426 test.substr, test.input, has, fn != nil)