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