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