github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/go/types/api_test.go (about)

     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 types_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/importer"
    12  	"go/parser"
    13  	"go/token"
    14  	"internal/testenv"
    15  	"reflect"
    16  	"regexp"
    17  	"strings"
    18  	"testing"
    19  
    20  	. "go/types"
    21  )
    22  
    23  func pkgFor(path, source string, info *Info) (*Package, error) {
    24  	fset := token.NewFileSet()
    25  	f, err := parser.ParseFile(fset, path, source, 0)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	conf := Config{Importer: importer.Default()}
    31  	return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
    32  }
    33  
    34  func mustTypecheck(t *testing.T, path, source string, info *Info) string {
    35  	pkg, err := pkgFor(path, source, info)
    36  	if err != nil {
    37  		name := path
    38  		if pkg != nil {
    39  			name = "package " + pkg.Name()
    40  		}
    41  		t.Fatalf("%s: didn't type-check (%s)", name, err)
    42  	}
    43  	return pkg.Name()
    44  }
    45  
    46  func TestValuesInfo(t *testing.T) {
    47  	var tests = []struct {
    48  		src  string
    49  		expr string // constant expression
    50  		typ  string // constant type
    51  		val  string // constant value
    52  	}{
    53  		{`package a0; const _ = false`, `false`, `untyped bool`, `false`},
    54  		{`package a1; const _ = 0`, `0`, `untyped int`, `0`},
    55  		{`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
    56  		{`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
    57  		{`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
    58  		{`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
    59  
    60  		{`package b0; var _ = false`, `false`, `bool`, `false`},
    61  		{`package b1; var _ = 0`, `0`, `int`, `0`},
    62  		{`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
    63  		{`package b3; var _ = 0.`, `0.`, `float64`, `0`},
    64  		{`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
    65  		{`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
    66  
    67  		{`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
    68  		{`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
    69  		{`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
    70  
    71  		{`package c1a; var _ = int(0)`, `0`, `int`, `0`},
    72  		{`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
    73  		{`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
    74  
    75  		{`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
    76  		{`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
    77  		{`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
    78  
    79  		{`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
    80  		{`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
    81  		{`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
    82  
    83  		{`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
    84  		{`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
    85  		{`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
    86  
    87  		{`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
    88  		{`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
    89  		{`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
    90  
    91  		{`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
    92  		{`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
    93  		{`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
    94  		{`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
    95  
    96  		{`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
    97  		{`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
    98  		{`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
    99  		{`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
   100  		{`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
   101  		{`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
   102  		{`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
   103  		{`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
   104  
   105  		{`package f0 ; var _ float32 =  1e-200`, `1e-200`, `float32`, `0`},
   106  		{`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
   107  		{`package f2a; var _ float64 =  1e-2000`, `1e-2000`, `float64`, `0`},
   108  		{`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
   109  		{`package f2b; var _         =  1e-2000`, `1e-2000`, `float64`, `0`},
   110  		{`package f3b; var _         = -1e-2000`, `-1e-2000`, `float64`, `0`},
   111  		{`package f4 ; var _ complex64  =  1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
   112  		{`package f5 ; var _ complex64  = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
   113  		{`package f6a; var _ complex128 =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
   114  		{`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
   115  		{`package f6b; var _            =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
   116  		{`package f7b; var _            = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
   117  	}
   118  
   119  	for _, test := range tests {
   120  		info := Info{
   121  			Types: make(map[ast.Expr]TypeAndValue),
   122  		}
   123  		name := mustTypecheck(t, "ValuesInfo", test.src, &info)
   124  
   125  		// look for constant expression
   126  		var expr ast.Expr
   127  		for e := range info.Types {
   128  			if ExprString(e) == test.expr {
   129  				expr = e
   130  				break
   131  			}
   132  		}
   133  		if expr == nil {
   134  			t.Errorf("package %s: no expression found for %s", name, test.expr)
   135  			continue
   136  		}
   137  		tv := info.Types[expr]
   138  
   139  		// check that type is correct
   140  		if got := tv.Type.String(); got != test.typ {
   141  			t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
   142  			continue
   143  		}
   144  
   145  		// check that value is correct
   146  		if got := tv.Value.ExactString(); got != test.val {
   147  			t.Errorf("package %s: got value %s; want %s", name, got, test.val)
   148  		}
   149  	}
   150  }
   151  
   152  func TestTypesInfo(t *testing.T) {
   153  	var tests = []struct {
   154  		src  string
   155  		expr string // expression
   156  		typ  string // value type
   157  	}{
   158  		// single-valued expressions of untyped constants
   159  		{`package b0; var x interface{} = false`, `false`, `bool`},
   160  		{`package b1; var x interface{} = 0`, `0`, `int`},
   161  		{`package b2; var x interface{} = 0.`, `0.`, `float64`},
   162  		{`package b3; var x interface{} = 0i`, `0i`, `complex128`},
   163  		{`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
   164  
   165  		// comma-ok expressions
   166  		{`package p0; var x interface{}; var _, _ = x.(int)`,
   167  			`x.(int)`,
   168  			`(int, bool)`,
   169  		},
   170  		{`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
   171  			`x.(int)`,
   172  			`(int, bool)`,
   173  		},
   174  		{`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
   175  			`m["foo"]`,
   176  			`(complex128, p2a.mybool)`,
   177  		},
   178  		{`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
   179  			`m["foo"]`,
   180  			`(complex128, bool)`,
   181  		},
   182  		{`package p3; var c chan string; var _, _ = <-c`,
   183  			`<-c`,
   184  			`(string, bool)`,
   185  		},
   186  
   187  		// issue 6796
   188  		{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
   189  			`x.(int)`,
   190  			`(int, bool)`,
   191  		},
   192  		{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
   193  			`(<-c)`,
   194  			`(string, bool)`,
   195  		},
   196  		{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
   197  			`<-c`,
   198  			`(string, bool)`,
   199  		},
   200  		{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
   201  			`(<-c)`,
   202  			`(string, bool)`,
   203  		},
   204  		{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
   205  			`(<-c)`,
   206  			`(string, bool)`,
   207  		},
   208  
   209  		// issue 7060
   210  		{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
   211  			`m[0]`,
   212  			`(string, bool)`,
   213  		},
   214  		{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
   215  			`m[0]`,
   216  			`(string, bool)`,
   217  		},
   218  		{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
   219  			`m[0]`,
   220  			`(string, bool)`,
   221  		},
   222  		{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
   223  			`<-ch`,
   224  			`(string, bool)`,
   225  		},
   226  		{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
   227  			`<-ch`,
   228  			`(string, bool)`,
   229  		},
   230  		{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
   231  			`<-ch`,
   232  			`(string, bool)`,
   233  		},
   234  	}
   235  
   236  	for _, test := range tests {
   237  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
   238  		name := mustTypecheck(t, "TypesInfo", test.src, &info)
   239  
   240  		// look for expression type
   241  		var typ Type
   242  		for e, tv := range info.Types {
   243  			if ExprString(e) == test.expr {
   244  				typ = tv.Type
   245  				break
   246  			}
   247  		}
   248  		if typ == nil {
   249  			t.Errorf("package %s: no type found for %s", name, test.expr)
   250  			continue
   251  		}
   252  
   253  		// check that type is correct
   254  		if got := typ.String(); got != test.typ {
   255  			t.Errorf("package %s: got %s; want %s", name, got, test.typ)
   256  		}
   257  	}
   258  }
   259  
   260  func TestImplicitsInfo(t *testing.T) {
   261  	testenv.MustHaveGoBuild(t)
   262  
   263  	var tests = []struct {
   264  		src  string
   265  		want string
   266  	}{
   267  		{`package p2; import . "fmt"; var _ = Println`, ""},           // no Implicits entry
   268  		{`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
   269  		{`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
   270  
   271  		{`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
   272  		{`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
   273  		{`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
   274  		{`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
   275  
   276  		{`package p7; func f(x int) {}`, ""}, // no Implicits entry
   277  		{`package p8; func f(int) {}`, "field: var  int"},
   278  		{`package p9; func f() (complex64) { return 0 }`, "field: var  complex64"},
   279  		{`package p10; type T struct{}; func (*T) f() {}`, "field: var  *p10.T"},
   280  	}
   281  
   282  	for _, test := range tests {
   283  		info := Info{
   284  			Implicits: make(map[ast.Node]Object),
   285  		}
   286  		name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
   287  
   288  		// the test cases expect at most one Implicits entry
   289  		if len(info.Implicits) > 1 {
   290  			t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
   291  			continue
   292  		}
   293  
   294  		// extract Implicits entry, if any
   295  		var got string
   296  		for n, obj := range info.Implicits {
   297  			switch x := n.(type) {
   298  			case *ast.ImportSpec:
   299  				got = "importSpec"
   300  			case *ast.CaseClause:
   301  				got = "caseClause"
   302  			case *ast.Field:
   303  				got = "field"
   304  			default:
   305  				t.Fatalf("package %s: unexpected %T", name, x)
   306  			}
   307  			got += ": " + obj.String()
   308  		}
   309  
   310  		// verify entry
   311  		if got != test.want {
   312  			t.Errorf("package %s: got %q; want %q", name, got, test.want)
   313  		}
   314  	}
   315  }
   316  
   317  func predString(tv TypeAndValue) string {
   318  	var buf bytes.Buffer
   319  	pred := func(b bool, s string) {
   320  		if b {
   321  			if buf.Len() > 0 {
   322  				buf.WriteString(", ")
   323  			}
   324  			buf.WriteString(s)
   325  		}
   326  	}
   327  
   328  	pred(tv.IsVoid(), "void")
   329  	pred(tv.IsType(), "type")
   330  	pred(tv.IsBuiltin(), "builtin")
   331  	pred(tv.IsValue() && tv.Value != nil, "const")
   332  	pred(tv.IsValue() && tv.Value == nil, "value")
   333  	pred(tv.IsNil(), "nil")
   334  	pred(tv.Addressable(), "addressable")
   335  	pred(tv.Assignable(), "assignable")
   336  	pred(tv.HasOk(), "hasOk")
   337  
   338  	if buf.Len() == 0 {
   339  		return "invalid"
   340  	}
   341  	return buf.String()
   342  }
   343  
   344  func TestPredicatesInfo(t *testing.T) {
   345  	testenv.MustHaveGoBuild(t)
   346  
   347  	var tests = []struct {
   348  		src  string
   349  		expr string
   350  		pred string
   351  	}{
   352  		// void
   353  		{`package n0; func f() { f() }`, `f()`, `void`},
   354  
   355  		// types
   356  		{`package t0; type _ int`, `int`, `type`},
   357  		{`package t1; type _ []int`, `[]int`, `type`},
   358  		{`package t2; type _ func()`, `func()`, `type`},
   359  
   360  		// built-ins
   361  		{`package b0; var _ = len("")`, `len`, `builtin`},
   362  		{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
   363  
   364  		// constants
   365  		{`package c0; var _ = 42`, `42`, `const`},
   366  		{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
   367  		{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
   368  
   369  		// values
   370  		{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
   371  		{`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
   372  		{`package v2; var _ = func(){}`, `(func() literal)`, `value`},
   373  		{`package v4; func f() { _ = f }`, `f`, `value`},
   374  		{`package v3; var _ *int = nil`, `nil`, `value, nil`},
   375  		{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
   376  
   377  		// addressable (and thus assignable) operands
   378  		{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
   379  		{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
   380  		{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
   381  		{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
   382  		{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
   383  		{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
   384  		{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
   385  		{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
   386  		// composite literals are not addressable
   387  
   388  		// assignable but not addressable values
   389  		{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
   390  		{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
   391  
   392  		// hasOk expressions
   393  		{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
   394  		{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
   395  
   396  		// missing entries
   397  		// - package names are collected in the Uses map
   398  		// - identifiers being declared are collected in the Defs map
   399  		{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
   400  		{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
   401  		{`package m2; const c = 0`, `c`, `<missing>`},
   402  		{`package m3; type T int`, `T`, `<missing>`},
   403  		{`package m4; var v int`, `v`, `<missing>`},
   404  		{`package m5; func f() {}`, `f`, `<missing>`},
   405  		{`package m6; func _(x int) {}`, `x`, `<missing>`},
   406  		{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
   407  		{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
   408  	}
   409  
   410  	for _, test := range tests {
   411  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
   412  		name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
   413  
   414  		// look for expression predicates
   415  		got := "<missing>"
   416  		for e, tv := range info.Types {
   417  			//println(name, ExprString(e))
   418  			if ExprString(e) == test.expr {
   419  				got = predString(tv)
   420  				break
   421  			}
   422  		}
   423  
   424  		if got != test.pred {
   425  			t.Errorf("package %s: got %s; want %s", name, got, test.pred)
   426  		}
   427  	}
   428  }
   429  
   430  func TestScopesInfo(t *testing.T) {
   431  	testenv.MustHaveGoBuild(t)
   432  
   433  	var tests = []struct {
   434  		src    string
   435  		scopes []string // list of scope descriptors of the form kind:varlist
   436  	}{
   437  		{`package p0`, []string{
   438  			"file:",
   439  		}},
   440  		{`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
   441  			"file:fmt m",
   442  		}},
   443  		{`package p2; func _() {}`, []string{
   444  			"file:", "func:",
   445  		}},
   446  		{`package p3; func _(x, y int) {}`, []string{
   447  			"file:", "func:x y",
   448  		}},
   449  		{`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
   450  			"file:", "func:x y z", // redeclaration of x
   451  		}},
   452  		{`package p5; func _(x, y int) (u, _ int) { return }`, []string{
   453  			"file:", "func:u x y",
   454  		}},
   455  		{`package p6; func _() { { var x int; _ = x } }`, []string{
   456  			"file:", "func:", "block:x",
   457  		}},
   458  		{`package p7; func _() { if true {} }`, []string{
   459  			"file:", "func:", "if:", "block:",
   460  		}},
   461  		{`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
   462  			"file:", "func:", "if:x", "block:y",
   463  		}},
   464  		{`package p9; func _() { switch x := 0; x {} }`, []string{
   465  			"file:", "func:", "switch:x",
   466  		}},
   467  		{`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
   468  			"file:", "func:", "switch:x", "case:y", "case:",
   469  		}},
   470  		{`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
   471  			"file:", "func:t", "type switch:",
   472  		}},
   473  		{`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
   474  			"file:", "func:t", "type switch:t",
   475  		}},
   476  		{`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
   477  			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
   478  		}},
   479  		{`package p14; func _() { select{} }`, []string{
   480  			"file:", "func:",
   481  		}},
   482  		{`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
   483  			"file:", "func:c", "comm:",
   484  		}},
   485  		{`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
   486  			"file:", "func:c", "comm:i x",
   487  		}},
   488  		{`package p17; func _() { for{} }`, []string{
   489  			"file:", "func:", "for:", "block:",
   490  		}},
   491  		{`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
   492  			"file:", "func:n", "for:i", "block:",
   493  		}},
   494  		{`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
   495  			"file:", "func:a", "range:i", "block:",
   496  		}},
   497  		{`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
   498  			"file:", "func:a", "range:i x", "block:",
   499  		}},
   500  	}
   501  
   502  	for _, test := range tests {
   503  		info := Info{Scopes: make(map[ast.Node]*Scope)}
   504  		name := mustTypecheck(t, "ScopesInfo", test.src, &info)
   505  
   506  		// number of scopes must match
   507  		if len(info.Scopes) != len(test.scopes) {
   508  			t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
   509  		}
   510  
   511  		// scope descriptions must match
   512  		for node, scope := range info.Scopes {
   513  			kind := "<unknown node kind>"
   514  			switch node.(type) {
   515  			case *ast.File:
   516  				kind = "file"
   517  			case *ast.FuncType:
   518  				kind = "func"
   519  			case *ast.BlockStmt:
   520  				kind = "block"
   521  			case *ast.IfStmt:
   522  				kind = "if"
   523  			case *ast.SwitchStmt:
   524  				kind = "switch"
   525  			case *ast.TypeSwitchStmt:
   526  				kind = "type switch"
   527  			case *ast.CaseClause:
   528  				kind = "case"
   529  			case *ast.CommClause:
   530  				kind = "comm"
   531  			case *ast.ForStmt:
   532  				kind = "for"
   533  			case *ast.RangeStmt:
   534  				kind = "range"
   535  			}
   536  
   537  			// look for matching scope description
   538  			desc := kind + ":" + strings.Join(scope.Names(), " ")
   539  			found := false
   540  			for _, d := range test.scopes {
   541  				if desc == d {
   542  					found = true
   543  					break
   544  				}
   545  			}
   546  			if !found {
   547  				t.Errorf("package %s: no matching scope found for %s", name, desc)
   548  			}
   549  		}
   550  	}
   551  }
   552  
   553  func TestInitOrderInfo(t *testing.T) {
   554  	var tests = []struct {
   555  		src   string
   556  		inits []string
   557  	}{
   558  		{`package p0; var (x = 1; y = x)`, []string{
   559  			"x = 1", "y = x",
   560  		}},
   561  		{`package p1; var (a = 1; b = 2; c = 3)`, []string{
   562  			"a = 1", "b = 2", "c = 3",
   563  		}},
   564  		{`package p2; var (a, b, c = 1, 2, 3)`, []string{
   565  			"a = 1", "b = 2", "c = 3",
   566  		}},
   567  		{`package p3; var _ = f(); func f() int { return 1 }`, []string{
   568  			"_ = f()", // blank var
   569  		}},
   570  		{`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
   571  			"a = 0", "z = 0", "y = z", "x = y",
   572  		}},
   573  		{`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
   574  			"a, _ = m[0]", // blank var
   575  		}},
   576  		{`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
   577  			"z = 0", "a, b = f()",
   578  		}},
   579  		{`package p7; var (a = func() int { return b }(); b = 1)`, []string{
   580  			"b = 1", "a = (func() int literal)()",
   581  		}},
   582  		{`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
   583  			"c = 1", "a, b = (func() (_, _ int) literal)()",
   584  		}},
   585  		{`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
   586  			"y = 1", "x = T.m",
   587  		}},
   588  		{`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
   589  			"a = 0", "b = 0", "c = 0", "d = c + b",
   590  		}},
   591  		{`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
   592  			"c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
   593  		}},
   594  		// emit an initializer for n:1 initializations only once (not for each node
   595  		// on the lhs which may appear in different order in the dependency graph)
   596  		{`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
   597  			"b = 0", "x, y = m[0]", "a = x",
   598  		}},
   599  		// test case from spec section on package initialization
   600  		{`package p12
   601  
   602  		var (
   603  			a = c + b
   604  			b = f()
   605  			c = f()
   606  			d = 3
   607  		)
   608  
   609  		func f() int {
   610  			d++
   611  			return d
   612  		}`, []string{
   613  			"d = 3", "b = f()", "c = f()", "a = c + b",
   614  		}},
   615  		// test case for issue 7131
   616  		{`package main
   617  
   618  		var counter int
   619  		func next() int { counter++; return counter }
   620  
   621  		var _ = makeOrder()
   622  		func makeOrder() []int { return []int{f, b, d, e, c, a} }
   623  
   624  		var a       = next()
   625  		var b, c    = next(), next()
   626  		var d, e, f = next(), next(), next()
   627  		`, []string{
   628  			"a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
   629  		}},
   630  		// test case for issue 10709
   631  		{`package p13
   632  
   633  		var (
   634  		    v = t.m()
   635  		    t = makeT(0)
   636  		)
   637  
   638  		type T struct{}
   639  
   640  		func (T) m() int { return 0 }
   641  
   642  		func makeT(n int) T {
   643  		    if n > 0 {
   644  		        return makeT(n-1)
   645  		    }
   646  		    return T{}
   647  		}`, []string{
   648  			"t = makeT(0)", "v = t.m()",
   649  		}},
   650  		// test case for issue 10709: same as test before, but variable decls swapped
   651  		{`package p14
   652  
   653  		var (
   654  		    t = makeT(0)
   655  		    v = t.m()
   656  		)
   657  
   658  		type T struct{}
   659  
   660  		func (T) m() int { return 0 }
   661  
   662  		func makeT(n int) T {
   663  		    if n > 0 {
   664  		        return makeT(n-1)
   665  		    }
   666  		    return T{}
   667  		}`, []string{
   668  			"t = makeT(0)", "v = t.m()",
   669  		}},
   670  		// another candidate possibly causing problems with issue 10709
   671  		{`package p15
   672  
   673  		var y1 = f1()
   674  
   675  		func f1() int { return g1() }
   676  		func g1() int { f1(); return x1 }
   677  
   678  		var x1 = 0
   679  
   680  		var y2 = f2()
   681  
   682  		func f2() int { return g2() }
   683  		func g2() int { return x2 }
   684  
   685  		var x2 = 0`, []string{
   686  			"x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
   687  		}},
   688  	}
   689  
   690  	for _, test := range tests {
   691  		info := Info{}
   692  		name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
   693  
   694  		// number of initializers must match
   695  		if len(info.InitOrder) != len(test.inits) {
   696  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
   697  			continue
   698  		}
   699  
   700  		// initializers must match
   701  		for i, want := range test.inits {
   702  			got := info.InitOrder[i].String()
   703  			if got != want {
   704  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
   705  				continue
   706  			}
   707  		}
   708  	}
   709  }
   710  
   711  func TestMultiFileInitOrder(t *testing.T) {
   712  	fset := token.NewFileSet()
   713  	mustParse := func(src string) *ast.File {
   714  		f, err := parser.ParseFile(fset, "main", src, 0)
   715  		if err != nil {
   716  			t.Fatal(err)
   717  		}
   718  		return f
   719  	}
   720  
   721  	fileA := mustParse(`package main; var a = 1`)
   722  	fileB := mustParse(`package main; var b = 2`)
   723  
   724  	// The initialization order must not depend on the parse
   725  	// order of the files, only on the presentation order to
   726  	// the type-checker.
   727  	for _, test := range []struct {
   728  		files []*ast.File
   729  		want  string
   730  	}{
   731  		{[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
   732  		{[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
   733  	} {
   734  		var info Info
   735  		if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
   736  			t.Fatal(err)
   737  		}
   738  		if got := fmt.Sprint(info.InitOrder); got != test.want {
   739  			t.Fatalf("got %s; want %s", got, test.want)
   740  		}
   741  	}
   742  }
   743  
   744  func TestFiles(t *testing.T) {
   745  	var sources = []string{
   746  		"package p; type T struct{}; func (T) m1() {}",
   747  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
   748  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
   749  		"package p",
   750  	}
   751  
   752  	var conf Config
   753  	fset := token.NewFileSet()
   754  	pkg := NewPackage("p", "p")
   755  	var info Info
   756  	check := NewChecker(&conf, fset, pkg, &info)
   757  
   758  	for i, src := range sources {
   759  		filename := fmt.Sprintf("sources%d", i)
   760  		f, err := parser.ParseFile(fset, filename, src, 0)
   761  		if err != nil {
   762  			t.Fatal(err)
   763  		}
   764  		if err := check.Files([]*ast.File{f}); err != nil {
   765  			t.Error(err)
   766  		}
   767  	}
   768  
   769  	// check InitOrder is [x y]
   770  	var vars []string
   771  	for _, init := range info.InitOrder {
   772  		for _, v := range init.Lhs {
   773  			vars = append(vars, v.Name())
   774  		}
   775  	}
   776  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
   777  		t.Errorf("InitOrder == %s, want %s", got, want)
   778  	}
   779  }
   780  
   781  type testImporter map[string]*Package
   782  
   783  func (m testImporter) Import(path string) (*Package, error) {
   784  	if pkg := m[path]; pkg != nil {
   785  		return pkg, nil
   786  	}
   787  	return nil, fmt.Errorf("package %q not found", path)
   788  }
   789  
   790  func TestSelection(t *testing.T) {
   791  	selections := make(map[*ast.SelectorExpr]*Selection)
   792  
   793  	fset := token.NewFileSet()
   794  	imports := make(testImporter)
   795  	conf := Config{Importer: imports}
   796  	makePkg := func(path, src string) {
   797  		f, err := parser.ParseFile(fset, path+".go", src, 0)
   798  		if err != nil {
   799  			t.Fatal(err)
   800  		}
   801  		pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
   802  		if err != nil {
   803  			t.Fatal(err)
   804  		}
   805  		imports[path] = pkg
   806  	}
   807  
   808  	const libSrc = `
   809  package lib
   810  type T float64
   811  const C T = 3
   812  var V T
   813  func F() {}
   814  func (T) M() {}
   815  `
   816  	const mainSrc = `
   817  package main
   818  import "lib"
   819  
   820  type A struct {
   821  	*B
   822  	C
   823  }
   824  
   825  type B struct {
   826  	b int
   827  }
   828  
   829  func (B) f(int)
   830  
   831  type C struct {
   832  	c int
   833  }
   834  
   835  func (C) g()
   836  func (*C) h()
   837  
   838  func main() {
   839  	// qualified identifiers
   840  	var _ lib.T
   841          _ = lib.C
   842          _ = lib.F
   843          _ = lib.V
   844  	_ = lib.T.M
   845  
   846  	// fields
   847  	_ = A{}.B
   848  	_ = new(A).B
   849  
   850  	_ = A{}.C
   851  	_ = new(A).C
   852  
   853  	_ = A{}.b
   854  	_ = new(A).b
   855  
   856  	_ = A{}.c
   857  	_ = new(A).c
   858  
   859  	// methods
   860          _ = A{}.f
   861          _ = new(A).f
   862          _ = A{}.g
   863          _ = new(A).g
   864          _ = new(A).h
   865  
   866          _ = B{}.f
   867          _ = new(B).f
   868  
   869          _ = C{}.g
   870          _ = new(C).g
   871          _ = new(C).h
   872  
   873  	// method expressions
   874          _ = A.f
   875          _ = (*A).f
   876          _ = B.f
   877          _ = (*B).f
   878  }`
   879  
   880  	wantOut := map[string][2]string{
   881  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
   882  
   883  		"A{}.B":    {"field (main.A) B *main.B", ".[0]"},
   884  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
   885  		"A{}.C":    {"field (main.A) C main.C", ".[1]"},
   886  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
   887  		"A{}.b":    {"field (main.A) b int", "->[0 0]"},
   888  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
   889  		"A{}.c":    {"field (main.A) c int", ".[1 0]"},
   890  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
   891  
   892  		"A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
   893  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
   894  		"A{}.g":    {"method (main.A) g()", ".[1 0]"},
   895  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
   896  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
   897  		"B{}.f":    {"method (main.B) f(int)", ".[0]"},
   898  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
   899  		"C{}.g":    {"method (main.C) g()", ".[0]"},
   900  		"new(C).g": {"method (*main.C) g()", "->[0]"},
   901  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
   902  
   903  		"A.f":    {"method expr (main.A) f(main.A, int)", "->[0 0]"},
   904  		"(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
   905  		"B.f":    {"method expr (main.B) f(main.B, int)", ".[0]"},
   906  		"(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
   907  	}
   908  
   909  	makePkg("lib", libSrc)
   910  	makePkg("main", mainSrc)
   911  
   912  	for e, sel := range selections {
   913  		_ = sel.String() // assertion: must not panic
   914  
   915  		start := fset.Position(e.Pos()).Offset
   916  		end := fset.Position(e.End()).Offset
   917  		syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
   918  
   919  		direct := "."
   920  		if sel.Indirect() {
   921  			direct = "->"
   922  		}
   923  		got := [2]string{
   924  			sel.String(),
   925  			fmt.Sprintf("%s%v", direct, sel.Index()),
   926  		}
   927  		want := wantOut[syntax]
   928  		if want != got {
   929  			t.Errorf("%s: got %q; want %q", syntax, got, want)
   930  		}
   931  		delete(wantOut, syntax)
   932  
   933  		// We must explicitly assert properties of the
   934  		// Signature's receiver since it doesn't participate
   935  		// in Identical() or String().
   936  		sig, _ := sel.Type().(*Signature)
   937  		if sel.Kind() == MethodVal {
   938  			got := sig.Recv().Type()
   939  			want := sel.Recv()
   940  			if !Identical(got, want) {
   941  				t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
   942  			}
   943  		} else if sig != nil && sig.Recv() != nil {
   944  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
   945  		}
   946  	}
   947  	// Assert that all wantOut entries were used exactly once.
   948  	for syntax := range wantOut {
   949  		t.Errorf("no ast.Selection found with syntax %q", syntax)
   950  	}
   951  }
   952  
   953  func TestIssue8518(t *testing.T) {
   954  	fset := token.NewFileSet()
   955  	imports := make(testImporter)
   956  	conf := Config{
   957  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
   958  		Importer: imports,
   959  	}
   960  	makePkg := func(path, src string) {
   961  		f, err := parser.ParseFile(fset, path, src, 0)
   962  		if err != nil {
   963  			t.Fatal(err)
   964  		}
   965  		pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
   966  		imports[path] = pkg
   967  	}
   968  
   969  	const libSrc = `
   970  package a
   971  import "missing"
   972  const C1 = foo
   973  const C2 = missing.C
   974  `
   975  
   976  	const mainSrc = `
   977  package main
   978  import "a"
   979  var _ = a.C1
   980  var _ = a.C2
   981  `
   982  
   983  	makePkg("a", libSrc)
   984  	makePkg("main", mainSrc) // don't crash when type-checking this package
   985  }
   986  
   987  func TestLookupFieldOrMethod(t *testing.T) {
   988  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
   989  	// addressable value, and x for a non-addressable value (even though a variable
   990  	// for ease of test case writing).
   991  	var tests = []struct {
   992  		src      string
   993  		found    bool
   994  		index    []int
   995  		indirect bool
   996  	}{
   997  		// field lookups
   998  		{"var x T; type T struct{}", false, nil, false},
   999  		{"var x T; type T struct{ f int }", true, []int{0}, false},
  1000  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
  1001  
  1002  		// method lookups
  1003  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
  1004  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
  1005  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
  1006  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
  1007  
  1008  		// collisions
  1009  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
  1010  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
  1011  
  1012  		// outside methodset
  1013  		// (*T).f method exists, but value of type T is not addressable
  1014  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
  1015  	}
  1016  
  1017  	for _, test := range tests {
  1018  		pkg, err := pkgFor("test", "package p;"+test.src, nil)
  1019  		if err != nil {
  1020  			t.Errorf("%s: incorrect test case: %s", test.src, err)
  1021  			continue
  1022  		}
  1023  
  1024  		obj := pkg.Scope().Lookup("a")
  1025  		if obj == nil {
  1026  			if obj = pkg.Scope().Lookup("x"); obj == nil {
  1027  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
  1028  				continue
  1029  			}
  1030  		}
  1031  
  1032  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
  1033  		if (f != nil) != test.found {
  1034  			if f == nil {
  1035  				t.Errorf("%s: got no object; want one", test.src)
  1036  			} else {
  1037  				t.Errorf("%s: got object = %v; want none", test.src, f)
  1038  			}
  1039  		}
  1040  		if !sameSlice(index, test.index) {
  1041  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
  1042  		}
  1043  		if indirect != test.indirect {
  1044  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
  1045  		}
  1046  	}
  1047  }
  1048  
  1049  func sameSlice(a, b []int) bool {
  1050  	if len(a) != len(b) {
  1051  		return false
  1052  	}
  1053  	for i, x := range a {
  1054  		if x != b[i] {
  1055  			return false
  1056  		}
  1057  	}
  1058  	return true
  1059  }
  1060  
  1061  // TestScopeLookupParent ensures that (*Scope).LookupParent returns
  1062  // the correct result at various positions with the source.
  1063  func TestScopeLookupParent(t *testing.T) {
  1064  	fset := token.NewFileSet()
  1065  	imports := make(testImporter)
  1066  	conf := Config{Importer: imports}
  1067  	mustParse := func(src string) *ast.File {
  1068  		f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
  1069  		if err != nil {
  1070  			t.Fatal(err)
  1071  		}
  1072  		return f
  1073  	}
  1074  	var info Info
  1075  	makePkg := func(path string, files ...*ast.File) {
  1076  		var err error
  1077  		imports[path], err = conf.Check(path, fset, files, &info)
  1078  		if err != nil {
  1079  			t.Fatal(err)
  1080  		}
  1081  	}
  1082  
  1083  	makePkg("lib", mustParse("package lib; var X int"))
  1084  	// Each /*name=kind:line*/ comment makes the test look up the
  1085  	// name at that point and checks that it resolves to a decl of
  1086  	// the specified kind and line number.  "undef" means undefined.
  1087  	mainSrc := `
  1088  /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
  1089  package main
  1090  
  1091  import "lib"
  1092  import . "lib"
  1093  
  1094  const Pi = 3.1415
  1095  type T struct{}
  1096  var Y, _ = lib.X, X
  1097  
  1098  func F(){
  1099  	const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
  1100  	type /*t=undef*/ t /*t=typename:14*/ *t
  1101  	print(Y) /*Y=var:10*/
  1102  	x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
  1103  	var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
  1104  
  1105  	var a []int
  1106  	for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
  1107  
  1108  	var i interface{}
  1109  	switch y := i.(type) { /*y=undef*/
  1110  	case /*y=undef*/ int /*y=var:23*/ :
  1111  	case float32, /*y=undef*/ float64 /*y=var:23*/ :
  1112  	default /*y=var:23*/:
  1113  		println(y)
  1114  	}
  1115  	/*y=undef*/
  1116  
  1117          switch int := i.(type) {
  1118          case /*int=typename:0*/ int /*int=var:31*/ :
  1119          	println(int)
  1120          default /*int=var:31*/ :
  1121          }
  1122  }
  1123  /*main=undef*/
  1124  `
  1125  
  1126  	info.Uses = make(map[*ast.Ident]Object)
  1127  	f := mustParse(mainSrc)
  1128  	makePkg("main", f)
  1129  	mainScope := imports["main"].Scope()
  1130  	rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
  1131  	for _, group := range f.Comments {
  1132  		for _, comment := range group.List {
  1133  			// Parse the assertion in the comment.
  1134  			m := rx.FindStringSubmatch(comment.Text)
  1135  			if m == nil {
  1136  				t.Errorf("%s: bad comment: %s",
  1137  					fset.Position(comment.Pos()), comment.Text)
  1138  				continue
  1139  			}
  1140  			name, want := m[1], m[2]
  1141  
  1142  			// Look up the name in the innermost enclosing scope.
  1143  			inner := mainScope.Innermost(comment.Pos())
  1144  			if inner == nil {
  1145  				t.Errorf("%s: at %s: can't find innermost scope",
  1146  					fset.Position(comment.Pos()), comment.Text)
  1147  				continue
  1148  			}
  1149  			got := "undef"
  1150  			if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
  1151  				kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
  1152  				got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
  1153  			}
  1154  			if got != want {
  1155  				t.Errorf("%s: at %s: %s resolved to %s, want %s",
  1156  					fset.Position(comment.Pos()), comment.Text, name, got, want)
  1157  			}
  1158  		}
  1159  	}
  1160  
  1161  	// Check that for each referring identifier,
  1162  	// a lookup of its name on the innermost
  1163  	// enclosing scope returns the correct object.
  1164  
  1165  	for id, wantObj := range info.Uses {
  1166  		inner := mainScope.Innermost(id.Pos())
  1167  		if inner == nil {
  1168  			t.Errorf("%s: can't find innermost scope enclosing %q",
  1169  				fset.Position(id.Pos()), id.Name)
  1170  			continue
  1171  		}
  1172  
  1173  		// Exclude selectors and qualified identifiers---lexical
  1174  		// refs only.  (Ideally, we'd see if the AST parent is a
  1175  		// SelectorExpr, but that requires PathEnclosingInterval
  1176  		// from golang.org/x/tools/go/ast/astutil.)
  1177  		if id.Name == "X" {
  1178  			continue
  1179  		}
  1180  
  1181  		_, gotObj := inner.LookupParent(id.Name, id.Pos())
  1182  		if gotObj != wantObj {
  1183  			t.Errorf("%s: got %v, want %v",
  1184  				fset.Position(id.Pos()), gotObj, wantObj)
  1185  			continue
  1186  		}
  1187  	}
  1188  }
  1189  
  1190  func TestIdentical_issue15173(t *testing.T) {
  1191  	// Identical should allow nil arguments and be symmetric.
  1192  	for _, test := range []struct {
  1193  		x, y Type
  1194  		want bool
  1195  	}{
  1196  		{Typ[Int], Typ[Int], true},
  1197  		{Typ[Int], nil, false},
  1198  		{nil, Typ[Int], false},
  1199  		{nil, nil, true},
  1200  	} {
  1201  		if got := Identical(test.x, test.y); got != test.want {
  1202  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
  1203  		}
  1204  	}
  1205  }
  1206  
  1207  func TestIssue15305(t *testing.T) {
  1208  	const src = "package p; func f() int16; var _ = f(undef)"
  1209  	fset := token.NewFileSet()
  1210  	f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
  1211  	if err != nil {
  1212  		t.Fatal(err)
  1213  	}
  1214  	conf := Config{
  1215  		Error: func(err error) {}, // allow errors
  1216  	}
  1217  	info := &Info{
  1218  		Types: make(map[ast.Expr]TypeAndValue),
  1219  	}
  1220  	conf.Check("p", fset, []*ast.File{f}, info) // ignore result
  1221  	for e, tv := range info.Types {
  1222  		if _, ok := e.(*ast.CallExpr); ok {
  1223  			if tv.Type != Typ[Int16] {
  1224  				t.Errorf("CallExpr has type %v, want int16", tv.Type)
  1225  			}
  1226  			return
  1227  		}
  1228  	}
  1229  	t.Errorf("CallExpr has no type")
  1230  }
  1231  
  1232  // TestCompositeLitTypes verifies that Info.Types registers the correct
  1233  // types for composite literal expressions and composite literal type
  1234  // expressions.
  1235  func TestCompositeLitTypes(t *testing.T) {
  1236  	for _, test := range []struct {
  1237  		lit, typ string
  1238  	}{
  1239  		{`[16]byte{}`, `[16]byte`},
  1240  		{`[...]byte{}`, `[0]byte`},                // test for issue #14092
  1241  		{`[...]int{1, 2, 3}`, `[3]int`},           // test for issue #14092
  1242  		{`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
  1243  		{`[]int{}`, `[]int`},
  1244  		{`map[string]bool{"foo": true}`, `map[string]bool`},
  1245  		{`struct{}{}`, `struct{}`},
  1246  		{`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
  1247  	} {
  1248  		fset := token.NewFileSet()
  1249  		f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
  1250  		if err != nil {
  1251  			t.Fatalf("%s: %v", test.lit, err)
  1252  		}
  1253  
  1254  		info := &Info{
  1255  			Types: make(map[ast.Expr]TypeAndValue),
  1256  		}
  1257  		if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
  1258  			t.Fatalf("%s: %v", test.lit, err)
  1259  		}
  1260  
  1261  		cmptype := func(x ast.Expr, want string) {
  1262  			tv, ok := info.Types[x]
  1263  			if !ok {
  1264  				t.Errorf("%s: no Types entry found", test.lit)
  1265  				return
  1266  			}
  1267  			if tv.Type == nil {
  1268  				t.Errorf("%s: type is nil", test.lit)
  1269  				return
  1270  			}
  1271  			if got := tv.Type.String(); got != want {
  1272  				t.Errorf("%s: got %v, want %s", test.lit, got, want)
  1273  			}
  1274  		}
  1275  
  1276  		// test type of composite literal expression
  1277  		rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
  1278  		cmptype(rhs, test.typ)
  1279  
  1280  		// test type of composite literal type expression
  1281  		cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
  1282  	}
  1283  }
  1284  
  1285  // TestObjectParents verifies that objects have parent scopes or not
  1286  // as specified by the Object interface.
  1287  func TestObjectParents(t *testing.T) {
  1288  	const src = `
  1289  package p
  1290  
  1291  const C = 0
  1292  
  1293  type T1 struct {
  1294  	a, b int
  1295  	T2
  1296  }
  1297  
  1298  type T2 interface {
  1299  	im1()
  1300  	im2()
  1301  }
  1302  
  1303  func (T1) m1() {}
  1304  func (*T1) m2() {}
  1305  
  1306  func f(x int) { y := x; print(y) }
  1307  `
  1308  
  1309  	fset := token.NewFileSet()
  1310  	f, err := parser.ParseFile(fset, "src", src, 0)
  1311  	if err != nil {
  1312  		t.Fatal(err)
  1313  	}
  1314  
  1315  	info := &Info{
  1316  		Defs: make(map[*ast.Ident]Object),
  1317  	}
  1318  	if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
  1319  		t.Fatal(err)
  1320  	}
  1321  
  1322  	for ident, obj := range info.Defs {
  1323  		if obj == nil {
  1324  			// only package names and implicit vars have a nil object
  1325  			// (in this test we only need to handle the package name)
  1326  			if ident.Name != "p" {
  1327  				t.Errorf("%v has nil object", ident)
  1328  			}
  1329  			continue
  1330  		}
  1331  
  1332  		// struct fields, type-associated and interface methods
  1333  		// have no parent scope
  1334  		wantParent := true
  1335  		switch obj := obj.(type) {
  1336  		case *Var:
  1337  			if obj.IsField() {
  1338  				wantParent = false
  1339  			}
  1340  		case *Func:
  1341  			if obj.Type().(*Signature).Recv() != nil { // method
  1342  				wantParent = false
  1343  			}
  1344  		}
  1345  
  1346  		gotParent := obj.Parent() != nil
  1347  		switch {
  1348  		case gotParent && !wantParent:
  1349  			t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
  1350  		case !gotParent && wantParent:
  1351  			t.Errorf("%v: no parent found", ident)
  1352  		}
  1353  	}
  1354  }
  1355  
  1356  // TestFailedImport tests that we don't get follow-on errors
  1357  // elsewhere in a package due to failing to import a package.
  1358  func TestFailedImport(t *testing.T) {
  1359  	testenv.MustHaveGoBuild(t)
  1360  
  1361  	const src = `
  1362  package p
  1363  
  1364  import "foo" // should only see an error here
  1365  
  1366  const c = foo.C
  1367  type T = foo.T
  1368  var v T = c
  1369  func f(x T) T { return foo.F(x) }
  1370  `
  1371  	fset := token.NewFileSet()
  1372  	f, err := parser.ParseFile(fset, "src", src, 0)
  1373  	if err != nil {
  1374  		t.Fatal(err)
  1375  	}
  1376  	files := []*ast.File{f}
  1377  
  1378  	// type-check using all possible importers
  1379  	for _, compiler := range []string{"gc", "gccgo", "source"} {
  1380  		errcount := 0
  1381  		conf := Config{
  1382  			Error: func(err error) {
  1383  				// we should only see the import error
  1384  				if errcount > 0 || !strings.Contains(err.Error(), "could not import foo") {
  1385  					t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
  1386  				}
  1387  				errcount++
  1388  			},
  1389  			Importer: importer.For(compiler, nil),
  1390  		}
  1391  
  1392  		info := &Info{
  1393  			Uses: make(map[*ast.Ident]Object),
  1394  		}
  1395  		pkg, _ := conf.Check("p", fset, files, info)
  1396  		if pkg == nil {
  1397  			t.Errorf("for %s importer, type-checking failed to return a package", compiler)
  1398  			continue
  1399  		}
  1400  
  1401  		imports := pkg.Imports()
  1402  		if len(imports) != 1 {
  1403  			t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
  1404  			continue
  1405  		}
  1406  		imp := imports[0]
  1407  		if imp.Name() != "foo" {
  1408  			t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
  1409  			continue
  1410  		}
  1411  
  1412  		// verify that all uses of foo refer to the imported package foo (imp)
  1413  		for ident, obj := range info.Uses {
  1414  			if ident.Name == "foo" {
  1415  				if obj, ok := obj.(*PkgName); ok {
  1416  					if obj.Imported() != imp {
  1417  						t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
  1418  					}
  1419  				} else {
  1420  					t.Errorf("%s resolved to %v; want package name", ident, obj)
  1421  				}
  1422  			}
  1423  		}
  1424  	}
  1425  }