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.
19 // ident type-checks identifier e and initializes x with the value or type of e.
20 // If an error occurred, x.mode is set to invalid.
21 // For the meaning of def, see Checker.definedType, below.
22 // If wantType is set, the identifier e is expected to denote a type.
24 func (check *Checker) ident(x *operand, e *ast.Ident, def *Named, wantType bool) {
28 // Note that we cannot use check.lookup here because the returned scope
29 // may be different from obj.Parent(). See also Scope.LookupParent doc.
30 scope, obj := check.scope.LookupParent(e.Name, check.pos)
33 check.errorf(e, _InvalidBlank, "cannot use _ as value or type")
35 check.errorf(e, _UndeclaredName, "undeclared name: %s", e.Name)
39 check.recordUse(e, obj)
41 // Type-check the object.
42 // Only call Checker.objDecl if the object doesn't have a type yet
43 // (in which case we must actually determine it) or the object is a
44 // TypeName and we also want a type (in which case we might detect
45 // a cycle which needs to be reported). Otherwise we can skip the
46 // call and avoid a possible cycle error in favor of the more
47 // informative "not a type/value" error that this function's caller
48 // will issue (see issue #25790).
50 if _, gotType := obj.(*TypeName); typ == nil || gotType && wantType {
51 check.objDecl(obj, def)
52 typ = obj.Type() // type must have been assigned by Checker.objDecl
56 // The object may be dot-imported: If so, remove its package from
57 // the map of unused dot imports for the respective file scope.
58 // (This code is only needed for dot-imports. Without them,
59 // we only have to mark variables, see *Var case below).
60 if pkg := obj.Pkg(); pkg != check.pkg && pkg != nil {
61 delete(check.unusedDotImports[scope], pkg)
64 switch obj := obj.(type) {
66 check.errorf(e, _InvalidPkgUse, "use of package %s not in selector", obj.name)
71 if typ == Typ[Invalid] {
74 if obj == universeIota {
75 if check.iota == nil {
76 check.errorf(e, _InvalidIota, "cannot use iota outside constant declaration")
90 // It's ok to mark non-local variables, but ignore variables
91 // from other packages to avoid potential race conditions with
92 // dot-imported variables.
93 if obj.pkg == check.pkg {
97 if typ == Typ[Invalid] {
103 check.addDeclDep(obj)
120 // typ type-checks the type expression e and returns its type, or Typ[Invalid].
121 // The type must not be an (uninstantiated) generic type.
122 func (check *Checker) typ(e ast.Expr) Type {
123 return check.definedType(e, nil)
126 // varType type-checks the type expression e and returns its type, or Typ[Invalid].
127 // The type must not be an (uninstantiated) generic type and it must be ordinary
128 // (see ordinaryType).
129 func (check *Checker) varType(e ast.Expr) Type {
130 typ := check.definedType(e, nil)
131 check.ordinaryType(e, typ)
135 // ordinaryType reports an error if typ is an interface type containing
136 // type lists or is (or embeds) the predeclared type comparable.
137 func (check *Checker) ordinaryType(pos positioner, typ Type) {
138 // We don't want to call under() (via asInterface) or complete interfaces
139 // while we are in the middle of type-checking parameter declarations that
140 // might belong to interface methods. Delay this check to the end of
143 if t := asInterface(typ); t != nil {
144 check.completeInterface(pos.Pos(), t) // TODO(gri) is this the correct position?
145 if t.allTypes != nil {
146 check.softErrorf(pos, _Todo, "interface contains type constraints (%s)", t.allTypes)
149 if t.IsComparable() {
150 check.softErrorf(pos, _Todo, "interface is (or embeds) comparable")
156 // anyType type-checks the type expression e and returns its type, or Typ[Invalid].
157 // The type may be generic or instantiated.
158 func (check *Checker) anyType(e ast.Expr) Type {
159 typ := check.typInternal(e, nil)
161 check.recordTypeAndValue(e, typexpr, typ, nil)
165 // definedType is like typ but also accepts a type name def.
166 // If def != nil, e is the type specification for the defined type def, declared
167 // in a type declaration, and def.underlying will be set to the type of e before
168 // any components of e are type-checked.
170 func (check *Checker) definedType(e ast.Expr, def *Named) Type {
171 typ := check.typInternal(e, def)
174 check.errorf(e, _Todo, "cannot use generic type %s without instantiation", typ)
177 check.recordTypeAndValue(e, typexpr, typ, nil)
181 // genericType is like typ but the type must be an (uninstantiated) generic type.
182 func (check *Checker) genericType(e ast.Expr, reportErr bool) Type {
183 typ := check.typInternal(e, nil)
185 if typ != Typ[Invalid] && !isGeneric(typ) {
187 check.errorf(e, _Todo, "%s is not a generic type", typ)
191 // TODO(gri) what is the correct call below?
192 check.recordTypeAndValue(e, typexpr, typ, nil)
196 // isubst returns an x with identifiers substituted per the substitution map smap.
197 // isubst only handles the case of (valid) method receiver type expressions correctly.
198 func isubst(x ast.Expr, smap map[*ast.Ident]*ast.Ident) ast.Expr {
199 switch n := x.(type) {
201 if alt := smap[n]; alt != nil {
205 X := isubst(n.X, smap)
213 for i, arg := range n.Args {
214 new := isubst(arg, smap)
217 args = make([]ast.Expr, len(n.Args))
229 return isubst(n.X, smap) // no need to keep parentheses
231 // Other receiver type expressions are invalid.
232 // It's fine to ignore those here as they will
233 // be checked elsewhere.
238 // funcType type-checks a function or method type.
239 func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
240 check.openScope(ftyp, "function")
241 check.scope.isFunc = true
242 check.recordScope(ftyp, check.scope)
243 sig.scope = check.scope
244 defer check.closeScope()
246 var recvTyp ast.Expr // rewritten receiver type; valid if != nil
247 if recvPar != nil && len(recvPar.List) > 0 {
248 // collect generic receiver type parameters, if any
249 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
250 // - the receiver specification acts as local declaration for its type parameters, which may be blank
251 _, rname, rparams := check.unpackRecv(recvPar.List[0].Type, true)
252 if len(rparams) > 0 {
253 // Blank identifiers don't get declared and regular type-checking of the instantiated
254 // parameterized receiver type expression fails in Checker.collectParams of receiver.
255 // Identify blank type parameters and substitute each with a unique new identifier named
256 // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
258 var smap map[*ast.Ident]*ast.Ident // substitution map from "_" to "n_" identifiers
259 for i, p := range rparams {
262 new.Name = fmt.Sprintf("%d_", i)
263 rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
265 smap = make(map[*ast.Ident]*ast.Ident)
271 // blank identifiers were found => use rewritten receiver type
272 recvTyp = isubst(recvPar.List[0].Type, smap)
274 sig.rparams = check.declareTypeParams(nil, rparams)
275 // determine receiver type to get its type parameters
276 // and the respective type parameter bounds
277 var recvTParams []*TypeName
279 // recv should be a Named type (otherwise an error is reported elsewhere)
280 // Also: Don't report an error via genericType since it will be reported
281 // again when we type-check the signature.
282 // TODO(gri) maybe the receiver should be marked as invalid instead?
283 if recv := asNamed(check.genericType(rname, false)); recv != nil {
284 recvTParams = recv.tparams
287 // provide type parameter bounds
288 // - only do this if we have the right number (otherwise an error is reported elsewhere)
289 if len(sig.rparams) == len(recvTParams) {
290 // We have a list of *TypeNames but we need a list of Types.
291 list := make([]Type, len(sig.rparams))
292 for i, t := range sig.rparams {
295 smap := makeSubstMap(recvTParams, list)
296 for i, tname := range sig.rparams {
297 bound := recvTParams[i].typ.(*TypeParam).bound
298 // bound is (possibly) parameterized in the context of the
299 // receiver type declaration. Substitute parameters for the
301 // TODO(gri) should we assume now that bounds always exist?
302 // (no bound == empty interface)
304 bound = check.subst(tname.pos, bound, smap)
305 tname.typ.(*TypeParam).bound = bound
312 if ftyp.TParams != nil {
313 sig.tparams = check.collectTypeParams(ftyp.TParams)
314 // Always type-check method type parameters but complain that they are not allowed.
315 // (A separate check is needed when type-checking interface method signatures because
316 // they don't have a receiver specification.)
318 check.errorf(ftyp.TParams, _Todo, "methods cannot have type parameters")
322 // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
323 // declarations and then squash that scope into the parent scope (and report any redeclarations at
325 scope := NewScope(check.scope, token.NoPos, token.NoPos, "function body (temp. scope)")
326 recvList, _ := check.collectParams(scope, recvPar, recvTyp, false) // use rewritten receiver type, if any
327 params, variadic := check.collectParams(scope, ftyp.Params, nil, true)
328 results, _ := check.collectParams(scope, ftyp.Results, nil, false)
329 scope.Squash(func(obj, alt Object) {
330 check.errorf(obj, _DuplicateDecl, "%s redeclared in this block", obj.Name())
331 check.reportAltDecl(alt)
335 // recv parameter list present (may be empty)
336 // spec: "The receiver is specified via an extra parameter section preceding the
337 // method name. That parameter section must declare a single parameter, the receiver."
339 switch len(recvList) {
341 // error reported by resolver
342 recv = NewParam(0, nil, "", Typ[Invalid]) // ignore recv below
344 // more than one receiver
345 check.error(recvList[len(recvList)-1], _BadRecv, "method must have exactly one receiver")
346 fallthrough // continue with first receiver
351 // TODO(gri) We should delay rtyp expansion to when we actually need the
352 // receiver; thus all checks here should be delayed to later.
353 rtyp, _ := deref(recv.typ)
356 // spec: "The receiver type must be of the form T or *T where T is a type name."
357 // (ignore invalid types - error was reported before)
358 if t := rtyp; t != Typ[Invalid] {
360 if T := asNamed(t); T != nil {
361 // spec: "The type denoted by T is called the receiver base type; it must not
362 // be a pointer or interface type and it must be declared in the same package
364 if T.obj.pkg != check.pkg {
365 err = "type not defined in this package"
367 switch u := optype(T).(type) {
369 // unsafe.Pointer is treated like a regular pointer
370 if u.kind == UnsafePointer {
371 err = "unsafe.Pointer"
373 case *Pointer, *Interface:
374 err = "pointer or interface type"
378 err = "basic or unnamed type"
381 check.errorf(recv, _InvalidRecv, "invalid receiver %s (%s)", recv.typ, err)
388 sig.params = NewTuple(params...)
389 sig.results = NewTuple(results...)
390 sig.variadic = variadic
393 // goTypeName returns the Go type name for typ and
394 // removes any occurences of "types." from that name.
395 func goTypeName(typ Type) string {
396 return strings.ReplaceAll(fmt.Sprintf("%T", typ), "types.", "")
399 // typInternal drives type checking of types.
400 // Must only be called by definedType or genericType.
402 func (check *Checker) typInternal(e0 ast.Expr, def *Named) (T Type) {
404 check.trace(e0.Pos(), "type %s", e0)
410 // Calling under() here may lead to endless instantiations.
411 // Test case: type T[P any] *T[P]
412 // TODO(gri) investigate if that's a bug or to be expected
413 // (see also analogous comment in Checker.instantiate).
414 under = T.Underlying()
417 check.trace(e0.Pos(), "=> %s // %s", T, goTypeName(T))
419 check.trace(e0.Pos(), "=> %s (under = %s) // %s", T, under, goTypeName(T))
424 switch e := e0.(type) {
426 // ignore - error reported before
430 check.ident(&x, e, def, true)
435 def.setUnderlying(typ)
438 // ignore - error reported before
440 check.errorf(&x, _NotAType, "%s used as type", &x)
442 check.errorf(&x, _NotAType, "%s is not a type", &x)
445 case *ast.SelectorExpr:
447 check.selector(&x, e)
452 def.setUnderlying(typ)
455 // ignore - error reported before
457 check.errorf(&x, _NotAType, "%s used as type", &x)
459 check.errorf(&x, _NotAType, "%s is not a type", &x)
463 return check.instantiatedType(e.X, []ast.Expr{e.Index}, def)
467 return check.instantiatedType(e.Fun, e.Args, def)
469 check.errorf(e0, _NotAType, "%s is not a type", e0)
473 // Generic types must be instantiated before they can be used in any form.
474 // Consequently, generic types cannot be parenthesized.
475 return check.definedType(e.X, def)
480 def.setUnderlying(typ)
481 typ.len = check.arrayLength(e.Len)
482 typ.elem = check.varType(e.Elt)
487 def.setUnderlying(typ)
488 typ.elem = check.varType(e.Elt)
492 // dots are handled explicitly where they are legal
493 // (array composite literals and parameter lists)
494 check.error(e, _InvalidDotDotDot, "invalid use of '...'")
497 case *ast.StructType:
499 def.setUnderlying(typ)
500 check.structType(typ, e)
505 def.setUnderlying(typ)
506 typ.base = check.varType(e.X)
510 typ := new(Signature)
511 def.setUnderlying(typ)
512 check.funcType(typ, nil, e)
515 case *ast.InterfaceType:
516 typ := new(Interface)
517 def.setUnderlying(typ)
521 check.interfaceType(typ, e, def)
526 def.setUnderlying(typ)
528 typ.key = check.varType(e.Key)
529 typ.elem = check.varType(e.Value)
531 // spec: "The comparison operators == and != must be fully defined
532 // for operands of the key type; thus the key type must not be a
533 // function, map, or slice."
535 // Delay this check because it requires fully setup types;
536 // it is safe to continue in any case (was issue 6667).
538 if !Comparable(typ.key) {
540 if asTypeParam(typ.key) != nil {
541 why = " (missing comparable constraint)"
543 check.errorf(e.Key, _IncomparableMapKey, "incomparable map key type %s%s", typ.key, why)
551 def.setUnderlying(typ)
555 case ast.SEND | ast.RECV:
562 check.invalidAST(e, "unknown channel direction %d", e.Dir)
567 typ.elem = check.varType(e.Value)
571 check.errorf(e0, _NotAType, "%s is not a type", e0)
575 def.setUnderlying(typ)
579 // typeOrNil type-checks the type expression (or nil value) e
580 // and returns the type of e, or nil. If e is a type, it must
581 // not be an (uninstantiated) generic type.
582 // If e is neither a type nor nil, typeOrNil returns Typ[Invalid].
583 // TODO(gri) should we also disallow non-var types?
584 func (check *Checker) typeOrNil(e ast.Expr) Type {
586 check.rawExpr(&x, e, nil)
589 // ignore - error reported before
591 check.errorf(&x, _NotAType, "%s used as type", &x)
593 check.instantiatedOperand(&x)
601 check.errorf(&x, _NotAType, "%s is not a type", &x)
606 func (check *Checker) instantiatedType(x ast.Expr, targs []ast.Expr, def *Named) Type {
607 b := check.genericType(x, true) // TODO(gri) what about cycles?
608 if b == Typ[Invalid] {
609 return b // error already reported
613 unreachable() // should have been caught by genericType
616 // create a new type instance rather than instantiate the type
617 // TODO(gri) should do argument number check here rather than
618 // when instantiating the type?
620 def.setUnderlying(typ)
626 // evaluate arguments (always)
627 typ.targs = check.typeList(targs)
628 if typ.targs == nil {
629 def.setUnderlying(Typ[Invalid]) // avoid later errors due to lazy instantiation
633 // determine argument positions (for error reporting)
634 typ.poslist = make([]token.Pos, len(targs))
635 for i, arg := range targs {
636 typ.poslist[i] = arg.Pos()
639 // make sure we check instantiation works at least once
640 // and that the resulting type is valid
643 check.validType(t, nil)
649 // arrayLength type-checks the array length expression e
650 // and returns the constant length >= 0, or a value < 0
651 // to indicate an error (and thus an unknown length).
652 func (check *Checker) arrayLength(e ast.Expr) int64 {
655 if x.mode != constant_ {
656 if x.mode != invalid {
657 check.errorf(&x, _InvalidArrayLen, "array length %s must be constant", &x)
661 if isUntyped(x.typ) || isInteger(x.typ) {
662 if val := constant.ToInt(x.val); val.Kind() == constant.Int {
663 if representableConst(val, check, Typ[Int], nil) {
664 if n, ok := constant.Int64Val(val); ok && n >= 0 {
667 check.errorf(&x, _InvalidArrayLen, "invalid array length %s", &x)
672 check.errorf(&x, _InvalidArrayLen, "array length %s must be integer", &x)
676 // typeList provides the list of types corresponding to the incoming expression list.
677 // If an error occured, the result is nil, but all list elements were type-checked.
678 func (check *Checker) typeList(list []ast.Expr) []Type {
679 res := make([]Type, len(list)) // res != nil even if len(list) == 0
680 for i, x := range list {
681 t := check.varType(x)
682 if t == Typ[Invalid] {
692 // collectParams declares the parameters of list in scope and returns the corresponding
693 // variable list. If type0 != nil, it is used instead of the the first type in list.
694 func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, type0 ast.Expr, variadicOk bool) (params []*Var, variadic bool) {
699 var named, anonymous bool
700 for i, field := range list.List {
702 if i == 0 && type0 != nil {
705 if t, _ := ftype.(*ast.Ellipsis); t != nil {
707 if variadicOk && i == len(list.List)-1 && len(field.Names) <= 1 {
710 check.softErrorf(t, _MisplacedDotDotDot, "can only use ... with final parameter in list")
711 // ignore ... and continue
714 typ := check.varType(ftype)
715 // The parser ensures that f.Tag is nil and we don't
716 // care if a constructed AST contains a non-nil tag.
717 if len(field.Names) > 0 {
719 for _, name := range field.Names {
721 check.invalidAST(name, "anonymous parameter")
724 par := NewParam(name.Pos(), check.pkg, name.Name, typ)
725 check.declare(scope, name, par, scope.pos)
726 params = append(params, par)
730 // anonymous parameter
731 par := NewParam(ftype.Pos(), check.pkg, "", typ)
732 check.recordImplicit(field, par)
733 params = append(params, par)
738 if named && anonymous {
739 check.invalidAST(list, "list contains both named and anonymous parameters")
743 // For a variadic function, change the last parameter's type from T to []T.
744 // Since we type-checked T rather than ...T, we also need to retro-actively
745 // record the type for ...T.
747 last := params[len(params)-1]
748 last.typ = &Slice{elem: last.typ}
749 check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
755 func (check *Checker) declareInSet(oset *objset, pos token.Pos, obj Object) bool {
756 if alt := oset.insert(obj); alt != nil {
757 check.errorf(atPos(pos), _DuplicateDecl, "%s redeclared", obj.Name())
758 check.reportAltDecl(alt)
764 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
765 var tlist *ast.Ident // "type" name of first entry in a type list declaration
767 for _, f := range iface.Methods.List {
768 if len(f.Names) > 0 {
769 // We have a method with name f.Names[0], or a type
770 // of a type list (name.Name == "type").
771 // (The parser ensures that there's only one method
772 // and we don't care if a constructed AST has more.)
774 if name.Name == "_" {
775 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
779 if name.Name == "type" {
780 // Always collect all type list entries, even from
781 // different type lists, under the assumption that
782 // the author intended to include all types.
783 types = append(types, f.Type)
784 if tlist != nil && tlist != name {
785 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
791 typ := check.typ(f.Type)
792 sig, _ := typ.(*Signature)
794 if typ != Typ[Invalid] {
795 check.invalidAST(f.Type, "%s is not a method signature", typ)
800 // Always type-check method type parameters but complain if they are not enabled.
801 // (This extra check is needed here because interface method signatures don't have
802 // a receiver specification.)
803 if sig.tparams != nil {
804 check.errorf(f.Type.(*ast.FuncType).TParams, _Todo, "methods cannot have type parameters")
807 // use named receiver type if available (for better error messages)
808 var recvTyp Type = ityp
812 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
814 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
815 check.recordDef(name, m)
816 ityp.methods = append(ityp.methods, m)
818 // We have an embedded type. completeInterface will
819 // eventually verify that we have an interface.
820 ityp.embeddeds = append(ityp.embeddeds, check.typ(f.Type))
821 check.posMap[ityp] = append(check.posMap[ityp], f.Type.Pos())
826 ityp.types = NewSum(check.collectTypeConstraints(iface.Pos(), types))
828 if len(ityp.methods) == 0 && ityp.types == nil && len(ityp.embeddeds) == 0 {
830 ityp.allMethods = markComplete
834 // sort for API stability
835 sort.Sort(byUniqueMethodName(ityp.methods))
836 sort.Stable(byUniqueTypeName(ityp.embeddeds))
838 check.later(func() { check.completeInterface(iface.Pos(), ityp) })
841 func (check *Checker) completeInterface(pos token.Pos, ityp *Interface) {
842 if ityp.allMethods != nil {
846 // completeInterface may be called via the LookupFieldOrMethod,
847 // MissingMethod, Identical, or IdenticalIgnoreTags external API
848 // in which case check will be nil. In this case, type-checking
849 // must be finished and all interfaces should have been completed.
851 panic("internal error: incomplete interface")
855 // Types don't generally have position information.
856 // If we don't have a valid pos provided, try to use
858 if !pos.IsValid() && len(ityp.methods) > 0 {
859 pos = ityp.methods[0].pos
862 check.trace(pos, "complete %s", ityp)
866 check.trace(pos, "=> %s (methods = %v, types = %v)", ityp, ityp.allMethods, ityp.allTypes)
870 // An infinitely expanding interface (due to a cycle) is detected
871 // elsewhere (Checker.validType), so here we simply assume we only
872 // have valid interfaces. Mark the interface as complete to avoid
873 // infinite recursion if the validType check occurs later for some
875 ityp.allMethods = markComplete
877 // Methods of embedded interfaces are collected unchanged; i.e., the identity
878 // of a method I.m's Func Object of an interface I is the same as that of
879 // the method m in an interface that embeds interface I. On the other hand,
880 // if a method is embedded via multiple overlapping embedded interfaces, we
881 // don't provide a guarantee which "original m" got chosen for the embedding
882 // interface. See also issue #34421.
884 // If we don't care to provide this identity guarantee anymore, instead of
885 // reusing the original method in embeddings, we can clone the method's Func
886 // Object and give it the position of a corresponding embedded interface. Then
887 // we can get rid of the mpos map below and simply use the cloned method's
892 mpos := make(map[*Func]token.Pos) // method specification or method embedding position, for good error messages
893 addMethod := func(pos token.Pos, m *Func, explicit bool) {
894 switch other := seen.insert(m); {
896 methods = append(methods, m)
899 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
900 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
902 // check method signatures after all types are computed (issue #33656)
904 if !check.identical(m.typ, other.Type()) {
905 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
906 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
912 for _, m := range ityp.methods {
913 addMethod(m.pos, m, true)
917 allTypes := ityp.types
919 posList := check.posMap[ityp]
920 for i, typ := range ityp.embeddeds {
921 pos := posList[i] // embedding position
923 etyp := asInterface(utyp)
925 if utyp != Typ[Invalid] {
927 if _, ok := utyp.(*TypeParam); ok {
928 format = "%s is a type parameter, not an interface"
930 format = "%s is not an interface"
932 // TODO: correct error code.
933 check.errorf(atPos(pos), _InvalidIfaceEmbed, format, typ)
937 check.completeInterface(pos, etyp)
938 for _, m := range etyp.allMethods {
939 addMethod(pos, m, false) // use embedding position pos rather than m.pos
941 allTypes = intersect(allTypes, etyp.allTypes)
945 sort.Sort(byUniqueMethodName(methods))
946 ityp.allMethods = methods
948 ityp.allTypes = allTypes
951 // intersect computes the intersection of the types x and y.
952 // Note: A incomming nil type stands for the top type. A top
953 // type result is returned as nil.
954 func intersect(x, y Type) (r Type) {
962 case x == theBottom || y == theBottom:
964 case x == nil || x == theTop:
966 case y == nil || x == theTop:
970 xtypes := unpackType(x)
971 ytypes := unpackType(y)
972 // Compute the list rtypes which includes only
973 // types that are in both xtypes and ytypes.
974 // Quadratic algorithm, but good enough for now.
975 // TODO(gri) fix this
977 for _, x := range xtypes {
978 if includes(ytypes, x) {
979 rtypes = append(rtypes, x)
986 return NewSum(rtypes)
989 // byUniqueTypeName named type lists can be sorted by their unique type names.
990 type byUniqueTypeName []Type
992 func (a byUniqueTypeName) Len() int { return len(a) }
993 func (a byUniqueTypeName) Less(i, j int) bool { return sortName(a[i]) < sortName(a[j]) }
994 func (a byUniqueTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
996 func sortName(t Type) string {
997 if named := asNamed(t); named != nil {
998 return named.obj.Id()
1003 // byUniqueMethodName method lists can be sorted by their unique method names.
1004 type byUniqueMethodName []*Func
1006 func (a byUniqueMethodName) Len() int { return len(a) }
1007 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() }
1008 func (a byUniqueMethodName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
1010 func (check *Checker) tag(t *ast.BasicLit) string {
1012 if t.Kind == token.STRING {
1013 if val, err := strconv.Unquote(t.Value); err == nil {
1017 check.invalidAST(t, "incorrect tag syntax: %q", t.Value)
1022 func (check *Checker) structType(styp *Struct, e *ast.StructType) {
1028 // struct fields and tags
1032 // for double-declaration checks
1035 // current field typ and tag
1038 add := func(ident *ast.Ident, embedded bool, pos token.Pos) {
1039 if tag != "" && tags == nil {
1040 tags = make([]string, len(fields))
1043 tags = append(tags, tag)
1047 fld := NewField(pos, check.pkg, name, typ, embedded)
1048 // spec: "Within a struct, non-blank field names must be unique."
1049 if name == "_" || check.declareInSet(&fset, pos, fld) {
1050 fields = append(fields, fld)
1051 check.recordDef(ident, fld)
1055 // addInvalid adds an embedded field of invalid type to the struct for
1056 // fields with errors; this keeps the number of struct fields in sync
1057 // with the source as long as the fields are _ or have different names
1059 addInvalid := func(ident *ast.Ident, pos token.Pos) {
1062 add(ident, true, pos)
1065 for _, f := range list.List {
1066 typ = check.varType(f.Type)
1067 tag = check.tag(f.Tag)
1068 if len(f.Names) > 0 {
1070 for _, name := range f.Names {
1071 add(name, false, name.Pos())
1075 // spec: "An embedded type must be specified as a type name T or as a
1076 // pointer to a non-interface type name *T, and T itself may not be a
1079 name := embeddedFieldIdent(f.Type)
1081 // TODO(rFindley): using invalidAST here causes test failures (all
1082 // errors should have codes). Clean this up.
1083 check.errorf(f.Type, _Todo, "invalid AST: embedded field type %s has no name", f.Type)
1084 name = ast.NewIdent("_")
1086 addInvalid(name, pos)
1089 add(name, true, pos)
1091 // Because we have a name, typ must be of the form T or *T, where T is the name
1092 // of a (named or alias) type, and t (= deref(typ)) must be the type of T.
1093 // We must delay this check to the end because we don't want to instantiate
1094 // (via under(t)) a possibly incomplete type.
1096 // for use in the closure below
1098 embeddedPos := f.Type
1100 check.atEnd(func() {
1101 t, isPtr := deref(embeddedTyp)
1102 switch t := optype(t).(type) {
1104 if t == Typ[Invalid] {
1105 // error was reported before
1108 // unsafe.Pointer is treated like a regular pointer
1109 if t.kind == UnsafePointer {
1110 check.errorf(embeddedPos, _InvalidPtrEmbed, "embedded field type cannot be unsafe.Pointer")
1113 check.errorf(embeddedPos, _InvalidPtrEmbed, "embedded field type cannot be a pointer")
1116 check.errorf(embeddedPos, _InvalidPtrEmbed, "embedded field type cannot be a pointer to an interface")
1123 styp.fields = fields
1127 func embeddedFieldIdent(e ast.Expr) *ast.Ident {
1128 switch e := e.(type) {
1132 // *T is valid, but **T is not
1133 if _, ok := e.X.(*ast.StarExpr); !ok {
1134 return embeddedFieldIdent(e.X)
1136 case *ast.SelectorExpr:
1138 case *ast.IndexExpr:
1139 return embeddedFieldIdent(e.X)
1142 return embeddedFieldIdent(e.Fun)
1145 return nil // invalid embedded field
1148 func (check *Checker) collectTypeConstraints(pos token.Pos, types []ast.Expr) []Type {
1149 list := make([]Type, 0, len(types)) // assume all types are correct
1150 for _, texpr := range types {
1152 check.invalidAST(atPos(pos), "missing type constraint")
1155 list = append(list, check.varType(texpr))
1158 // Ensure that each type is only present once in the type list. Types may be
1159 // interfaces, which may not be complete yet. It's ok to do this check at the
1160 // end because it's not a requirement for correctness of the code.
1161 // Note: This is a quadratic algorithm, but type lists tend to be short.
1162 check.atEnd(func() {
1163 for i, t := range list {
1164 if t := asInterface(t); t != nil {
1165 check.completeInterface(types[i].Pos(), t)
1167 if includes(list[:i], t) {
1168 check.softErrorf(types[i], _Todo, "duplicate type %s in type list", t)
1176 // includes reports whether typ is in list.
1177 func includes(list []Type, typ Type) bool {
1178 for _, e := range list {
1179 if Identical(typ, e) {