github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/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 !x.isInteger() { 377 check.errorf(x.pos(), "array length %s must be integer", &x) 378 return 0 379 } 380 n, ok := constant.Int64Val(x.val) 381 if !ok || n < 0 { 382 check.errorf(x.pos(), "invalid array length %s", &x) 383 return 0 384 } 385 return n 386 } 387 388 func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool) { 389 if list == nil { 390 return 391 } 392 393 var named, anonymous bool 394 for i, field := range list.List { 395 ftype := field.Type 396 if t, _ := ftype.(*ast.Ellipsis); t != nil { 397 ftype = t.Elt 398 if variadicOk && i == len(list.List)-1 { 399 variadic = true 400 } else { 401 check.invalidAST(field.Pos(), "... not permitted") 402 // ignore ... and continue 403 } 404 } 405 typ := check.typ(ftype) 406 // The parser ensures that f.Tag is nil and we don't 407 // care if a constructed AST contains a non-nil tag. 408 if len(field.Names) > 0 { 409 // named parameter 410 for _, name := range field.Names { 411 if name.Name == "" { 412 check.invalidAST(name.Pos(), "anonymous parameter") 413 // ok to continue 414 } 415 par := NewParam(name.Pos(), check.pkg, name.Name, typ) 416 check.declare(scope, name, par, scope.pos) 417 params = append(params, par) 418 } 419 named = true 420 } else { 421 // anonymous parameter 422 par := NewParam(ftype.Pos(), check.pkg, "", typ) 423 check.recordImplicit(field, par) 424 params = append(params, par) 425 anonymous = true 426 } 427 } 428 429 if named && anonymous { 430 check.invalidAST(list.Pos(), "list contains both named and anonymous parameters") 431 // ok to continue 432 } 433 434 // For a variadic function, change the last parameter's type from T to []T. 435 if variadic && len(params) > 0 { 436 last := params[len(params)-1] 437 last.typ = &Slice{elem: last.typ} 438 } 439 440 return 441 } 442 443 func (check *Checker) declareInSet(oset *objset, pos token.Pos, obj Object) bool { 444 if alt := oset.insert(obj); alt != nil { 445 check.errorf(pos, "%s redeclared", obj.Name()) 446 check.reportAltDecl(alt) 447 return false 448 } 449 return true 450 } 451 452 func (check *Checker) interfaceType(iface *Interface, ityp *ast.InterfaceType, def *Named, path []*TypeName) { 453 // empty interface: common case 454 if ityp.Methods == nil { 455 return 456 } 457 458 // The parser ensures that field tags are nil and we don't 459 // care if a constructed AST contains non-nil tags. 460 461 // use named receiver type if available (for better error messages) 462 var recvTyp Type = iface 463 if def != nil { 464 recvTyp = def 465 } 466 467 // Phase 1: Collect explicitly declared methods, the corresponding 468 // signature (AST) expressions, and the list of embedded 469 // type (AST) expressions. Do not resolve signatures or 470 // embedded types yet to avoid cycles referring to this 471 // interface. 472 473 var ( 474 mset objset 475 signatures []ast.Expr // list of corresponding method signatures 476 embedded []ast.Expr // list of embedded types 477 ) 478 for _, f := range ityp.Methods.List { 479 if len(f.Names) > 0 { 480 // The parser ensures that there's only one method 481 // and we don't care if a constructed AST has more. 482 name := f.Names[0] 483 pos := name.Pos() 484 // spec: "As with all method sets, in an interface type, 485 // each method must have a unique non-blank name." 486 if name.Name == "_" { 487 check.errorf(pos, "invalid method name _") 488 continue 489 } 490 // Don't type-check signature yet - use an 491 // empty signature now and update it later. 492 // Since we know the receiver, set it up now 493 // (required to avoid crash in ptrRecv; see 494 // e.g. test case for issue 6638). 495 // TODO(gri) Consider marking methods signatures 496 // as incomplete, for better error messages. See 497 // also the T4 and T5 tests in testdata/cycles2.src. 498 sig := new(Signature) 499 sig.recv = NewVar(pos, check.pkg, "", recvTyp) 500 m := NewFunc(pos, check.pkg, name.Name, sig) 501 if check.declareInSet(&mset, pos, m) { 502 iface.methods = append(iface.methods, m) 503 iface.allMethods = append(iface.allMethods, m) 504 signatures = append(signatures, f.Type) 505 check.recordDef(name, m) 506 } 507 } else { 508 // embedded type 509 embedded = append(embedded, f.Type) 510 } 511 } 512 513 // Phase 2: Resolve embedded interfaces. Because an interface must not 514 // embed itself (directly or indirectly), each embedded interface 515 // can be fully resolved without depending on any method of this 516 // interface (if there is a cycle or another error, the embedded 517 // type resolves to an invalid type and is ignored). 518 // In particular, the list of methods for each embedded interface 519 // must be complete (it cannot depend on this interface), and so 520 // those methods can be added to the list of all methods of this 521 // interface. 522 523 for _, e := range embedded { 524 pos := e.Pos() 525 typ := check.typExpr(e, nil, path) 526 // Determine underlying embedded (possibly incomplete) type 527 // by following its forward chain. 528 named, _ := typ.(*Named) 529 under := underlying(named) 530 embed, _ := under.(*Interface) 531 if embed == nil { 532 if typ != Typ[Invalid] { 533 check.errorf(pos, "%s is not an interface", typ) 534 } 535 continue 536 } 537 iface.embeddeds = append(iface.embeddeds, named) 538 // collect embedded methods 539 for _, m := range embed.allMethods { 540 if check.declareInSet(&mset, pos, m) { 541 iface.allMethods = append(iface.allMethods, m) 542 } 543 } 544 } 545 546 // Phase 3: At this point all methods have been collected for this interface. 547 // It is now safe to type-check the signatures of all explicitly 548 // declared methods, even if they refer to this interface via a cycle 549 // and embed the methods of this interface in a parameter of interface 550 // type. 551 552 for i, m := range iface.methods { 553 expr := signatures[i] 554 typ := check.typ(expr) 555 sig, _ := typ.(*Signature) 556 if sig == nil { 557 if typ != Typ[Invalid] { 558 check.invalidAST(expr.Pos(), "%s is not a method signature", typ) 559 } 560 continue // keep method with empty method signature 561 } 562 // update signature, but keep recv that was set up before 563 old := m.typ.(*Signature) 564 sig.recv = old.recv 565 *old = *sig // update signature (don't replace it!) 566 } 567 568 // TODO(gri) The list of explicit methods is only sorted for now to 569 // produce the same Interface as NewInterface. We may be able to 570 // claim source order in the future. Revisit. 571 sort.Sort(byUniqueMethodName(iface.methods)) 572 573 // TODO(gri) The list of embedded types is only sorted for now to 574 // produce the same Interface as NewInterface. We may be able to 575 // claim source order in the future. Revisit. 576 sort.Sort(byUniqueTypeName(iface.embeddeds)) 577 578 sort.Sort(byUniqueMethodName(iface.allMethods)) 579 } 580 581 // byUniqueTypeName named type lists can be sorted by their unique type names. 582 type byUniqueTypeName []*Named 583 584 func (a byUniqueTypeName) Len() int { return len(a) } 585 func (a byUniqueTypeName) Less(i, j int) bool { return a[i].obj.Id() < a[j].obj.Id() } 586 func (a byUniqueTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 587 588 // byUniqueMethodName method lists can be sorted by their unique method names. 589 type byUniqueMethodName []*Func 590 591 func (a byUniqueMethodName) Len() int { return len(a) } 592 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() } 593 func (a byUniqueMethodName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 594 595 func (check *Checker) tag(t *ast.BasicLit) string { 596 if t != nil { 597 if t.Kind == token.STRING { 598 if val, err := strconv.Unquote(t.Value); err == nil { 599 return val 600 } 601 } 602 check.invalidAST(t.Pos(), "incorrect tag syntax: %q", t.Value) 603 } 604 return "" 605 } 606 607 func (check *Checker) structType(styp *Struct, e *ast.StructType, path []*TypeName) { 608 list := e.Fields 609 if list == nil { 610 return 611 } 612 613 // struct fields and tags 614 var fields []*Var 615 var tags []string 616 617 // for double-declaration checks 618 var fset objset 619 620 // current field typ and tag 621 var typ Type 622 var tag string 623 // anonymous != nil indicates an anonymous field. 624 add := func(field *ast.Field, ident *ast.Ident, anonymous *TypeName, pos token.Pos) { 625 if tag != "" && tags == nil { 626 tags = make([]string, len(fields)) 627 } 628 if tags != nil { 629 tags = append(tags, tag) 630 } 631 632 name := ident.Name 633 fld := NewField(pos, check.pkg, name, typ, anonymous != nil) 634 // spec: "Within a struct, non-blank field names must be unique." 635 if name == "_" || check.declareInSet(&fset, pos, fld) { 636 fields = append(fields, fld) 637 check.recordDef(ident, fld) 638 } 639 if anonymous != nil { 640 check.recordUse(ident, anonymous) 641 } 642 } 643 644 for _, f := range list.List { 645 typ = check.typExpr(f.Type, nil, path) 646 tag = check.tag(f.Tag) 647 if len(f.Names) > 0 { 648 // named fields 649 for _, name := range f.Names { 650 add(f, name, nil, name.Pos()) 651 } 652 } else { 653 // anonymous field 654 name := anonymousFieldIdent(f.Type) 655 pos := f.Type.Pos() 656 t, isPtr := deref(typ) 657 switch t := t.(type) { 658 case *Basic: 659 if t == Typ[Invalid] { 660 // error was reported before 661 continue 662 } 663 // unsafe.Pointer is treated like a regular pointer 664 if t.kind == UnsafePointer { 665 check.errorf(pos, "anonymous field type cannot be unsafe.Pointer") 666 continue 667 } 668 add(f, name, Universe.Lookup(t.name).(*TypeName), pos) 669 670 case *Named: 671 // spec: "An embedded type must be specified as a type name 672 // T or as a pointer to a non-interface type name *T, and T 673 // itself may not be a pointer type." 674 switch u := t.underlying.(type) { 675 case *Basic: 676 // unsafe.Pointer is treated like a regular pointer 677 if u.kind == UnsafePointer { 678 check.errorf(pos, "anonymous field type cannot be unsafe.Pointer") 679 continue 680 } 681 case *Pointer: 682 check.errorf(pos, "anonymous field type cannot be a pointer") 683 continue 684 case *Interface: 685 if isPtr { 686 check.errorf(pos, "anonymous field type cannot be a pointer to an interface") 687 continue 688 } 689 } 690 add(f, name, t.obj, pos) 691 692 default: 693 check.invalidAST(pos, "anonymous field type %s must be named", typ) 694 } 695 } 696 } 697 698 styp.fields = fields 699 styp.tags = tags 700 } 701 702 func anonymousFieldIdent(e ast.Expr) *ast.Ident { 703 switch e := e.(type) { 704 case *ast.Ident: 705 return e 706 case *ast.StarExpr: 707 return anonymousFieldIdent(e.X) 708 case *ast.SelectorExpr: 709 return e.Sel 710 } 711 return nil // invalid anonymous field 712 }