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