github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/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 "os" 16 "os/exec" 17 "path/filepath" 18 "reflect" 19 "regexp" 20 "strings" 21 "testing" 22 23 . "go/types" 24 ) 25 26 func pkgFor(path, source string, info *Info) (*Package, error) { 27 fset := token.NewFileSet() 28 f, err := parser.ParseFile(fset, path, source, 0) 29 if err != nil { 30 return nil, err 31 } 32 33 conf := Config{Importer: importer.Default()} 34 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info) 35 } 36 37 func mustTypecheck(t *testing.T, path, source string, info *Info) string { 38 pkg, err := pkgFor(path, source, info) 39 if err != nil { 40 name := path 41 if pkg != nil { 42 name = "package " + pkg.Name() 43 } 44 t.Fatalf("%s: didn't type-check (%s)", name, err) 45 } 46 return pkg.Name() 47 } 48 49 func TestValuesInfo(t *testing.T) { 50 var tests = []struct { 51 src string 52 expr string // constant expression 53 typ string // constant type 54 val string // constant value 55 }{ 56 {`package a0; const _ = false`, `false`, `untyped bool`, `false`}, 57 {`package a1; const _ = 0`, `0`, `untyped int`, `0`}, 58 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`}, 59 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`}, 60 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`}, 61 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`}, 62 63 {`package b0; var _ = false`, `false`, `bool`, `false`}, 64 {`package b1; var _ = 0`, `0`, `int`, `0`}, 65 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`}, 66 {`package b3; var _ = 0.`, `0.`, `float64`, `0`}, 67 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`}, 68 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`}, 69 70 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`}, 71 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`}, 72 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`}, 73 74 {`package c1a; var _ = int(0)`, `0`, `int`, `0`}, 75 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`}, 76 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`}, 77 78 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`}, 79 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`}, 80 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`}, 81 82 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`}, 83 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`}, 84 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`}, 85 86 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`}, 87 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`}, 88 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`}, 89 90 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`}, 91 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`}, 92 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`}, 93 94 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`}, 95 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`}, 96 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`}, 97 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`}, 98 99 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`}, 100 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`}, 101 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`}, 102 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`}, 103 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`}, 104 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`}, 105 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`}, 106 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`}, 107 108 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`}, 109 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`}, 110 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`}, 111 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`}, 112 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`}, 113 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`}, 114 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`}, 115 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`}, 116 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`}, 117 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`}, 118 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`}, 119 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`}, 120 } 121 122 for _, test := range tests { 123 info := Info{ 124 Types: make(map[ast.Expr]TypeAndValue), 125 } 126 name := mustTypecheck(t, "ValuesInfo", test.src, &info) 127 128 // look for constant expression 129 var expr ast.Expr 130 for e := range info.Types { 131 if ExprString(e) == test.expr { 132 expr = e 133 break 134 } 135 } 136 if expr == nil { 137 t.Errorf("package %s: no expression found for %s", name, test.expr) 138 continue 139 } 140 tv := info.Types[expr] 141 142 // check that type is correct 143 if got := tv.Type.String(); got != test.typ { 144 t.Errorf("package %s: got type %s; want %s", name, got, test.typ) 145 continue 146 } 147 148 // check that value is correct 149 if got := tv.Value.ExactString(); got != test.val { 150 t.Errorf("package %s: got value %s; want %s", name, got, test.val) 151 } 152 } 153 } 154 155 func TestTypesInfo(t *testing.T) { 156 var tests = []struct { 157 src string 158 expr string // expression 159 typ string // value type 160 }{ 161 // single-valued expressions of untyped constants 162 {`package b0; var x interface{} = false`, `false`, `bool`}, 163 {`package b1; var x interface{} = 0`, `0`, `int`}, 164 {`package b2; var x interface{} = 0.`, `0.`, `float64`}, 165 {`package b3; var x interface{} = 0i`, `0i`, `complex128`}, 166 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`}, 167 168 // comma-ok expressions 169 {`package p0; var x interface{}; var _, _ = x.(int)`, 170 `x.(int)`, 171 `(int, bool)`, 172 }, 173 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`, 174 `x.(int)`, 175 `(int, bool)`, 176 }, 177 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`, 178 `m["foo"]`, 179 `(complex128, p2a.mybool)`, 180 }, 181 {`package p2b; 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 263 func 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 290 func 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 376 func 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 499 func 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 // test case for issue 10709 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 // another candidate possibly causing problems with issue 10709 617 {`package p15 618 619 var y1 = f1() 620 621 func f1() int { return g1() } 622 func g1() int { f1(); return x1 } 623 624 var x1 = 0 625 626 var y2 = f2() 627 628 func f2() int { return g2() } 629 func g2() int { return x2 } 630 631 var x2 = 0`, []string{ 632 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()", 633 }}, 634 } 635 636 for _, test := range tests { 637 info := Info{} 638 name := mustTypecheck(t, "InitOrderInfo", test.src, &info) 639 640 // number of initializers must match 641 if len(info.InitOrder) != len(test.inits) { 642 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits)) 643 continue 644 } 645 646 // initializers must match 647 for i, want := range test.inits { 648 got := info.InitOrder[i].String() 649 if got != want { 650 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want) 651 continue 652 } 653 } 654 } 655 } 656 657 func TestMultiFileInitOrder(t *testing.T) { 658 fset := token.NewFileSet() 659 mustParse := func(src string) *ast.File { 660 f, err := parser.ParseFile(fset, "main", src, 0) 661 if err != nil { 662 t.Fatal(err) 663 } 664 return f 665 } 666 667 fileA := mustParse(`package main; var a = 1`) 668 fileB := mustParse(`package main; var b = 2`) 669 670 // The initialization order must not depend on the parse 671 // order of the files, only on the presentation order to 672 // the type-checker. 673 for _, test := range []struct { 674 files []*ast.File 675 want string 676 }{ 677 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"}, 678 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"}, 679 } { 680 var info Info 681 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil { 682 t.Fatal(err) 683 } 684 if got := fmt.Sprint(info.InitOrder); got != test.want { 685 t.Fatalf("got %s; want %s", got, test.want) 686 } 687 } 688 } 689 690 func TestFiles(t *testing.T) { 691 var sources = []string{ 692 "package p; type T struct{}; func (T) m1() {}", 693 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}", 694 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}", 695 "package p", 696 } 697 698 var conf Config 699 fset := token.NewFileSet() 700 pkg := NewPackage("p", "p") 701 var info Info 702 check := NewChecker(&conf, fset, pkg, &info) 703 704 for i, src := range sources { 705 filename := fmt.Sprintf("sources%d", i) 706 f, err := parser.ParseFile(fset, filename, src, 0) 707 if err != nil { 708 t.Fatal(err) 709 } 710 if err := check.Files([]*ast.File{f}); err != nil { 711 t.Error(err) 712 } 713 } 714 715 // check InitOrder is [x y] 716 var vars []string 717 for _, init := range info.InitOrder { 718 for _, v := range init.Lhs { 719 vars = append(vars, v.Name()) 720 } 721 } 722 if got, want := fmt.Sprint(vars), "[x y]"; got != want { 723 t.Errorf("InitOrder == %s, want %s", got, want) 724 } 725 } 726 727 type testImporter map[string]*Package 728 729 func (m testImporter) Import(path string) (*Package, error) { 730 if pkg := m[path]; pkg != nil { 731 return pkg, nil 732 } 733 return nil, fmt.Errorf("package %q not found", path) 734 } 735 736 func TestSelection(t *testing.T) { 737 selections := make(map[*ast.SelectorExpr]*Selection) 738 739 fset := token.NewFileSet() 740 imports := make(testImporter) 741 conf := Config{Importer: imports} 742 makePkg := func(path, src string) { 743 f, err := parser.ParseFile(fset, path+".go", src, 0) 744 if err != nil { 745 t.Fatal(err) 746 } 747 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections}) 748 if err != nil { 749 t.Fatal(err) 750 } 751 imports[path] = pkg 752 } 753 754 const libSrc = ` 755 package lib 756 type T float64 757 const C T = 3 758 var V T 759 func F() {} 760 func (T) M() {} 761 ` 762 const mainSrc = ` 763 package main 764 import "lib" 765 766 type A struct { 767 *B 768 C 769 } 770 771 type B struct { 772 b int 773 } 774 775 func (B) f(int) 776 777 type C struct { 778 c int 779 } 780 781 func (C) g() 782 func (*C) h() 783 784 func main() { 785 // qualified identifiers 786 var _ lib.T 787 _ = lib.C 788 _ = lib.F 789 _ = lib.V 790 _ = lib.T.M 791 792 // fields 793 _ = A{}.B 794 _ = new(A).B 795 796 _ = A{}.C 797 _ = new(A).C 798 799 _ = A{}.b 800 _ = new(A).b 801 802 _ = A{}.c 803 _ = new(A).c 804 805 // methods 806 _ = A{}.f 807 _ = new(A).f 808 _ = A{}.g 809 _ = new(A).g 810 _ = new(A).h 811 812 _ = B{}.f 813 _ = new(B).f 814 815 _ = C{}.g 816 _ = new(C).g 817 _ = new(C).h 818 819 // method expressions 820 _ = A.f 821 _ = (*A).f 822 _ = B.f 823 _ = (*B).f 824 }` 825 826 wantOut := map[string][2]string{ 827 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"}, 828 829 "A{}.B": {"field (main.A) B *main.B", ".[0]"}, 830 "new(A).B": {"field (*main.A) B *main.B", "->[0]"}, 831 "A{}.C": {"field (main.A) C main.C", ".[1]"}, 832 "new(A).C": {"field (*main.A) C main.C", "->[1]"}, 833 "A{}.b": {"field (main.A) b int", "->[0 0]"}, 834 "new(A).b": {"field (*main.A) b int", "->[0 0]"}, 835 "A{}.c": {"field (main.A) c int", ".[1 0]"}, 836 "new(A).c": {"field (*main.A) c int", "->[1 0]"}, 837 838 "A{}.f": {"method (main.A) f(int)", "->[0 0]"}, 839 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"}, 840 "A{}.g": {"method (main.A) g()", ".[1 0]"}, 841 "new(A).g": {"method (*main.A) g()", "->[1 0]"}, 842 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ? 843 "B{}.f": {"method (main.B) f(int)", ".[0]"}, 844 "new(B).f": {"method (*main.B) f(int)", "->[0]"}, 845 "C{}.g": {"method (main.C) g()", ".[0]"}, 846 "new(C).g": {"method (*main.C) g()", "->[0]"}, 847 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ? 848 849 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"}, 850 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"}, 851 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"}, 852 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"}, 853 } 854 855 makePkg("lib", libSrc) 856 makePkg("main", mainSrc) 857 858 for e, sel := range selections { 859 _ = sel.String() // assertion: must not panic 860 861 start := fset.Position(e.Pos()).Offset 862 end := fset.Position(e.End()).Offset 863 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib) 864 865 direct := "." 866 if sel.Indirect() { 867 direct = "->" 868 } 869 got := [2]string{ 870 sel.String(), 871 fmt.Sprintf("%s%v", direct, sel.Index()), 872 } 873 want := wantOut[syntax] 874 if want != got { 875 t.Errorf("%s: got %q; want %q", syntax, got, want) 876 } 877 delete(wantOut, syntax) 878 879 // We must explicitly assert properties of the 880 // Signature's receiver since it doesn't participate 881 // in Identical() or String(). 882 sig, _ := sel.Type().(*Signature) 883 if sel.Kind() == MethodVal { 884 got := sig.Recv().Type() 885 want := sel.Recv() 886 if !Identical(got, want) { 887 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want) 888 } 889 } else if sig != nil && sig.Recv() != nil { 890 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type()) 891 } 892 } 893 // Assert that all wantOut entries were used exactly once. 894 for syntax := range wantOut { 895 t.Errorf("no ast.Selection found with syntax %q", syntax) 896 } 897 } 898 899 func TestIssue8518(t *testing.T) { 900 fset := token.NewFileSet() 901 imports := make(testImporter) 902 conf := Config{ 903 Error: func(err error) { t.Log(err) }, // don't exit after first error 904 Importer: imports, 905 } 906 makePkg := func(path, src string) { 907 f, err := parser.ParseFile(fset, path, src, 0) 908 if err != nil { 909 t.Fatal(err) 910 } 911 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error 912 imports[path] = pkg 913 } 914 915 const libSrc = ` 916 package a 917 import "missing" 918 const C1 = foo 919 const C2 = missing.C 920 ` 921 922 const mainSrc = ` 923 package main 924 import "a" 925 var _ = a.C1 926 var _ = a.C2 927 ` 928 929 makePkg("a", libSrc) 930 makePkg("main", mainSrc) // don't crash when type-checking this package 931 } 932 933 func TestLookupFieldOrMethod(t *testing.T) { 934 // Test cases assume a lookup of the form a.f or x.f, where a stands for an 935 // addressable value, and x for a non-addressable value (even though a variable 936 // for ease of test case writing). 937 var tests = []struct { 938 src string 939 found bool 940 index []int 941 indirect bool 942 }{ 943 // field lookups 944 {"var x T; type T struct{}", false, nil, false}, 945 {"var x T; type T struct{ f int }", true, []int{0}, false}, 946 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false}, 947 948 // method lookups 949 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false}, 950 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true}, 951 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false}, 952 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false? 953 954 // collisions 955 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false}, 956 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false}, 957 958 // outside methodset 959 // (*T).f method exists, but value of type T is not addressable 960 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true}, 961 } 962 963 for _, test := range tests { 964 pkg, err := pkgFor("test", "package p;"+test.src, nil) 965 if err != nil { 966 t.Errorf("%s: incorrect test case: %s", test.src, err) 967 continue 968 } 969 970 obj := pkg.Scope().Lookup("a") 971 if obj == nil { 972 if obj = pkg.Scope().Lookup("x"); obj == nil { 973 t.Errorf("%s: incorrect test case - no object a or x", test.src) 974 continue 975 } 976 } 977 978 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f") 979 if (f != nil) != test.found { 980 if f == nil { 981 t.Errorf("%s: got no object; want one", test.src) 982 } else { 983 t.Errorf("%s: got object = %v; want none", test.src, f) 984 } 985 } 986 if !sameSlice(index, test.index) { 987 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index) 988 } 989 if indirect != test.indirect { 990 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect) 991 } 992 } 993 } 994 995 func sameSlice(a, b []int) bool { 996 if len(a) != len(b) { 997 return false 998 } 999 for i, x := range a { 1000 if x != b[i] { 1001 return false 1002 } 1003 } 1004 return true 1005 } 1006 1007 // TestScopeLookupParent ensures that (*Scope).LookupParent returns 1008 // the correct result at various positions with the source. 1009 func TestScopeLookupParent(t *testing.T) { 1010 fset := token.NewFileSet() 1011 imports := make(testImporter) 1012 conf := Config{Importer: imports} 1013 mustParse := func(src string) *ast.File { 1014 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments) 1015 if err != nil { 1016 t.Fatal(err) 1017 } 1018 return f 1019 } 1020 var info Info 1021 makePkg := func(path string, files ...*ast.File) { 1022 var err error 1023 imports[path], err = conf.Check(path, fset, files, &info) 1024 if err != nil { 1025 t.Fatal(err) 1026 } 1027 } 1028 1029 makePkg("lib", mustParse("package lib; var X int")) 1030 // Each /*name=kind:line*/ comment makes the test look up the 1031 // name at that point and checks that it resolves to a decl of 1032 // the specified kind and line number. "undef" means undefined. 1033 mainSrc := ` 1034 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/ 1035 package main 1036 1037 import "lib" 1038 import . "lib" 1039 1040 const Pi = 3.1415 1041 type T struct{} 1042 var Y, _ = lib.X, X 1043 1044 func F(){ 1045 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/ 1046 type /*t=undef*/ t /*t=typename:14*/ *t 1047 print(Y) /*Y=var:10*/ 1048 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y 1049 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F 1050 1051 var a []int 1052 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x } 1053 1054 var i interface{} 1055 switch y := i.(type) { /*y=undef*/ 1056 case /*y=undef*/ int /*y=var:23*/ : 1057 case float32, /*y=undef*/ float64 /*y=var:23*/ : 1058 default /*y=var:23*/: 1059 println(y) 1060 } 1061 /*y=undef*/ 1062 1063 switch int := i.(type) { 1064 case /*int=typename:0*/ int /*int=var:31*/ : 1065 println(int) 1066 default /*int=var:31*/ : 1067 } 1068 } 1069 /*main=undef*/ 1070 ` 1071 1072 info.Uses = make(map[*ast.Ident]Object) 1073 f := mustParse(mainSrc) 1074 makePkg("main", f) 1075 mainScope := imports["main"].Scope() 1076 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`) 1077 for _, group := range f.Comments { 1078 for _, comment := range group.List { 1079 // Parse the assertion in the comment. 1080 m := rx.FindStringSubmatch(comment.Text) 1081 if m == nil { 1082 t.Errorf("%s: bad comment: %s", 1083 fset.Position(comment.Pos()), comment.Text) 1084 continue 1085 } 1086 name, want := m[1], m[2] 1087 1088 // Look up the name in the innermost enclosing scope. 1089 inner := mainScope.Innermost(comment.Pos()) 1090 if inner == nil { 1091 t.Errorf("%s: at %s: can't find innermost scope", 1092 fset.Position(comment.Pos()), comment.Text) 1093 continue 1094 } 1095 got := "undef" 1096 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil { 1097 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types.")) 1098 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line) 1099 } 1100 if got != want { 1101 t.Errorf("%s: at %s: %s resolved to %s, want %s", 1102 fset.Position(comment.Pos()), comment.Text, name, got, want) 1103 } 1104 } 1105 } 1106 1107 // Check that for each referring identifier, 1108 // a lookup of its name on the innermost 1109 // enclosing scope returns the correct object. 1110 1111 for id, wantObj := range info.Uses { 1112 inner := mainScope.Innermost(id.Pos()) 1113 if inner == nil { 1114 t.Errorf("%s: can't find innermost scope enclosing %q", 1115 fset.Position(id.Pos()), id.Name) 1116 continue 1117 } 1118 1119 // Exclude selectors and qualified identifiers---lexical 1120 // refs only. (Ideally, we'd see if the AST parent is a 1121 // SelectorExpr, but that requires PathEnclosingInterval 1122 // from golang.org/x/tools/go/ast/astutil.) 1123 if id.Name == "X" { 1124 continue 1125 } 1126 1127 _, gotObj := inner.LookupParent(id.Name, id.Pos()) 1128 if gotObj != wantObj { 1129 t.Errorf("%s: got %v, want %v", 1130 fset.Position(id.Pos()), gotObj, wantObj) 1131 continue 1132 } 1133 } 1134 } 1135 1136 func TestIdentical_issue15173(t *testing.T) { 1137 // Identical should allow nil arguments and be symmetric. 1138 for _, test := range []struct { 1139 x, y Type 1140 want bool 1141 }{ 1142 {Typ[Int], Typ[Int], true}, 1143 {Typ[Int], nil, false}, 1144 {nil, Typ[Int], false}, 1145 {nil, nil, true}, 1146 } { 1147 if got := Identical(test.x, test.y); got != test.want { 1148 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got) 1149 } 1150 } 1151 } 1152 1153 func TestIssue15305(t *testing.T) { 1154 const src = "package p; func f() int16; var _ = f(undef)" 1155 fset := token.NewFileSet() 1156 f, err := parser.ParseFile(fset, "issue15305.go", src, 0) 1157 if err != nil { 1158 t.Fatal(err) 1159 } 1160 conf := Config{ 1161 Error: func(err error) {}, // allow errors 1162 } 1163 info := &Info{ 1164 Types: make(map[ast.Expr]TypeAndValue), 1165 } 1166 conf.Check("p", fset, []*ast.File{f}, info) // ignore result 1167 for e, tv := range info.Types { 1168 if _, ok := e.(*ast.CallExpr); ok { 1169 if tv.Type != Typ[Int16] { 1170 t.Errorf("CallExpr has type %v, want int16", tv.Type) 1171 } 1172 return 1173 } 1174 } 1175 t.Errorf("CallExpr has no type") 1176 } 1177 1178 // TestCompositeLitTypes verifies that Info.Types registers the correct 1179 // types for composite literal expressions and composite literal type 1180 // expressions. 1181 func TestCompositeLitTypes(t *testing.T) { 1182 for _, test := range []struct { 1183 lit, typ string 1184 }{ 1185 {`[16]byte{}`, `[16]byte`}, 1186 {`[...]byte{}`, `[0]byte`}, // test for issue #14092 1187 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092 1188 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092 1189 {`[]int{}`, `[]int`}, 1190 {`map[string]bool{"foo": true}`, `map[string]bool`}, 1191 {`struct{}{}`, `struct{}`}, 1192 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`}, 1193 } { 1194 fset := token.NewFileSet() 1195 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0) 1196 if err != nil { 1197 t.Fatalf("%s: %v", test.lit, err) 1198 } 1199 1200 info := &Info{ 1201 Types: make(map[ast.Expr]TypeAndValue), 1202 } 1203 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil { 1204 t.Fatalf("%s: %v", test.lit, err) 1205 } 1206 1207 cmptype := func(x ast.Expr, want string) { 1208 tv, ok := info.Types[x] 1209 if !ok { 1210 t.Errorf("%s: no Types entry found", test.lit) 1211 return 1212 } 1213 if tv.Type == nil { 1214 t.Errorf("%s: type is nil", test.lit) 1215 return 1216 } 1217 if got := tv.Type.String(); got != want { 1218 t.Errorf("%s: got %v, want %s", test.lit, got, want) 1219 } 1220 } 1221 1222 // test type of composite literal expression 1223 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0] 1224 cmptype(rhs, test.typ) 1225 1226 // test type of composite literal type expression 1227 cmptype(rhs.(*ast.CompositeLit).Type, test.typ) 1228 } 1229 } 1230 1231 // TestObjectParents verifies that objects have parent scopes or not 1232 // as specified by the Object interface. 1233 func TestObjectParents(t *testing.T) { 1234 const src = ` 1235 package p 1236 1237 const C = 0 1238 1239 type T1 struct { 1240 a, b int 1241 T2 1242 } 1243 1244 type T2 interface { 1245 im1() 1246 im2() 1247 } 1248 1249 func (T1) m1() {} 1250 func (*T1) m2() {} 1251 1252 func f(x int) { y := x; print(y) } 1253 ` 1254 1255 fset := token.NewFileSet() 1256 f, err := parser.ParseFile(fset, "src", src, 0) 1257 if err != nil { 1258 t.Fatal(err) 1259 } 1260 1261 info := &Info{ 1262 Defs: make(map[*ast.Ident]Object), 1263 } 1264 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil { 1265 t.Fatal(err) 1266 } 1267 1268 for ident, obj := range info.Defs { 1269 if obj == nil { 1270 // only package names and implicit vars have a nil object 1271 // (in this test we only need to handle the package name) 1272 if ident.Name != "p" { 1273 t.Errorf("%v has nil object", ident) 1274 } 1275 continue 1276 } 1277 1278 // struct fields, type-associated and interface methods 1279 // have no parent scope 1280 wantParent := true 1281 switch obj := obj.(type) { 1282 case *Var: 1283 if obj.IsField() { 1284 wantParent = false 1285 } 1286 case *Func: 1287 if obj.Type().(*Signature).Recv() != nil { // method 1288 wantParent = false 1289 } 1290 } 1291 1292 gotParent := obj.Parent() != nil 1293 switch { 1294 case gotParent && !wantParent: 1295 t.Errorf("%v: want no parent, got %s", ident, obj.Parent()) 1296 case !gotParent && wantParent: 1297 t.Errorf("%v: no parent found", ident) 1298 } 1299 } 1300 } 1301 1302 func TestAliases(t *testing.T) { 1303 testenv.MustHaveGoBuild(t) 1304 1305 const src = ` 1306 package b 1307 1308 import ( 1309 "./testdata/alias" 1310 a "./testdata/alias" 1311 "math" 1312 ) 1313 1314 const ( 1315 c1 = alias.Pi1 1316 c2 => a.Pi1 1317 c3 => a.Pi2 1318 c4 => math.Pi 1319 ) 1320 1321 var ( 1322 v1 => alias.Default 1323 v2 => a.Default 1324 v3 = f1 1325 ) 1326 1327 type ( 1328 t1 => alias.Context 1329 t2 => a.Context 1330 ) 1331 1332 func f1 => alias.Sin 1333 func f2 => a.Sin 1334 1335 func _() { 1336 assert(c1 == alias.Pi1 && c2 == a.Pi1 && c3 == a.Pi2 && c4 == math.Pi) 1337 assert(c2 == c2 && c2 == c3 && c3 == c4) 1338 v1 = v2 // must be assignable 1339 var _ *t1 = new(t2) // must be assignable 1340 var _ t2 = alias.Default 1341 f1(1) // must be callable 1342 f2(1) 1343 _ = alias.Sin(1) 1344 _ = a.Sin(1) 1345 } 1346 ` 1347 1348 if out := compile(t, "testdata", "alias.go"); out != "" { 1349 defer os.Remove(out) 1350 } 1351 1352 DefPredeclaredTestFuncs() // declare assert built-in for testing 1353 mustTypecheck(t, "Aliases", src, nil) 1354 } 1355 1356 func compile(t *testing.T, dirname, filename string) string { 1357 cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", filename) 1358 cmd.Dir = dirname 1359 out, err := cmd.CombinedOutput() 1360 if err != nil { 1361 t.Logf("%s", out) 1362 t.Fatalf("go tool compile %s failed: %s", filename, err) 1363 } 1364 // filename should end with ".go" 1365 return filepath.Join(dirname, filename[:len(filename)-2]+"o") 1366 } 1367 1368 func TestAliasDefUses(t *testing.T) { 1369 testenv.MustHaveGoBuild(t) 1370 1371 const src = ` 1372 package p 1373 1374 import( 1375 "go/build" 1376 "go/types" 1377 ) 1378 1379 // Defs 1380 const Invalid => types.Invalid 1381 type Struct => types.Struct 1382 var Default => build.Default 1383 func Implements => types.Implements 1384 1385 // Uses 1386 const _ = Invalid 1387 var _ types.Struct = Struct{} // types must be identical 1388 var _ build.Context = Default 1389 var _ = Implements(nil, nil) 1390 ` 1391 1392 info := Info{ 1393 Defs: make(map[*ast.Ident]Object), 1394 Uses: make(map[*ast.Ident]Object), 1395 } 1396 mustTypecheck(t, "TestAliasDefUses", src, &info) 1397 1398 // verify Defs 1399 defs := map[string]string{ 1400 "Invalid": "types.Invalid", 1401 "Struct": "types.Struct", 1402 "Default": "build.Default", 1403 "Implements": "types.Implements", 1404 } 1405 1406 for ident, obj := range info.Defs { 1407 if alias, ok := obj.(*Alias); ok { 1408 if want := defs[ident.Name]; want != "" { 1409 orig := alias.Orig() 1410 if got := orig.Pkg().Name() + "." + orig.Name(); got != want { 1411 t.Errorf("%v: got %v, want %v", ident, got, want) 1412 } 1413 delete(defs, ident.Name) // mark as found 1414 } else { 1415 t.Errorf("unexpected alias def of %v", ident) 1416 } 1417 } 1418 } 1419 1420 if len(defs) != 0 { 1421 t.Errorf("missing aliases: %v", defs) 1422 } 1423 1424 // verify Uses 1425 uses := map[string]string{ 1426 "Invalid": "types.Invalid", 1427 "Struct": "types.Struct", 1428 "Default": "build.Default", 1429 "Implements": "types.Implements", 1430 } 1431 1432 for ident, obj := range info.Uses { 1433 if alias, ok := obj.(*Alias); ok { 1434 if want := uses[ident.Name]; want != "" { 1435 orig := alias.Orig() 1436 if got := orig.Pkg().Name() + "." + orig.Name(); got != want { 1437 t.Errorf("%v: got %v, want %v", ident, got, want) 1438 } 1439 delete(uses, ident.Name) // mark as found 1440 } else { 1441 t.Errorf("unexpected alias use of %v", ident) 1442 } 1443 } 1444 } 1445 1446 if len(uses) != 0 { 1447 t.Errorf("missing aliases: %v", defs) 1448 } 1449 }