github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/go/types/typexpr.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 // This file implements type-checking of identifiers and type expressions. 6 7 package types 8 9 import ( 10 "go/ast" 11 "go/constant" 12 "go/token" 13 "sort" 14 "strconv" 15 ) 16 17 // ident type-checks identifier e and initializes x with the value or type of e. 18 // If an error occurred, x.mode is set to invalid. 19 // For the meaning of def and path, see check.typ, below. 20 // 21 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, path []*TypeName) { 22 x.mode = invalid 23 x.expr = e 24 25 scope, obj := check.scope.LookupParent(e.Name, check.pos) 26 if obj == nil { 27 if e.Name == "_" { 28 check.errorf(e.Pos(), "cannot use _ as value or type") 29 } else { 30 check.errorf(e.Pos(), "undeclared name: %s", e.Name) 31 } 32 return 33 } 34 check.recordUse(e, obj) 35 36 check.objDecl(obj, def, path) 37 typ := obj.Type() 38 assert(typ != nil) 39 40 // The object may be dot-imported: If so, remove its package from 41 // the map of unused dot imports for the respective file scope. 42 // (This code is only needed for dot-imports. Without them, 43 // we only have to mark variables, see *Var case below). 44 if pkg := obj.Pkg(); pkg != check.pkg && pkg != nil { 45 delete(check.unusedDotImports[scope], pkg) 46 } 47 48 // An alias stands for the original object; use that one instead. 49 // TODO(gri) We should be able to factor out the Typ[Invalid] test. 50 if alias, _ := obj.(*Alias); alias != nil { 51 obj = original(obj) 52 if obj == nil || typ == Typ[Invalid] { 53 return 54 } 55 assert(typ == obj.Type()) 56 } 57 58 switch obj := obj.(type) { 59 case *PkgName: 60 check.errorf(e.Pos(), "use of package %s not in selector", obj.name) 61 return 62 63 case *Const: 64 check.addDeclDep(obj) 65 if typ == Typ[Invalid] { 66 return 67 } 68 if obj == universeIota { 69 if check.iota == nil { 70 check.errorf(e.Pos(), "cannot use iota outside constant declaration") 71 return 72 } 73 x.val = check.iota 74 } else { 75 x.val = obj.val 76 } 77 assert(x.val != nil) 78 x.mode = constant_ 79 80 case *TypeName: 81 x.mode = typexpr 82 // check for cycle 83 // (it's ok to iterate forward because each named type appears at most once in path) 84 for i, prev := range path { 85 if prev == obj { 86 check.errorf(obj.pos, "illegal cycle in declaration of %s", obj.name) 87 // print cycle 88 for _, obj := range path[i:] { 89 check.errorf(obj.Pos(), "\t%s refers to", obj.Name()) // secondary error, \t indented 90 } 91 check.errorf(obj.Pos(), "\t%s", obj.Name()) 92 // maintain x.mode == typexpr despite error 93 typ = Typ[Invalid] 94 break 95 } 96 } 97 98 case *Var: 99 if obj.pkg == check.pkg { 100 obj.used = true 101 } 102 check.addDeclDep(obj) 103 if typ == Typ[Invalid] { 104 return 105 } 106 x.mode = variable 107 108 case *Func: 109 check.addDeclDep(obj) 110 x.mode = value 111 112 case *Builtin: 113 x.id = obj.id 114 x.mode = builtin 115 116 case *Nil: 117 x.mode = value 118 119 default: 120 unreachable() 121 } 122 123 x.typ = typ 124 } 125 126 // typExpr type-checks the type expression e and returns its type, or Typ[Invalid]. 127 // If def != nil, e is the type specification for the named type def, declared 128 // in a type declaration, and def.underlying will be set to the type of e before 129 // any components of e are type-checked. Path contains the path of named types 130 // referring to this type. 131 // 132 func (check *Checker) typExpr(e ast.Expr, def *Named, path []*TypeName) (T Type) { 133 if trace { 134 check.trace(e.Pos(), "%s", e) 135 check.indent++ 136 defer func() { 137 check.indent-- 138 check.trace(e.Pos(), "=> %s", T) 139 }() 140 } 141 142 T = check.typExprInternal(e, def, path) 143 assert(isTyped(T)) 144 check.recordTypeAndValue(e, typexpr, T, nil) 145 146 return 147 } 148 149 func (check *Checker) typ(e ast.Expr) Type { 150 return check.typExpr(e, nil, nil) 151 } 152 153 // funcType type-checks a function or method type. 154 func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) { 155 scope := NewScope(check.scope, token.NoPos, token.NoPos, "function") 156 check.recordScope(ftyp, scope) 157 158 recvList, _ := check.collectParams(scope, recvPar, false) 159 params, variadic := check.collectParams(scope, ftyp.Params, true) 160 results, _ := check.collectParams(scope, ftyp.Results, false) 161 162 if recvPar != nil { 163 // recv parameter list present (may be empty) 164 // spec: "The receiver is specified via an extra parameter section preceding the 165 // method name. That parameter section must declare a single parameter, the receiver." 166 var recv *Var 167 switch len(recvList) { 168 case 0: 169 check.error(recvPar.Pos(), "method is missing receiver") 170 recv = NewParam(0, nil, "", Typ[Invalid]) // ignore recv below 171 default: 172 // more than one receiver 173 check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver") 174 fallthrough // continue with first receiver 175 case 1: 176 recv = recvList[0] 177 } 178 // spec: "The receiver type must be of the form T or *T where T is a type name." 179 // (ignore invalid types - error was reported before) 180 if t, _ := deref(recv.typ); t != Typ[Invalid] { 181 var err string 182 if T, _ := t.(*Named); T != nil { 183 // spec: "The type denoted by T is called the receiver base type; it must not 184 // be a pointer or interface type and it must be declared in the same package 185 // as the method." 186 if T.obj.pkg != check.pkg { 187 err = "type not defined in this package" 188 } else { 189 // TODO(gri) This is not correct if the underlying type is unknown yet. 190 switch u := T.underlying.(type) { 191 case *Basic: 192 // unsafe.Pointer is treated like a regular pointer 193 if u.kind == UnsafePointer { 194 err = "unsafe.Pointer" 195 } 196 case *Pointer, *Interface: 197 err = "pointer or interface type" 198 } 199 } 200 } else { 201 err = "basic or unnamed type" 202 } 203 if err != "" { 204 check.errorf(recv.pos, "invalid receiver %s (%s)", recv.typ, err) 205 // ok to continue 206 } 207 } 208 sig.recv = recv 209 } 210 211 sig.scope = scope 212 sig.params = NewTuple(params...) 213 sig.results = NewTuple(results...) 214 sig.variadic = variadic 215 } 216 217 // typExprInternal drives type checking of types. 218 // Must only be called by typExpr. 219 // 220 func (check *Checker) typExprInternal(e ast.Expr, def *Named, path []*TypeName) Type { 221 switch e := e.(type) { 222 case *ast.BadExpr: 223 // ignore - error reported before 224 225 case *ast.Ident: 226 var x operand 227 check.ident(&x, e, def, path) 228 229 switch x.mode { 230 case typexpr: 231 typ := x.typ 232 def.setUnderlying(typ) 233 return typ 234 case invalid: 235 // ignore - error reported before 236 case novalue: 237 check.errorf(x.pos(), "%s used as type", &x) 238 default: 239 check.errorf(x.pos(), "%s is not a type", &x) 240 } 241 242 case *ast.SelectorExpr: 243 var x operand 244 check.selector(&x, e) 245 246 switch x.mode { 247 case typexpr: 248 typ := x.typ 249 def.setUnderlying(typ) 250 return typ 251 case invalid: 252 // ignore - error reported before 253 case novalue: 254 check.errorf(x.pos(), "%s used as type", &x) 255 default: 256 check.errorf(x.pos(), "%s is not a type", &x) 257 } 258 259 case *ast.ParenExpr: 260 return check.typExpr(e.X, def, path) 261 262 case *ast.ArrayType: 263 if e.Len != nil { 264 typ := new(Array) 265 def.setUnderlying(typ) 266 typ.len = check.arrayLength(e.Len) 267 typ.elem = check.typExpr(e.Elt, nil, path) 268 return typ 269 270 } else { 271 typ := new(Slice) 272 def.setUnderlying(typ) 273 typ.elem = check.typ(e.Elt) 274 return typ 275 } 276 277 case *ast.StructType: 278 typ := new(Struct) 279 def.setUnderlying(typ) 280 check.structType(typ, e, path) 281 return typ 282 283 case *ast.StarExpr: 284 typ := new(Pointer) 285 def.setUnderlying(typ) 286 typ.base = check.typ(e.X) 287 return typ 288 289 case *ast.FuncType: 290 typ := new(Signature) 291 def.setUnderlying(typ) 292 check.funcType(typ, nil, e) 293 return typ 294 295 case *ast.InterfaceType: 296 typ := new(Interface) 297 def.setUnderlying(typ) 298 check.interfaceType(typ, e, def, path) 299 return typ 300 301 case *ast.MapType: 302 typ := new(Map) 303 def.setUnderlying(typ) 304 305 typ.key = check.typ(e.Key) 306 typ.elem = check.typ(e.Value) 307 308 // spec: "The comparison operators == and != must be fully defined 309 // for operands of the key type; thus the key type must not be a 310 // function, map, or slice." 311 // 312 // Delay this check because it requires fully setup types; 313 // it is safe to continue in any case (was issue 6667). 314 check.delay(func() { 315 if !Comparable(typ.key) { 316 check.errorf(e.Key.Pos(), "invalid map key type %s", typ.key) 317 } 318 }) 319 320 return typ 321 322 case *ast.ChanType: 323 typ := new(Chan) 324 def.setUnderlying(typ) 325 326 dir := SendRecv 327 switch e.Dir { 328 case ast.SEND | ast.RECV: 329 // nothing to do 330 case ast.SEND: 331 dir = SendOnly 332 case ast.RECV: 333 dir = RecvOnly 334 default: 335 check.invalidAST(e.Pos(), "unknown channel direction %d", e.Dir) 336 // ok to continue 337 } 338 339 typ.dir = dir 340 typ.elem = check.typ(e.Value) 341 return typ 342 343 default: 344 check.errorf(e.Pos(), "%s is not a type", e) 345 } 346 347 typ := Typ[Invalid] 348 def.setUnderlying(typ) 349 return typ 350 } 351 352 // typeOrNil type-checks the type expression (or nil value) e 353 // and returns the typ of e, or nil. 354 // If e is neither a type nor nil, typOrNil returns Typ[Invalid]. 355 // 356 func (check *Checker) typOrNil(e ast.Expr) Type { 357 var x operand 358 check.rawExpr(&x, e, nil) 359 switch x.mode { 360 case invalid: 361 // ignore - error reported before 362 case novalue: 363 check.errorf(x.pos(), "%s used as type", &x) 364 case typexpr: 365 return x.typ 366 case value: 367 if x.isNil() { 368 return nil 369 } 370 fallthrough 371 default: 372 check.errorf(x.pos(), "%s is not a type", &x) 373 } 374 return Typ[Invalid] 375 } 376 377 func (check *Checker) arrayLength(e ast.Expr) int64 { 378 var x operand 379 check.expr(&x, e) 380 if x.mode != constant_ { 381 if x.mode != invalid { 382 check.errorf(x.pos(), "array length %s must be constant", &x) 383 } 384 return 0 385 } 386 if isUntyped(x.typ) || isInteger(x.typ) { 387 if val := constant.ToInt(x.val); val.Kind() == constant.Int { 388 if representableConst(val, check.conf, Typ[Int], nil) { 389 if n, ok := constant.Int64Val(val); ok && n >= 0 { 390 return n 391 } 392 check.errorf(x.pos(), "invalid array length %s", &x) 393 return 0 394 } 395 } 396 } 397 check.errorf(x.pos(), "array length %s must be integer", &x) 398 return 0 399 } 400 401 func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool) { 402 if list == nil { 403 return 404 } 405 406 var named, anonymous bool 407 for i, field := range list.List { 408 ftype := field.Type 409 if t, _ := ftype.(*ast.Ellipsis); t != nil { 410 ftype = t.Elt 411 if variadicOk && i == len(list.List)-1 { 412 variadic = true 413 } else { 414 check.invalidAST(field.Pos(), "... not permitted") 415 // ignore ... and continue 416 } 417 } 418 typ := check.typ(ftype) 419 // The parser ensures that f.Tag is nil and we don't 420 // care if a constructed AST contains a non-nil tag. 421 if len(field.Names) > 0 { 422 // named parameter 423 for _, name := range field.Names { 424 if name.Name == "" { 425 check.invalidAST(name.Pos(), "anonymous parameter") 426 // ok to continue 427 } 428 par := NewParam(name.Pos(), check.pkg, name.Name, typ) 429 check.declare(scope, name, par, scope.pos) 430 params = append(params, par) 431 } 432 named = true 433 } else { 434 // anonymous parameter 435 par := NewParam(ftype.Pos(), check.pkg, "", typ) 436 check.recordImplicit(field, par) 437 params = append(params, par) 438 anonymous = true 439 } 440 } 441 442 if named && anonymous { 443 check.invalidAST(list.Pos(), "list contains both named and anonymous parameters") 444 // ok to continue 445 } 446 447 // For a variadic function, change the last parameter's type from T to []T. 448 if variadic && len(params) > 0 { 449 last := params[len(params)-1] 450 last.typ = &Slice{elem: last.typ} 451 } 452 453 return 454 } 455 456 func (check *Checker) declareInSet(oset *objset, pos token.Pos, obj Object) bool { 457 if alt := oset.insert(obj); alt != nil { 458 check.errorf(pos, "%s redeclared", obj.Name()) 459 check.reportAltDecl(alt) 460 return false 461 } 462 return true 463 } 464 465 func (check *Checker) interfaceType(iface *Interface, ityp *ast.InterfaceType, def *Named, path []*TypeName) { 466 // empty interface: common case 467 if ityp.Methods == nil { 468 return 469 } 470 471 // The parser ensures that field tags are nil and we don't 472 // care if a constructed AST contains non-nil tags. 473 474 // use named receiver type if available (for better error messages) 475 var recvTyp Type = iface 476 if def != nil { 477 recvTyp = def 478 } 479 480 // Phase 1: Collect explicitly declared methods, the corresponding 481 // signature (AST) expressions, and the list of embedded 482 // type (AST) expressions. Do not resolve signatures or 483 // embedded types yet to avoid cycles referring to this 484 // interface. 485 486 var ( 487 mset objset 488 signatures []ast.Expr // list of corresponding method signatures 489 embedded []ast.Expr // list of embedded types 490 ) 491 for _, f := range ityp.Methods.List { 492 if len(f.Names) > 0 { 493 // The parser ensures that there's only one method 494 // and we don't care if a constructed AST has more. 495 name := f.Names[0] 496 pos := name.Pos() 497 // spec: "As with all method sets, in an interface type, 498 // each method must have a unique non-blank name." 499 if name.Name == "_" { 500 check.errorf(pos, "invalid method name _") 501 continue 502 } 503 // Don't type-check signature yet - use an 504 // empty signature now and update it later. 505 // Since we know the receiver, set it up now 506 // (required to avoid crash in ptrRecv; see 507 // e.g. test case for issue 6638). 508 // TODO(gri) Consider marking methods signatures 509 // as incomplete, for better error messages. See 510 // also the T4 and T5 tests in testdata/cycles2.src. 511 sig := new(Signature) 512 sig.recv = NewVar(pos, check.pkg, "", recvTyp) 513 m := NewFunc(pos, check.pkg, name.Name, sig) 514 if check.declareInSet(&mset, pos, m) { 515 iface.methods = append(iface.methods, m) 516 iface.allMethods = append(iface.allMethods, m) 517 signatures = append(signatures, f.Type) 518 check.recordDef(name, m) 519 } 520 } else { 521 // embedded type 522 embedded = append(embedded, f.Type) 523 } 524 } 525 526 // Phase 2: Resolve embedded interfaces. Because an interface must not 527 // embed itself (directly or indirectly), each embedded interface 528 // can be fully resolved without depending on any method of this 529 // interface (if there is a cycle or another error, the embedded 530 // type resolves to an invalid type and is ignored). 531 // In particular, the list of methods for each embedded interface 532 // must be complete (it cannot depend on this interface), and so 533 // those methods can be added to the list of all methods of this 534 // interface. 535 536 for _, e := range embedded { 537 pos := e.Pos() 538 typ := check.typExpr(e, nil, path) 539 // Determine underlying embedded (possibly incomplete) type 540 // by following its forward chain. 541 named, _ := typ.(*Named) 542 under := underlying(named) 543 embed, _ := under.(*Interface) 544 if embed == nil { 545 if typ != Typ[Invalid] { 546 check.errorf(pos, "%s is not an interface", typ) 547 } 548 continue 549 } 550 iface.embeddeds = append(iface.embeddeds, named) 551 // collect embedded methods 552 for _, m := range embed.allMethods { 553 if check.declareInSet(&mset, pos, m) { 554 iface.allMethods = append(iface.allMethods, m) 555 } 556 } 557 } 558 559 // Phase 3: At this point all methods have been collected for this interface. 560 // It is now safe to type-check the signatures of all explicitly 561 // declared methods, even if they refer to this interface via a cycle 562 // and embed the methods of this interface in a parameter of interface 563 // type. 564 565 for i, m := range iface.methods { 566 expr := signatures[i] 567 typ := check.typ(expr) 568 sig, _ := typ.(*Signature) 569 if sig == nil { 570 if typ != Typ[Invalid] { 571 check.invalidAST(expr.Pos(), "%s is not a method signature", typ) 572 } 573 continue // keep method with empty method signature 574 } 575 // update signature, but keep recv that was set up before 576 old := m.typ.(*Signature) 577 sig.recv = old.recv 578 *old = *sig // update signature (don't replace it!) 579 } 580 581 // TODO(gri) The list of explicit methods is only sorted for now to 582 // produce the same Interface as NewInterface. We may be able to 583 // claim source order in the future. Revisit. 584 sort.Sort(byUniqueMethodName(iface.methods)) 585 586 // TODO(gri) The list of embedded types is only sorted for now to 587 // produce the same Interface as NewInterface. We may be able to 588 // claim source order in the future. Revisit. 589 sort.Sort(byUniqueTypeName(iface.embeddeds)) 590 591 sort.Sort(byUniqueMethodName(iface.allMethods)) 592 } 593 594 // byUniqueTypeName named type lists can be sorted by their unique type names. 595 type byUniqueTypeName []*Named 596 597 func (a byUniqueTypeName) Len() int { return len(a) } 598 func (a byUniqueTypeName) Less(i, j int) bool { return a[i].obj.Id() < a[j].obj.Id() } 599 func (a byUniqueTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 600 601 // byUniqueMethodName method lists can be sorted by their unique method names. 602 type byUniqueMethodName []*Func 603 604 func (a byUniqueMethodName) Len() int { return len(a) } 605 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() } 606 func (a byUniqueMethodName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 607 608 func (check *Checker) tag(t *ast.BasicLit) string { 609 if t != nil { 610 if t.Kind == token.STRING { 611 if val, err := strconv.Unquote(t.Value); err == nil { 612 return val 613 } 614 } 615 check.invalidAST(t.Pos(), "incorrect tag syntax: %q", t.Value) 616 } 617 return "" 618 } 619 620 func (check *Checker) structType(styp *Struct, e *ast.StructType, path []*TypeName) { 621 list := e.Fields 622 if list == nil { 623 return 624 } 625 626 // struct fields and tags 627 var fields []*Var 628 var tags []string 629 630 // for double-declaration checks 631 var fset objset 632 633 // current field typ and tag 634 var typ Type 635 var tag string 636 // anonymous != nil indicates an anonymous field. 637 add := func(field *ast.Field, ident *ast.Ident, anonymous *TypeName, pos token.Pos) { 638 if tag != "" && tags == nil { 639 tags = make([]string, len(fields)) 640 } 641 if tags != nil { 642 tags = append(tags, tag) 643 } 644 645 name := ident.Name 646 fld := NewField(pos, check.pkg, name, typ, anonymous != nil) 647 // spec: "Within a struct, non-blank field names must be unique." 648 if name == "_" || check.declareInSet(&fset, pos, fld) { 649 fields = append(fields, fld) 650 check.recordDef(ident, fld) 651 } 652 if anonymous != nil { 653 check.recordUse(ident, anonymous) 654 } 655 } 656 657 for _, f := range list.List { 658 typ = check.typExpr(f.Type, nil, path) 659 tag = check.tag(f.Tag) 660 if len(f.Names) > 0 { 661 // named fields 662 for _, name := range f.Names { 663 add(f, name, nil, name.Pos()) 664 } 665 } else { 666 // anonymous field 667 name := anonymousFieldIdent(f.Type) 668 pos := f.Type.Pos() 669 t, isPtr := deref(typ) 670 switch t := t.(type) { 671 case *Basic: 672 if t == Typ[Invalid] { 673 // error was reported before 674 continue 675 } 676 // unsafe.Pointer is treated like a regular pointer 677 if t.kind == UnsafePointer { 678 check.errorf(pos, "anonymous field type cannot be unsafe.Pointer") 679 continue 680 } 681 add(f, name, Universe.Lookup(t.name).(*TypeName), pos) 682 683 case *Named: 684 // spec: "An embedded type must be specified as a type name 685 // T or as a pointer to a non-interface type name *T, and T 686 // itself may not be a pointer type." 687 switch u := t.underlying.(type) { 688 case *Basic: 689 // unsafe.Pointer is treated like a regular pointer 690 if u.kind == UnsafePointer { 691 check.errorf(pos, "anonymous field type cannot be unsafe.Pointer") 692 continue 693 } 694 case *Pointer: 695 check.errorf(pos, "anonymous field type cannot be a pointer") 696 continue 697 case *Interface: 698 if isPtr { 699 check.errorf(pos, "anonymous field type cannot be a pointer to an interface") 700 continue 701 } 702 } 703 add(f, name, t.obj, pos) 704 705 default: 706 check.invalidAST(pos, "anonymous field type %s must be named", typ) 707 } 708 } 709 } 710 711 styp.fields = fields 712 styp.tags = tags 713 } 714 715 func anonymousFieldIdent(e ast.Expr) *ast.Ident { 716 switch e := e.(type) { 717 case *ast.Ident: 718 return e 719 case *ast.StarExpr: 720 return anonymousFieldIdent(e.X) 721 case *ast.SelectorExpr: 722 return e.Sel 723 } 724 return nil // invalid anonymous field 725 }