...
Run Format

Source file src/go/types/api_test.go

Documentation: go/types

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

View as plain text