github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/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  		// TODO(gri): uncomment if we accept issue 8189.
   175  		// {`package p2; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
   176  		// 	`m["foo"]`,
   177  		// 	`(complex128, p2.mybool)`,
   178  		// },
   179  		// TODO(gri): remove if we accept issue 8189.
   180  		{`package p2; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
   181  			`m["foo"]`,
   182  			`(complex128, bool)`,
   183  		},
   184  		{`package p3; var c chan string; var _, _ = <-c`,
   185  			`<-c`,
   186  			`(string, bool)`,
   187  		},
   188  
   189  		// issue 6796
   190  		{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
   191  			`x.(int)`,
   192  			`(int, bool)`,
   193  		},
   194  		{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
   195  			`(<-c)`,
   196  			`(string, bool)`,
   197  		},
   198  		{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
   199  			`<-c`,
   200  			`(string, bool)`,
   201  		},
   202  		{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
   203  			`(<-c)`,
   204  			`(string, bool)`,
   205  		},
   206  		{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
   207  			`(<-c)`,
   208  			`(string, bool)`,
   209  		},
   210  
   211  		// issue 7060
   212  		{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
   213  			`m[0]`,
   214  			`(string, bool)`,
   215  		},
   216  		{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
   217  			`m[0]`,
   218  			`(string, bool)`,
   219  		},
   220  		{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
   221  			`m[0]`,
   222  			`(string, bool)`,
   223  		},
   224  		{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
   225  			`<-ch`,
   226  			`(string, bool)`,
   227  		},
   228  		{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
   229  			`<-ch`,
   230  			`(string, bool)`,
   231  		},
   232  		{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
   233  			`<-ch`,
   234  			`(string, bool)`,
   235  		},
   236  	}
   237  
   238  	for _, test := range tests {
   239  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
   240  		name := mustTypecheck(t, "TypesInfo", test.src, &info)
   241  
   242  		// look for expression type
   243  		var typ Type
   244  		for e, tv := range info.Types {
   245  			if ExprString(e) == test.expr {
   246  				typ = tv.Type
   247  				break
   248  			}
   249  		}
   250  		if typ == nil {
   251  			t.Errorf("package %s: no type found for %s", name, test.expr)
   252  			continue
   253  		}
   254  
   255  		// check that type is correct
   256  		if got := typ.String(); got != test.typ {
   257  			t.Errorf("package %s: got %s; want %s", name, got, test.typ)
   258  		}
   259  	}
   260  }
   261  
   262  func predString(tv TypeAndValue) string {
   263  	var buf bytes.Buffer
   264  	pred := func(b bool, s string) {
   265  		if b {
   266  			if buf.Len() > 0 {
   267  				buf.WriteString(", ")
   268  			}
   269  			buf.WriteString(s)
   270  		}
   271  	}
   272  
   273  	pred(tv.IsVoid(), "void")
   274  	pred(tv.IsType(), "type")
   275  	pred(tv.IsBuiltin(), "builtin")
   276  	pred(tv.IsValue() && tv.Value != nil, "const")
   277  	pred(tv.IsValue() && tv.Value == nil, "value")
   278  	pred(tv.IsNil(), "nil")
   279  	pred(tv.Addressable(), "addressable")
   280  	pred(tv.Assignable(), "assignable")
   281  	pred(tv.HasOk(), "hasOk")
   282  
   283  	if buf.Len() == 0 {
   284  		return "invalid"
   285  	}
   286  	return buf.String()
   287  }
   288  
   289  func TestPredicatesInfo(t *testing.T) {
   290  	testenv.MustHaveGoBuild(t)
   291  
   292  	var tests = []struct {
   293  		src  string
   294  		expr string
   295  		pred string
   296  	}{
   297  		// void
   298  		{`package n0; func f() { f() }`, `f()`, `void`},
   299  
   300  		// types
   301  		{`package t0; type _ int`, `int`, `type`},
   302  		{`package t1; type _ []int`, `[]int`, `type`},
   303  		{`package t2; type _ func()`, `func()`, `type`},
   304  
   305  		// built-ins
   306  		{`package b0; var _ = len("")`, `len`, `builtin`},
   307  		{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
   308  
   309  		// constants
   310  		{`package c0; var _ = 42`, `42`, `const`},
   311  		{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
   312  		{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
   313  
   314  		// values
   315  		{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
   316  		{`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
   317  		{`package v2; var _ = func(){}`, `(func() literal)`, `value`},
   318  		{`package v4; func f() { _ = f }`, `f`, `value`},
   319  		{`package v3; var _ *int = nil`, `nil`, `value, nil`},
   320  		{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
   321  
   322  		// addressable (and thus assignable) operands
   323  		{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
   324  		{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
   325  		{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
   326  		{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
   327  		{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
   328  		{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
   329  		{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
   330  		{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
   331  		// composite literals are not addressable
   332  
   333  		// assignable but not addressable values
   334  		{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
   335  		{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
   336  
   337  		// hasOk expressions
   338  		{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
   339  		{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
   340  
   341  		// missing entries
   342  		// - package names are collected in the Uses map
   343  		// - identifiers being declared are collected in the Defs map
   344  		{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
   345  		{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
   346  		{`package m2; const c = 0`, `c`, `<missing>`},
   347  		{`package m3; type T int`, `T`, `<missing>`},
   348  		{`package m4; var v int`, `v`, `<missing>`},
   349  		{`package m5; func f() {}`, `f`, `<missing>`},
   350  		{`package m6; func _(x int) {}`, `x`, `<missing>`},
   351  		{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
   352  		{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
   353  	}
   354  
   355  	for _, test := range tests {
   356  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
   357  		name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
   358  
   359  		// look for expression predicates
   360  		got := "<missing>"
   361  		for e, tv := range info.Types {
   362  			//println(name, ExprString(e))
   363  			if ExprString(e) == test.expr {
   364  				got = predString(tv)
   365  				break
   366  			}
   367  		}
   368  
   369  		if got != test.pred {
   370  			t.Errorf("package %s: got %s; want %s", name, got, test.pred)
   371  		}
   372  	}
   373  }
   374  
   375  func TestScopesInfo(t *testing.T) {
   376  	testenv.MustHaveGoBuild(t)
   377  
   378  	var tests = []struct {
   379  		src    string
   380  		scopes []string // list of scope descriptors of the form kind:varlist
   381  	}{
   382  		{`package p0`, []string{
   383  			"file:",
   384  		}},
   385  		{`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
   386  			"file:fmt m",
   387  		}},
   388  		{`package p2; func _() {}`, []string{
   389  			"file:", "func:",
   390  		}},
   391  		{`package p3; func _(x, y int) {}`, []string{
   392  			"file:", "func:x y",
   393  		}},
   394  		{`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
   395  			"file:", "func:x y z", // redeclaration of x
   396  		}},
   397  		{`package p5; func _(x, y int) (u, _ int) { return }`, []string{
   398  			"file:", "func:u x y",
   399  		}},
   400  		{`package p6; func _() { { var x int; _ = x } }`, []string{
   401  			"file:", "func:", "block:x",
   402  		}},
   403  		{`package p7; func _() { if true {} }`, []string{
   404  			"file:", "func:", "if:", "block:",
   405  		}},
   406  		{`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
   407  			"file:", "func:", "if:x", "block:y",
   408  		}},
   409  		{`package p9; func _() { switch x := 0; x {} }`, []string{
   410  			"file:", "func:", "switch:x",
   411  		}},
   412  		{`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
   413  			"file:", "func:", "switch:x", "case:y", "case:",
   414  		}},
   415  		{`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
   416  			"file:", "func:t", "type switch:",
   417  		}},
   418  		{`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
   419  			"file:", "func:t", "type switch:t",
   420  		}},
   421  		{`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
   422  			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
   423  		}},
   424  		{`package p14; func _() { select{} }`, []string{
   425  			"file:", "func:",
   426  		}},
   427  		{`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
   428  			"file:", "func:c", "comm:",
   429  		}},
   430  		{`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
   431  			"file:", "func:c", "comm:i x",
   432  		}},
   433  		{`package p17; func _() { for{} }`, []string{
   434  			"file:", "func:", "for:", "block:",
   435  		}},
   436  		{`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
   437  			"file:", "func:n", "for:i", "block:",
   438  		}},
   439  		{`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
   440  			"file:", "func:a", "range:i", "block:",
   441  		}},
   442  		{`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
   443  			"file:", "func:a", "range:i x", "block:",
   444  		}},
   445  	}
   446  
   447  	for _, test := range tests {
   448  		info := Info{Scopes: make(map[ast.Node]*Scope)}
   449  		name := mustTypecheck(t, "ScopesInfo", test.src, &info)
   450  
   451  		// number of scopes must match
   452  		if len(info.Scopes) != len(test.scopes) {
   453  			t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
   454  		}
   455  
   456  		// scope descriptions must match
   457  		for node, scope := range info.Scopes {
   458  			kind := "<unknown node kind>"
   459  			switch node.(type) {
   460  			case *ast.File:
   461  				kind = "file"
   462  			case *ast.FuncType:
   463  				kind = "func"
   464  			case *ast.BlockStmt:
   465  				kind = "block"
   466  			case *ast.IfStmt:
   467  				kind = "if"
   468  			case *ast.SwitchStmt:
   469  				kind = "switch"
   470  			case *ast.TypeSwitchStmt:
   471  				kind = "type switch"
   472  			case *ast.CaseClause:
   473  				kind = "case"
   474  			case *ast.CommClause:
   475  				kind = "comm"
   476  			case *ast.ForStmt:
   477  				kind = "for"
   478  			case *ast.RangeStmt:
   479  				kind = "range"
   480  			}
   481  
   482  			// look for matching scope description
   483  			desc := kind + ":" + strings.Join(scope.Names(), " ")
   484  			found := false
   485  			for _, d := range test.scopes {
   486  				if desc == d {
   487  					found = true
   488  					break
   489  				}
   490  			}
   491  			if !found {
   492  				t.Errorf("package %s: no matching scope found for %s", name, desc)
   493  			}
   494  		}
   495  	}
   496  }
   497  
   498  func TestInitOrderInfo(t *testing.T) {
   499  	var tests = []struct {
   500  		src   string
   501  		inits []string
   502  	}{
   503  		{`package p0; var (x = 1; y = x)`, []string{
   504  			"x = 1", "y = x",
   505  		}},
   506  		{`package p1; var (a = 1; b = 2; c = 3)`, []string{
   507  			"a = 1", "b = 2", "c = 3",
   508  		}},
   509  		{`package p2; var (a, b, c = 1, 2, 3)`, []string{
   510  			"a = 1", "b = 2", "c = 3",
   511  		}},
   512  		{`package p3; var _ = f(); func f() int { return 1 }`, []string{
   513  			"_ = f()", // blank var
   514  		}},
   515  		{`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
   516  			"a = 0", "z = 0", "y = z", "x = y",
   517  		}},
   518  		{`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
   519  			"a, _ = m[0]", // blank var
   520  		}},
   521  		{`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
   522  			"z = 0", "a, b = f()",
   523  		}},
   524  		{`package p7; var (a = func() int { return b }(); b = 1)`, []string{
   525  			"b = 1", "a = (func() int literal)()",
   526  		}},
   527  		{`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
   528  			"c = 1", "a, b = (func() (_, _ int) literal)()",
   529  		}},
   530  		{`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
   531  			"y = 1", "x = T.m",
   532  		}},
   533  		{`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
   534  			"a = 0", "b = 0", "c = 0", "d = c + b",
   535  		}},
   536  		{`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
   537  			"c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
   538  		}},
   539  		// emit an initializer for n:1 initializations only once (not for each node
   540  		// on the lhs which may appear in different order in the dependency graph)
   541  		{`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
   542  			"b = 0", "x, y = m[0]", "a = x",
   543  		}},
   544  		// test case from spec section on package initialization
   545  		{`package p12
   546  
   547  		var (
   548  			a = c + b
   549  			b = f()
   550  			c = f()
   551  			d = 3
   552  		)
   553  
   554  		func f() int {
   555  			d++
   556  			return d
   557  		}`, []string{
   558  			"d = 3", "b = f()", "c = f()", "a = c + b",
   559  		}},
   560  		// test case for issue 7131
   561  		{`package main
   562  
   563  		var counter int
   564  		func next() int { counter++; return counter }
   565  
   566  		var _ = makeOrder()
   567  		func makeOrder() []int { return []int{f, b, d, e, c, a} }
   568  
   569  		var a       = next()
   570  		var b, c    = next(), next()
   571  		var d, e, f = next(), next(), next()
   572  		`, []string{
   573  			"a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
   574  		}},
   575  	}
   576  
   577  	for _, test := range tests {
   578  		info := Info{}
   579  		name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
   580  
   581  		// number of initializers must match
   582  		if len(info.InitOrder) != len(test.inits) {
   583  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
   584  			continue
   585  		}
   586  
   587  		// initializers must match
   588  		for i, want := range test.inits {
   589  			got := info.InitOrder[i].String()
   590  			if got != want {
   591  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
   592  				continue
   593  			}
   594  		}
   595  	}
   596  }
   597  
   598  func TestMultiFileInitOrder(t *testing.T) {
   599  	fset := token.NewFileSet()
   600  	mustParse := func(src string) *ast.File {
   601  		f, err := parser.ParseFile(fset, "main", src, 0)
   602  		if err != nil {
   603  			t.Fatal(err)
   604  		}
   605  		return f
   606  	}
   607  
   608  	fileA := mustParse(`package main; var a = 1`)
   609  	fileB := mustParse(`package main; var b = 2`)
   610  
   611  	// The initialization order must not depend on the parse
   612  	// order of the files, only on the presentation order to
   613  	// the type-checker.
   614  	for _, test := range []struct {
   615  		files []*ast.File
   616  		want  string
   617  	}{
   618  		{[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
   619  		{[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
   620  	} {
   621  		var info Info
   622  		if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
   623  			t.Fatal(err)
   624  		}
   625  		if got := fmt.Sprint(info.InitOrder); got != test.want {
   626  			t.Fatalf("got %s; want %s", got, test.want)
   627  		}
   628  	}
   629  }
   630  
   631  func TestFiles(t *testing.T) {
   632  	var sources = []string{
   633  		"package p; type T struct{}; func (T) m1() {}",
   634  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
   635  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
   636  		"package p",
   637  	}
   638  
   639  	var conf Config
   640  	fset := token.NewFileSet()
   641  	pkg := NewPackage("p", "p")
   642  	var info Info
   643  	check := NewChecker(&conf, fset, pkg, &info)
   644  
   645  	for i, src := range sources {
   646  		filename := fmt.Sprintf("sources%d", i)
   647  		f, err := parser.ParseFile(fset, filename, src, 0)
   648  		if err != nil {
   649  			t.Fatal(err)
   650  		}
   651  		if err := check.Files([]*ast.File{f}); err != nil {
   652  			t.Error(err)
   653  		}
   654  	}
   655  
   656  	// check InitOrder is [x y]
   657  	var vars []string
   658  	for _, init := range info.InitOrder {
   659  		for _, v := range init.Lhs {
   660  			vars = append(vars, v.Name())
   661  		}
   662  	}
   663  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
   664  		t.Errorf("InitOrder == %s, want %s", got, want)
   665  	}
   666  }
   667  
   668  type testImporter map[string]*Package
   669  
   670  func (m testImporter) Import(path string) (*Package, error) {
   671  	if pkg := m[path]; pkg != nil {
   672  		return pkg, nil
   673  	}
   674  	return nil, fmt.Errorf("package %q not found", path)
   675  }
   676  
   677  func TestSelection(t *testing.T) {
   678  	selections := make(map[*ast.SelectorExpr]*Selection)
   679  
   680  	fset := token.NewFileSet()
   681  	imports := make(testImporter)
   682  	conf := Config{Importer: imports}
   683  	makePkg := func(path, src string) {
   684  		f, err := parser.ParseFile(fset, path+".go", src, 0)
   685  		if err != nil {
   686  			t.Fatal(err)
   687  		}
   688  		pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
   689  		if err != nil {
   690  			t.Fatal(err)
   691  		}
   692  		imports[path] = pkg
   693  	}
   694  
   695  	const libSrc = `
   696  package lib
   697  type T float64
   698  const C T = 3
   699  var V T
   700  func F() {}
   701  func (T) M() {}
   702  `
   703  	const mainSrc = `
   704  package main
   705  import "lib"
   706  
   707  type A struct {
   708  	*B
   709  	C
   710  }
   711  
   712  type B struct {
   713  	b int
   714  }
   715  
   716  func (B) f(int)
   717  
   718  type C struct {
   719  	c int
   720  }
   721  
   722  func (C) g()
   723  func (*C) h()
   724  
   725  func main() {
   726  	// qualified identifiers
   727  	var _ lib.T
   728          _ = lib.C
   729          _ = lib.F
   730          _ = lib.V
   731  	_ = lib.T.M
   732  
   733  	// fields
   734  	_ = A{}.B
   735  	_ = new(A).B
   736  
   737  	_ = A{}.C
   738  	_ = new(A).C
   739  
   740  	_ = A{}.b
   741  	_ = new(A).b
   742  
   743  	_ = A{}.c
   744  	_ = new(A).c
   745  
   746  	// methods
   747          _ = A{}.f
   748          _ = new(A).f
   749          _ = A{}.g
   750          _ = new(A).g
   751          _ = new(A).h
   752  
   753          _ = B{}.f
   754          _ = new(B).f
   755  
   756          _ = C{}.g
   757          _ = new(C).g
   758          _ = new(C).h
   759  
   760  	// method expressions
   761          _ = A.f
   762          _ = (*A).f
   763          _ = B.f
   764          _ = (*B).f
   765  }`
   766  
   767  	wantOut := map[string][2]string{
   768  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
   769  
   770  		"A{}.B":    {"field (main.A) B *main.B", ".[0]"},
   771  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
   772  		"A{}.C":    {"field (main.A) C main.C", ".[1]"},
   773  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
   774  		"A{}.b":    {"field (main.A) b int", "->[0 0]"},
   775  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
   776  		"A{}.c":    {"field (main.A) c int", ".[1 0]"},
   777  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
   778  
   779  		"A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
   780  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
   781  		"A{}.g":    {"method (main.A) g()", ".[1 0]"},
   782  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
   783  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
   784  		"B{}.f":    {"method (main.B) f(int)", ".[0]"},
   785  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
   786  		"C{}.g":    {"method (main.C) g()", ".[0]"},
   787  		"new(C).g": {"method (*main.C) g()", "->[0]"},
   788  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
   789  
   790  		"A.f":    {"method expr (main.A) f(main.A, int)", "->[0 0]"},
   791  		"(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
   792  		"B.f":    {"method expr (main.B) f(main.B, int)", ".[0]"},
   793  		"(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
   794  	}
   795  
   796  	makePkg("lib", libSrc)
   797  	makePkg("main", mainSrc)
   798  
   799  	for e, sel := range selections {
   800  		_ = sel.String() // assertion: must not panic
   801  
   802  		start := fset.Position(e.Pos()).Offset
   803  		end := fset.Position(e.End()).Offset
   804  		syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
   805  
   806  		direct := "."
   807  		if sel.Indirect() {
   808  			direct = "->"
   809  		}
   810  		got := [2]string{
   811  			sel.String(),
   812  			fmt.Sprintf("%s%v", direct, sel.Index()),
   813  		}
   814  		want := wantOut[syntax]
   815  		if want != got {
   816  			t.Errorf("%s: got %q; want %q", syntax, got, want)
   817  		}
   818  		delete(wantOut, syntax)
   819  
   820  		// We must explicitly assert properties of the
   821  		// Signature's receiver since it doesn't participate
   822  		// in Identical() or String().
   823  		sig, _ := sel.Type().(*Signature)
   824  		if sel.Kind() == MethodVal {
   825  			got := sig.Recv().Type()
   826  			want := sel.Recv()
   827  			if !Identical(got, want) {
   828  				t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
   829  			}
   830  		} else if sig != nil && sig.Recv() != nil {
   831  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
   832  		}
   833  	}
   834  	// Assert that all wantOut entries were used exactly once.
   835  	for syntax := range wantOut {
   836  		t.Errorf("no ast.Selection found with syntax %q", syntax)
   837  	}
   838  }
   839  
   840  func TestIssue8518(t *testing.T) {
   841  	fset := token.NewFileSet()
   842  	imports := make(testImporter)
   843  	conf := Config{
   844  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
   845  		Importer: imports,
   846  	}
   847  	makePkg := func(path, src string) {
   848  		f, err := parser.ParseFile(fset, path, src, 0)
   849  		if err != nil {
   850  			t.Fatal(err)
   851  		}
   852  		pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
   853  		imports[path] = pkg
   854  	}
   855  
   856  	const libSrc = `
   857  package a
   858  import "missing"
   859  const C1 = foo
   860  const C2 = missing.C
   861  `
   862  
   863  	const mainSrc = `
   864  package main
   865  import "a"
   866  var _ = a.C1
   867  var _ = a.C2
   868  `
   869  
   870  	makePkg("a", libSrc)
   871  	makePkg("main", mainSrc) // don't crash when type-checking this package
   872  }
   873  
   874  func TestLookupFieldOrMethod(t *testing.T) {
   875  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
   876  	// addressable value, and x for a non-addressable value (even though a variable
   877  	// for ease of test case writing).
   878  	var tests = []struct {
   879  		src      string
   880  		found    bool
   881  		index    []int
   882  		indirect bool
   883  	}{
   884  		// field lookups
   885  		{"var x T; type T struct{}", false, nil, false},
   886  		{"var x T; type T struct{ f int }", true, []int{0}, false},
   887  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
   888  
   889  		// method lookups
   890  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
   891  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
   892  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
   893  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
   894  
   895  		// collisions
   896  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
   897  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
   898  
   899  		// outside methodset
   900  		// (*T).f method exists, but value of type T is not addressable
   901  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
   902  	}
   903  
   904  	for _, test := range tests {
   905  		pkg, err := pkgFor("test", "package p;"+test.src, nil)
   906  		if err != nil {
   907  			t.Errorf("%s: incorrect test case: %s", test.src, err)
   908  			continue
   909  		}
   910  
   911  		obj := pkg.Scope().Lookup("a")
   912  		if obj == nil {
   913  			if obj = pkg.Scope().Lookup("x"); obj == nil {
   914  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
   915  				continue
   916  			}
   917  		}
   918  
   919  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
   920  		if (f != nil) != test.found {
   921  			if f == nil {
   922  				t.Errorf("%s: got no object; want one", test.src)
   923  			} else {
   924  				t.Errorf("%s: got object = %v; want none", test.src, f)
   925  			}
   926  		}
   927  		if !sameSlice(index, test.index) {
   928  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
   929  		}
   930  		if indirect != test.indirect {
   931  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
   932  		}
   933  	}
   934  }
   935  
   936  func sameSlice(a, b []int) bool {
   937  	if len(a) != len(b) {
   938  		return false
   939  	}
   940  	for i, x := range a {
   941  		if x != b[i] {
   942  			return false
   943  		}
   944  	}
   945  	return true
   946  }
   947  
   948  // TestScopeLookupParent ensures that (*Scope).LookupParent returns
   949  // the correct result at various positions with the source.
   950  func TestScopeLookupParent(t *testing.T) {
   951  	fset := token.NewFileSet()
   952  	imports := make(testImporter)
   953  	conf := Config{Importer: imports}
   954  	mustParse := func(src string) *ast.File {
   955  		f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
   956  		if err != nil {
   957  			t.Fatal(err)
   958  		}
   959  		return f
   960  	}
   961  	var info Info
   962  	makePkg := func(path string, files ...*ast.File) {
   963  		imports[path], _ = conf.Check(path, fset, files, &info)
   964  	}
   965  
   966  	makePkg("lib", mustParse("package lib; var X int"))
   967  	// Each /*name=kind:line*/ comment makes the test look up the
   968  	// name at that point and checks that it resolves to a decl of
   969  	// the specified kind and line number.  "undef" means undefined.
   970  	mainSrc := `
   971  package main
   972  import "lib"
   973  var Y = lib.X
   974  func f() {
   975  	print(Y) /*Y=var:4*/
   976  	z /*z=undef*/ := /*z=undef*/ 1 /*z=var:7*/
   977  	print(z)
   978  	/*f=func:5*/ /*lib=pkgname:3*/
   979  	type /*T=undef*/ T /*T=typename:10*/ *T
   980  }
   981  `
   982  	info.Uses = make(map[*ast.Ident]Object)
   983  	f := mustParse(mainSrc)
   984  	makePkg("main", f)
   985  	mainScope := imports["main"].Scope()
   986  	rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
   987  	for _, group := range f.Comments {
   988  		for _, comment := range group.List {
   989  			// Parse the assertion in the comment.
   990  			m := rx.FindStringSubmatch(comment.Text)
   991  			if m == nil {
   992  				t.Errorf("%s: bad comment: %s",
   993  					fset.Position(comment.Pos()), comment.Text)
   994  				continue
   995  			}
   996  			name, want := m[1], m[2]
   997  
   998  			// Look up the name in the innermost enclosing scope.
   999  			inner := mainScope.Innermost(comment.Pos())
  1000  			if inner == nil {
  1001  				t.Errorf("%s: at %s: can't find innermost scope",
  1002  					fset.Position(comment.Pos()), comment.Text)
  1003  				continue
  1004  			}
  1005  			got := "undef"
  1006  			if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
  1007  				kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
  1008  				got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
  1009  			}
  1010  			if got != want {
  1011  				t.Errorf("%s: at %s: %s resolved to %s, want %s",
  1012  					fset.Position(comment.Pos()), comment.Text, name, got, want)
  1013  			}
  1014  		}
  1015  	}
  1016  
  1017  	// Check that for each referring identifier,
  1018  	// a lookup of its name on the innermost
  1019  	// enclosing scope returns the correct object.
  1020  
  1021  	for id, wantObj := range info.Uses {
  1022  		inner := mainScope.Innermost(id.Pos())
  1023  		if inner == nil {
  1024  			t.Errorf("%s: can't find innermost scope enclosing %q",
  1025  				fset.Position(id.Pos()), id.Name)
  1026  			continue
  1027  		}
  1028  
  1029  		// Exclude selectors and qualified identifiers---lexical
  1030  		// refs only.  (Ideally, we'd see if the AST parent is a
  1031  		// SelectorExpr, but that requires PathEnclosingInterval
  1032  		// from golang.org/x/tools/go/ast/astutil.)
  1033  		if id.Name == "X" {
  1034  			continue
  1035  		}
  1036  
  1037  		_, gotObj := inner.LookupParent(id.Name, id.Pos())
  1038  		if gotObj != wantObj {
  1039  			t.Errorf("%s: got %v, want %v",
  1040  				fset.Position(id.Pos()), gotObj, wantObj)
  1041  			continue
  1042  		}
  1043  	}
  1044  }