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