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