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.
5 // This file implements type-checking of identifiers and type expressions.
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.
21 func (check
*Checker
) ident(x
*operand
, e
*ast
.Ident
, def
*Named
, path
[]*TypeName
) {
25 scope
, obj
:= check
.scope
.LookupParent(e
.Name
, check
.pos
)
28 check
.errorf(e
.Pos(), "cannot use _ as value or type")
30 check
.errorf(e
.Pos(), "undeclared name: %s", e
.Name
)
34 check
.recordUse(e
, obj
)
36 check
.objDecl(obj
, def
, path
)
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
)
48 switch obj
:= obj
.(type) {
50 check
.errorf(e
.Pos(), "use of package %s not in selector", obj
.name
)
55 if typ
== Typ
[Invalid
] {
58 if obj
== universeIota
{
59 if check
.iota == nil {
60 check
.errorf(e
.Pos(), "cannot use iota outside constant declaration")
73 // (it's ok to iterate forward because each named type appears at most once in path)
74 for i
, prev
:= range path
{
76 check
.errorf(obj
.pos
, "illegal cycle in declaration of %s", obj
.name
)
78 for _
, obj
:= range path
[i
:] {
79 check
.errorf(obj
.Pos(), "\t%s refers to", obj
.Name()) // secondary error, \t indented
81 check
.errorf(obj
.Pos(), "\t%s", obj
.Name())
82 // maintain x.mode == typexpr despite error
89 if obj
.pkg
== check
.pkg
{
93 if typ
== Typ
[Invalid
] {
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.
122 func (check
*Checker
) typExpr(e ast
.Expr
, def
*Named
, path
[]*TypeName
) (T Type
) {
124 check
.trace(e
.Pos(), "%s", e
)
128 check
.trace(e
.Pos(), "=> %s", T
)
132 T
= check
.typExprInternal(e
, def
, path
)
134 check
.recordTypeAndValue(e
, typexpr
, T
, nil)
139 func (check
*Checker
) typ(e ast
.Expr
) Type
{
140 return check
.typExpr(e
, nil, nil)
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
)
148 recvList
, _
:= check
.collectParams(scope
, recvPar
, false)
149 params
, variadic
:= check
.collectParams(scope
, ftyp
.Params
, true)
150 results
, _
:= check
.collectParams(scope
, ftyp
.Results
, false)
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."
157 switch len(recvList
) {
159 check
.error(recvPar
.Pos(), "method is missing receiver")
160 recv
= NewParam(0, nil, "", Typ
[Invalid
]) // ignore recv below
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
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
] {
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
176 if T
.obj
.pkg
!= check
.pkg
{
177 err
= "type not defined in this package"
179 // TODO(gri) This is not correct if the underlying type is unknown yet.
180 switch u
:= T
.underlying
.(type) {
182 // unsafe.Pointer is treated like a regular pointer
183 if u
.kind
== UnsafePointer
{
184 err
= "unsafe.Pointer"
186 case *Pointer
, *Interface
:
187 err
= "pointer or interface type"
191 err
= "basic or unnamed type"
194 check
.errorf(recv
.pos
, "invalid receiver %s (%s)", recv
.typ
, err
)
202 sig
.params
= NewTuple(params
...)
203 sig
.results
= NewTuple(results
...)
204 sig
.variadic
= variadic
207 // typExprInternal drives type checking of types.
208 // Must only be called by typExpr.
210 func (check
*Checker
) typExprInternal(e ast
.Expr
, def
*Named
, path
[]*TypeName
) Type
{
211 switch e
:= e
.(type) {
213 // ignore - error reported before
217 check
.ident(&x
, e
, def
, path
)
222 def
.setUnderlying(typ
)
225 // ignore - error reported before
227 check
.errorf(x
.pos(), "%s used as type", &x
)
229 check
.errorf(x
.pos(), "%s is not a type", &x
)
232 case *ast
.SelectorExpr
:
234 check
.selector(&x
, e
)
239 def
.setUnderlying(typ
)
242 // ignore - error reported before
244 check
.errorf(x
.pos(), "%s used as type", &x
)
246 check
.errorf(x
.pos(), "%s is not a type", &x
)
250 return check
.typExpr(e
.X
, def
, path
)
255 def
.setUnderlying(typ
)
256 typ
.len = check
.arrayLength(e
.Len
)
257 typ
.elem
= check
.typExpr(e
.Elt
, nil, path
)
262 def
.setUnderlying(typ
)
263 typ
.elem
= check
.typ(e
.Elt
)
267 case *ast
.StructType
:
269 def
.setUnderlying(typ
)
270 check
.structType(typ
, e
, path
)
275 def
.setUnderlying(typ
)
276 typ
.base
= check
.typ(e
.X
)
280 typ
:= new(Signature
)
281 def
.setUnderlying(typ
)
282 check
.funcType(typ
, nil, e
)
285 case *ast
.InterfaceType
:
286 typ
:= new(Interface
)
287 def
.setUnderlying(typ
)
288 check
.interfaceType(typ
, e
, def
, path
)
293 def
.setUnderlying(typ
)
295 typ
.key
= check
.typ(e
.Key
)
296 typ
.elem
= check
.typ(e
.Value
)
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."
302 // Delay this check because it requires fully setup types;
303 // it is safe to continue in any case (was issue 6667).
305 if !Comparable(typ
.key
) {
306 check
.errorf(e
.Key
.Pos(), "invalid map key type %s", typ
.key
)
314 def
.setUnderlying(typ
)
318 case ast
.SEND | ast
.RECV
:
325 check
.invalidAST(e
.Pos(), "unknown channel direction %d", e
.Dir
)
330 typ
.elem
= check
.typ(e
.Value
)
334 check
.errorf(e
.Pos(), "%s is not a type", e
)
338 def
.setUnderlying(typ
)
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].
346 func (check
*Checker
) typOrNil(e ast
.Expr
) Type
{
348 check
.rawExpr(&x
, e
, nil)
351 // ignore - error reported before
353 check
.errorf(x
.pos(), "%s used as type", &x
)
362 check
.errorf(x
.pos(), "%s is not a type", &x
)
367 func (check
*Checker
) arrayLength(e ast
.Expr
) int64 {
370 if x
.mode
!= constant_
{
371 if x
.mode
!= invalid
{
372 check
.errorf(x
.pos(), "array length %s must be constant", &x
)
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 {
382 check
.errorf(x
.pos(), "invalid array length %s", &x
)
387 check
.errorf(x
.pos(), "array length %s must be integer", &x
)
391 func (check
*Checker
) collectParams(scope
*Scope
, list
*ast
.FieldList
, variadicOk
bool) (params
[]*Var
, variadic
bool) {
396 var named
, anonymous
bool
397 for i
, field
:= range list
.List
{
399 if t
, _
:= ftype
.(*ast
.Ellipsis
); t
!= nil {
401 if variadicOk
&& i
== len(list
.List
)-1 {
404 check
.invalidAST(field
.Pos(), "... not permitted")
405 // ignore ... and continue
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 {
413 for _
, name
:= range field
.Names
{
415 check
.invalidAST(name
.Pos(), "anonymous parameter")
418 par
:= NewParam(name
.Pos(), check
.pkg
, name
.Name
, typ
)
419 check
.declare(scope
, name
, par
, scope
.pos
)
420 params
= append(params
, par
)
424 // anonymous parameter
425 par
:= NewParam(ftype
.Pos(), check
.pkg
, "", typ
)
426 check
.recordImplicit(field
, par
)
427 params
= append(params
, par
)
432 if named
&& anonymous
{
433 check
.invalidAST(list
.Pos(), "list contains both named and anonymous parameters")
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
}
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
)
455 func (check
*Checker
) interfaceType(iface
*Interface
, ityp
*ast
.InterfaceType
, def
*Named
, path
[]*TypeName
) {
456 // empty interface: common case
457 if ityp
.Methods
== nil {
461 // The parser ensures that field tags are nil and we don't
462 // care if a constructed AST contains non-nil tags.
464 // use named receiver type if available (for better error messages)
465 var recvTyp Type
= iface
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
478 signatures
[]ast
.Expr
// list of corresponding method signatures
479 embedded
[]ast
.Expr
// list of embedded types
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.
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 _")
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
)
512 embedded
= append(embedded
, f
.Type
)
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
526 for _
, e
:= range embedded
{
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
)
535 if typ
!= Typ
[Invalid
] {
536 check
.errorf(pos
, "%s is not an interface", typ
)
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
)
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
555 for i
, m
:= range iface
.methods
{
556 expr
:= signatures
[i
]
557 typ
:= check
.typ(expr
)
558 sig
, _
:= typ
.(*Signature
)
560 if typ
!= Typ
[Invalid
] {
561 check
.invalidAST(expr
.Pos(), "%s is not a method signature", typ
)
563 continue // keep method with empty method signature
565 // update signature, but keep recv that was set up before
566 old
:= m
.typ
.(*Signature
)
568 *old
= *sig
// update signature (don't replace it!)
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
))
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
))
581 sort
.Sort(byUniqueMethodName(iface
.allMethods
))
584 // byUniqueTypeName named type lists can be sorted by their unique type names.
585 type byUniqueTypeName
[]*Named
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
] }
591 // byUniqueMethodName method lists can be sorted by their unique method names.
592 type byUniqueMethodName
[]*Func
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
] }
598 func (check
*Checker
) tag(t
*ast
.BasicLit
) string {
600 if t
.Kind
== token
.STRING
{
601 if val
, err
:= strconv
.Unquote(t
.Value
); err
== nil {
605 check
.invalidAST(t
.Pos(), "incorrect tag syntax: %q", t
.Value
)
610 func (check
*Checker
) structType(styp
*Struct
, e
*ast
.StructType
, path
[]*TypeName
) {
616 // struct fields and tags
620 // for double-declaration checks
623 // current field typ and tag
626 add
:= func(ident
*ast
.Ident
, anonymous
bool, pos token
.Pos
) {
627 if tag
!= "" && tags
== nil {
628 tags
= make([]string, len(fields
))
631 tags
= append(tags
, tag
)
635 fld
:= NewField(pos
, check
.pkg
, name
, typ
, anonymous
)
636 // spec: "Within a struct, non-blank field names must be unique."
637 if name
== "_" || check
.declareInSet(&fset
, pos
, fld
) {
638 fields
= append(fields
, fld
)
639 check
.recordDef(ident
, fld
)
643 for _
, f
:= range list
.List
{
644 typ
= check
.typExpr(f
.Type
, nil, path
)
645 tag
= check
.tag(f
.Tag
)
646 if len(f
.Names
) > 0 {
648 for _
, name
:= range f
.Names
{
649 add(name
, false, name
.Pos())
653 // spec: "An embedded type must be specified as a type name T or as a pointer
654 // to a non-interface type name *T, and T itself may not be a pointer type."
656 name
:= anonymousFieldIdent(f
.Type
)
658 check
.invalidAST(pos
, "anonymous field type %s has no name", f
.Type
)
661 t
, isPtr
:= deref(typ
)
662 // Because we have a name, typ must be of the form T or *T, where T is the name
663 // of a (named or alias) type, and t (= deref(typ)) must be the type of T.
664 switch t
:= t
.Underlying().(type) {
666 if t
== Typ
[Invalid
] {
667 // error was reported before
671 // unsafe.Pointer is treated like a regular pointer
672 if t
.kind
== UnsafePointer
{
673 check
.errorf(pos
, "anonymous field type cannot be unsafe.Pointer")
678 check
.errorf(pos
, "anonymous field type cannot be a pointer")
683 check
.errorf(pos
, "anonymous field type cannot be a pointer to an interface")
695 func anonymousFieldIdent(e ast
.Expr
) *ast
.Ident
{
696 switch e
:= e
.(type) {
700 // *T is valid, but **T is not
701 if _
, ok
:= e
.X
.(*ast
.StarExpr
); !ok
{
702 return anonymousFieldIdent(e
.X
)
704 case *ast
.SelectorExpr
:
707 return nil // invalid anonymous field