github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/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  		// test case for issue 10709
   576  		// TODO(gri) enable once the issue is fixed
   577  		// {`package p13
   578  
   579  		// var (
   580  		//     v = t.m()
   581  		//     t = makeT(0)
   582  		// )
   583  
   584  		// type T struct{}
   585  
   586  		// func (T) m() int { return 0 }
   587  
   588  		// func makeT(n int) T {
   589  		//     if n > 0 {
   590  		//         return makeT(n-1)
   591  		//     }
   592  		//     return T{}
   593  		// }`, []string{
   594  		// 	"t = makeT(0)", "v = t.m()",
   595  		// }},
   596  		// test case for issue 10709: same as test before, but variable decls swapped
   597  		{`package p14
   598  
   599  		var (
   600  		    t = makeT(0)
   601  		    v = t.m()
   602  		)
   603  
   604  		type T struct{}
   605  
   606  		func (T) m() int { return 0 }
   607  
   608  		func makeT(n int) T {
   609  		    if n > 0 {
   610  		        return makeT(n-1)
   611  		    }
   612  		    return T{}
   613  		}`, []string{
   614  			"t = makeT(0)", "v = t.m()",
   615  		}},
   616  	}
   617  
   618  	for _, test := range tests {
   619  		info := Info{}
   620  		name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
   621  
   622  		// number of initializers must match
   623  		if len(info.InitOrder) != len(test.inits) {
   624  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
   625  			continue
   626  		}
   627  
   628  		// initializers must match
   629  		for i, want := range test.inits {
   630  			got := info.InitOrder[i].String()
   631  			if got != want {
   632  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
   633  				continue
   634  			}
   635  		}
   636  	}
   637  }
   638  
   639  func TestMultiFileInitOrder(t *testing.T) {
   640  	fset := token.NewFileSet()
   641  	mustParse := func(src string) *ast.File {
   642  		f, err := parser.ParseFile(fset, "main", src, 0)
   643  		if err != nil {
   644  			t.Fatal(err)
   645  		}
   646  		return f
   647  	}
   648  
   649  	fileA := mustParse(`package main; var a = 1`)
   650  	fileB := mustParse(`package main; var b = 2`)
   651  
   652  	// The initialization order must not depend on the parse
   653  	// order of the files, only on the presentation order to
   654  	// the type-checker.
   655  	for _, test := range []struct {
   656  		files []*ast.File
   657  		want  string
   658  	}{
   659  		{[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
   660  		{[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
   661  	} {
   662  		var info Info
   663  		if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
   664  			t.Fatal(err)
   665  		}
   666  		if got := fmt.Sprint(info.InitOrder); got != test.want {
   667  			t.Fatalf("got %s; want %s", got, test.want)
   668  		}
   669  	}
   670  }
   671  
   672  func TestFiles(t *testing.T) {
   673  	var sources = []string{
   674  		"package p; type T struct{}; func (T) m1() {}",
   675  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
   676  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
   677  		"package p",
   678  	}
   679  
   680  	var conf Config
   681  	fset := token.NewFileSet()
   682  	pkg := NewPackage("p", "p")
   683  	var info Info
   684  	check := NewChecker(&conf, fset, pkg, &info)
   685  
   686  	for i, src := range sources {
   687  		filename := fmt.Sprintf("sources%d", i)
   688  		f, err := parser.ParseFile(fset, filename, src, 0)
   689  		if err != nil {
   690  			t.Fatal(err)
   691  		}
   692  		if err := check.Files([]*ast.File{f}); err != nil {
   693  			t.Error(err)
   694  		}
   695  	}
   696  
   697  	// check InitOrder is [x y]
   698  	var vars []string
   699  	for _, init := range info.InitOrder {
   700  		for _, v := range init.Lhs {
   701  			vars = append(vars, v.Name())
   702  		}
   703  	}
   704  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
   705  		t.Errorf("InitOrder == %s, want %s", got, want)
   706  	}
   707  }
   708  
   709  type testImporter map[string]*Package
   710  
   711  func (m testImporter) Import(path string) (*Package, error) {
   712  	if pkg := m[path]; pkg != nil {
   713  		return pkg, nil
   714  	}
   715  	return nil, fmt.Errorf("package %q not found", path)
   716  }
   717  
   718  func TestSelection(t *testing.T) {
   719  	selections := make(map[*ast.SelectorExpr]*Selection)
   720  
   721  	fset := token.NewFileSet()
   722  	imports := make(testImporter)
   723  	conf := Config{Importer: imports}
   724  	makePkg := func(path, src string) {
   725  		f, err := parser.ParseFile(fset, path+".go", src, 0)
   726  		if err != nil {
   727  			t.Fatal(err)
   728  		}
   729  		pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
   730  		if err != nil {
   731  			t.Fatal(err)
   732  		}
   733  		imports[path] = pkg
   734  	}
   735  
   736  	const libSrc = `
   737  package lib
   738  type T float64
   739  const C T = 3
   740  var V T
   741  func F() {}
   742  func (T) M() {}
   743  `
   744  	const mainSrc = `
   745  package main
   746  import "lib"
   747  
   748  type A struct {
   749  	*B
   750  	C
   751  }
   752  
   753  type B struct {
   754  	b int
   755  }
   756  
   757  func (B) f(int)
   758  
   759  type C struct {
   760  	c int
   761  }
   762  
   763  func (C) g()
   764  func (*C) h()
   765  
   766  func main() {
   767  	// qualified identifiers
   768  	var _ lib.T
   769          _ = lib.C
   770          _ = lib.F
   771          _ = lib.V
   772  	_ = lib.T.M
   773  
   774  	// fields
   775  	_ = A{}.B
   776  	_ = new(A).B
   777  
   778  	_ = A{}.C
   779  	_ = new(A).C
   780  
   781  	_ = A{}.b
   782  	_ = new(A).b
   783  
   784  	_ = A{}.c
   785  	_ = new(A).c
   786  
   787  	// methods
   788          _ = A{}.f
   789          _ = new(A).f
   790          _ = A{}.g
   791          _ = new(A).g
   792          _ = new(A).h
   793  
   794          _ = B{}.f
   795          _ = new(B).f
   796  
   797          _ = C{}.g
   798          _ = new(C).g
   799          _ = new(C).h
   800  
   801  	// method expressions
   802          _ = A.f
   803          _ = (*A).f
   804          _ = B.f
   805          _ = (*B).f
   806  }`
   807  
   808  	wantOut := map[string][2]string{
   809  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
   810  
   811  		"A{}.B":    {"field (main.A) B *main.B", ".[0]"},
   812  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
   813  		"A{}.C":    {"field (main.A) C main.C", ".[1]"},
   814  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
   815  		"A{}.b":    {"field (main.A) b int", "->[0 0]"},
   816  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
   817  		"A{}.c":    {"field (main.A) c int", ".[1 0]"},
   818  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
   819  
   820  		"A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
   821  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
   822  		"A{}.g":    {"method (main.A) g()", ".[1 0]"},
   823  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
   824  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
   825  		"B{}.f":    {"method (main.B) f(int)", ".[0]"},
   826  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
   827  		"C{}.g":    {"method (main.C) g()", ".[0]"},
   828  		"new(C).g": {"method (*main.C) g()", "->[0]"},
   829  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
   830  
   831  		"A.f":    {"method expr (main.A) f(main.A, int)", "->[0 0]"},
   832  		"(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
   833  		"B.f":    {"method expr (main.B) f(main.B, int)", ".[0]"},
   834  		"(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
   835  	}
   836  
   837  	makePkg("lib", libSrc)
   838  	makePkg("main", mainSrc)
   839  
   840  	for e, sel := range selections {
   841  		_ = sel.String() // assertion: must not panic
   842  
   843  		start := fset.Position(e.Pos()).Offset
   844  		end := fset.Position(e.End()).Offset
   845  		syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
   846  
   847  		direct := "."
   848  		if sel.Indirect() {
   849  			direct = "->"
   850  		}
   851  		got := [2]string{
   852  			sel.String(),
   853  			fmt.Sprintf("%s%v", direct, sel.Index()),
   854  		}
   855  		want := wantOut[syntax]
   856  		if want != got {
   857  			t.Errorf("%s: got %q; want %q", syntax, got, want)
   858  		}
   859  		delete(wantOut, syntax)
   860  
   861  		// We must explicitly assert properties of the
   862  		// Signature's receiver since it doesn't participate
   863  		// in Identical() or String().
   864  		sig, _ := sel.Type().(*Signature)
   865  		if sel.Kind() == MethodVal {
   866  			got := sig.Recv().Type()
   867  			want := sel.Recv()
   868  			if !Identical(got, want) {
   869  				t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
   870  			}
   871  		} else if sig != nil && sig.Recv() != nil {
   872  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
   873  		}
   874  	}
   875  	// Assert that all wantOut entries were used exactly once.
   876  	for syntax := range wantOut {
   877  		t.Errorf("no ast.Selection found with syntax %q", syntax)
   878  	}
   879  }
   880  
   881  func TestIssue8518(t *testing.T) {
   882  	fset := token.NewFileSet()
   883  	imports := make(testImporter)
   884  	conf := Config{
   885  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
   886  		Importer: imports,
   887  	}
   888  	makePkg := func(path, src string) {
   889  		f, err := parser.ParseFile(fset, path, src, 0)
   890  		if err != nil {
   891  			t.Fatal(err)
   892  		}
   893  		pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
   894  		imports[path] = pkg
   895  	}
   896  
   897  	const libSrc = `
   898  package a
   899  import "missing"
   900  const C1 = foo
   901  const C2 = missing.C
   902  `
   903  
   904  	const mainSrc = `
   905  package main
   906  import "a"
   907  var _ = a.C1
   908  var _ = a.C2
   909  `
   910  
   911  	makePkg("a", libSrc)
   912  	makePkg("main", mainSrc) // don't crash when type-checking this package
   913  }
   914  
   915  func TestLookupFieldOrMethod(t *testing.T) {
   916  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
   917  	// addressable value, and x for a non-addressable value (even though a variable
   918  	// for ease of test case writing).
   919  	var tests = []struct {
   920  		src      string
   921  		found    bool
   922  		index    []int
   923  		indirect bool
   924  	}{
   925  		// field lookups
   926  		{"var x T; type T struct{}", false, nil, false},
   927  		{"var x T; type T struct{ f int }", true, []int{0}, false},
   928  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
   929  
   930  		// method lookups
   931  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
   932  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
   933  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
   934  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
   935  
   936  		// collisions
   937  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
   938  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
   939  
   940  		// outside methodset
   941  		// (*T).f method exists, but value of type T is not addressable
   942  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
   943  	}
   944  
   945  	for _, test := range tests {
   946  		pkg, err := pkgFor("test", "package p;"+test.src, nil)
   947  		if err != nil {
   948  			t.Errorf("%s: incorrect test case: %s", test.src, err)
   949  			continue
   950  		}
   951  
   952  		obj := pkg.Scope().Lookup("a")
   953  		if obj == nil {
   954  			if obj = pkg.Scope().Lookup("x"); obj == nil {
   955  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
   956  				continue
   957  			}
   958  		}
   959  
   960  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
   961  		if (f != nil) != test.found {
   962  			if f == nil {
   963  				t.Errorf("%s: got no object; want one", test.src)
   964  			} else {
   965  				t.Errorf("%s: got object = %v; want none", test.src, f)
   966  			}
   967  		}
   968  		if !sameSlice(index, test.index) {
   969  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
   970  		}
   971  		if indirect != test.indirect {
   972  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
   973  		}
   974  	}
   975  }
   976  
   977  func sameSlice(a, b []int) bool {
   978  	if len(a) != len(b) {
   979  		return false
   980  	}
   981  	for i, x := range a {
   982  		if x != b[i] {
   983  			return false
   984  		}
   985  	}
   986  	return true
   987  }
   988  
   989  // TestScopeLookupParent ensures that (*Scope).LookupParent returns
   990  // the correct result at various positions with the source.
   991  func TestScopeLookupParent(t *testing.T) {
   992  	fset := token.NewFileSet()
   993  	imports := make(testImporter)
   994  	conf := Config{Importer: imports}
   995  	mustParse := func(src string) *ast.File {
   996  		f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
   997  		if err != nil {
   998  			t.Fatal(err)
   999  		}
  1000  		return f
  1001  	}
  1002  	var info Info
  1003  	makePkg := func(path string, files ...*ast.File) {
  1004  		imports[path], _ = conf.Check(path, fset, files, &info)
  1005  	}
  1006  
  1007  	makePkg("lib", mustParse("package lib; var X int"))
  1008  	// Each /*name=kind:line*/ comment makes the test look up the
  1009  	// name at that point and checks that it resolves to a decl of
  1010  	// the specified kind and line number.  "undef" means undefined.
  1011  	mainSrc := `
  1012  package main
  1013  import "lib"
  1014  var Y = lib.X
  1015  func f() {
  1016  	print(Y) /*Y=var:4*/
  1017  	z /*z=undef*/ := /*z=undef*/ 1 /*z=var:7*/
  1018  	print(z)
  1019  	/*f=func:5*/ /*lib=pkgname:3*/
  1020  	type /*T=undef*/ T /*T=typename:10*/ *T
  1021  }
  1022  `
  1023  	info.Uses = make(map[*ast.Ident]Object)
  1024  	f := mustParse(mainSrc)
  1025  	makePkg("main", f)
  1026  	mainScope := imports["main"].Scope()
  1027  	rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
  1028  	for _, group := range f.Comments {
  1029  		for _, comment := range group.List {
  1030  			// Parse the assertion in the comment.
  1031  			m := rx.FindStringSubmatch(comment.Text)
  1032  			if m == nil {
  1033  				t.Errorf("%s: bad comment: %s",
  1034  					fset.Position(comment.Pos()), comment.Text)
  1035  				continue
  1036  			}
  1037  			name, want := m[1], m[2]
  1038  
  1039  			// Look up the name in the innermost enclosing scope.
  1040  			inner := mainScope.Innermost(comment.Pos())
  1041  			if inner == nil {
  1042  				t.Errorf("%s: at %s: can't find innermost scope",
  1043  					fset.Position(comment.Pos()), comment.Text)
  1044  				continue
  1045  			}
  1046  			got := "undef"
  1047  			if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
  1048  				kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
  1049  				got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
  1050  			}
  1051  			if got != want {
  1052  				t.Errorf("%s: at %s: %s resolved to %s, want %s",
  1053  					fset.Position(comment.Pos()), comment.Text, name, got, want)
  1054  			}
  1055  		}
  1056  	}
  1057  
  1058  	// Check that for each referring identifier,
  1059  	// a lookup of its name on the innermost
  1060  	// enclosing scope returns the correct object.
  1061  
  1062  	for id, wantObj := range info.Uses {
  1063  		inner := mainScope.Innermost(id.Pos())
  1064  		if inner == nil {
  1065  			t.Errorf("%s: can't find innermost scope enclosing %q",
  1066  				fset.Position(id.Pos()), id.Name)
  1067  			continue
  1068  		}
  1069  
  1070  		// Exclude selectors and qualified identifiers---lexical
  1071  		// refs only.  (Ideally, we'd see if the AST parent is a
  1072  		// SelectorExpr, but that requires PathEnclosingInterval
  1073  		// from golang.org/x/tools/go/ast/astutil.)
  1074  		if id.Name == "X" {
  1075  			continue
  1076  		}
  1077  
  1078  		_, gotObj := inner.LookupParent(id.Name, id.Pos())
  1079  		if gotObj != wantObj {
  1080  			t.Errorf("%s: got %v, want %v",
  1081  				fset.Position(id.Pos()), gotObj, wantObj)
  1082  			continue
  1083  		}
  1084  	}
  1085  }
  1086  
  1087  func TestIdentical_issue15173(t *testing.T) {
  1088  	// Identical should allow nil arguments and be symmetric.
  1089  	for _, test := range []struct {
  1090  		x, y Type
  1091  		want bool
  1092  	}{
  1093  		{Typ[Int], Typ[Int], true},
  1094  		{Typ[Int], nil, false},
  1095  		{nil, Typ[Int], false},
  1096  		{nil, nil, true},
  1097  	} {
  1098  		if got := Identical(test.x, test.y); got != test.want {
  1099  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
  1100  		}
  1101  	}
  1102  }
  1103  
  1104  func TestIssue15305(t *testing.T) {
  1105  	const src = "package p; func f() int16; var _ = f(undef)"
  1106  	fset := token.NewFileSet()
  1107  	f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
  1108  	if err != nil {
  1109  		t.Fatal(err)
  1110  	}
  1111  	conf := Config{
  1112  		Error: func(err error) {}, // allow errors
  1113  	}
  1114  	info := &Info{
  1115  		Types: make(map[ast.Expr]TypeAndValue),
  1116  	}
  1117  	conf.Check("p", fset, []*ast.File{f}, info) // ignore result
  1118  	for e, tv := range info.Types {
  1119  		if _, ok := e.(*ast.CallExpr); ok {
  1120  			if tv.Type != Typ[Int16] {
  1121  				t.Errorf("CallExpr has type %v, want int16", tv.Type)
  1122  			}
  1123  			return
  1124  		}
  1125  	}
  1126  	t.Errorf("CallExpr has no type")
  1127  }