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