1 // Copyright 2009 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.
16 Etop = 1 << iota // evaluated at statement level
17 Erv // evaluated in value context
18 Etype // evaluated in type context
19 Ecall // call-only expressions are ok
20 Efnstruct // multivalue function returns are ok
21 Easgn // assigning to expression
22 Ecomplit // type in composite literal
25 // type check the whole tree of an expression.
26 // calculates expression types.
27 // evaluates compile time constants.
28 // marks variables that escape the local frame.
29 // rewrites n->op to be more specific in some cases.
30 var typecheckdefstack []*Node
32 // resolve ONONAME to definition, if any.
33 func resolve(n *Node) *Node {
34 if n != nil && n.Op == ONONAME && n.Sym != nil {
39 } else if n.Iota() >= 0 {
40 n = nodintconst(n.Iota())
48 func typecheckslice(l []*Node, top int) {
50 l[i] = typecheck(l[i], top)
54 var _typekind = []string{
66 TCOMPLEX64: "complex64",
67 TCOMPLEX128: "complex128",
74 TUNSAFEPTR: "unsafe.Pointer",
83 TIDEAL: "untyped number",
86 func typekind(t *Type) string {
91 if int(et) < len(_typekind) {
97 return fmt.Sprintf("etype=%d", et)
100 // sprint_depchain prints a dependency chain of nodes into trace.
101 // It is used by typecheck in the case of OLITERAL nodes
102 // to print constant definition loops.
103 func sprint_depchain(trace *string, stack []*Node, cur *Node, first *Node) {
104 for i := len(stack) - 1; i >= 0; i-- {
105 if n := stack[i]; n.Op == cur.Op {
107 sprint_depchain(trace, stack[:i], n, first)
109 *trace += fmt.Sprintf("\n\t%v: %v uses %v", n.Line(), n, cur)
115 var typecheck_tcstack []*Node
117 // typecheck type checks node n.
118 // The result of typecheck MUST be assigned back to n, e.g.
119 // n.Left = typecheck(n.Left, top)
120 func typecheck(n *Node, top int) *Node {
121 // cannot type check until all the source has been parsed
123 Fatalf("early typecheck")
137 // Resolve definition of name and value of iota lazily.
140 // Skip typecheck if already done.
141 // But re-typecheck ONAME/OTYPE/OLITERAL/OPACK node in case context has changed.
142 if n.Typecheck == 1 {
144 case ONAME, OTYPE, OLITERAL, OPACK:
153 if n.Typecheck == 2 {
154 // Typechecking loop. Trying printing a meaningful message,
155 // otherwise a stack trace of typechecking.
157 // We can already diagnose variables used as types.
159 if top&(Erv|Etype) == Etype {
160 yyerror("%v is not a type", n)
164 if top&Etype == Etype {
166 sprint_depchain(&trace, typecheck_tcstack, n, n)
167 yyerrorl(n.Pos, "invalid recursive type alias %v%s", n, trace)
171 if top&(Erv|Etype) == Etype {
172 yyerror("%v is not a type", n)
176 sprint_depchain(&trace, typecheck_tcstack, n, n)
177 yyerrorl(n.Pos, "constant definition loop%s", trace)
180 if nsavederrors+nerrors == 0 {
182 for i := len(typecheck_tcstack) - 1; i >= 0; i-- {
183 x := typecheck_tcstack[i]
184 trace += fmt.Sprintf("\n\t%v %v", x.Line(), x)
186 yyerror("typechecking loop involving %v%s", n, trace)
195 typecheck_tcstack = append(typecheck_tcstack, n)
196 n = typecheck1(n, top)
200 last := len(typecheck_tcstack) - 1
201 typecheck_tcstack[last] = nil
202 typecheck_tcstack = typecheck_tcstack[:last]
208 // does n contain a call or receive operation?
209 func callrecv(n *Node) bool {
229 return callrecv(n.Left) || callrecv(n.Right) || callrecvlist(n.Ninit) || callrecvlist(n.Nbody) || callrecvlist(n.List) || callrecvlist(n.Rlist)
232 func callrecvlist(l Nodes) bool {
233 for _, n := range l.Slice() {
241 // indexlit implements typechecking of untyped values as
242 // array/slice indexes. It is equivalent to defaultlit
243 // except for constants of numerical kind, which are acceptable
244 // whenever they can be represented by a value of type int.
245 // The result of indexlit MUST be assigned back to n, e.g.
246 // n.Left = indexlit(n.Left)
247 func indexlit(n *Node) *Node {
248 if n == nil || !n.Type.IsUntyped() {
251 switch consttype(n) {
252 case CTINT, CTRUNE, CTFLT, CTCPLX:
253 n = defaultlit(n, Types[TINT])
256 n = defaultlit(n, nil)
260 // The result of typecheck1 MUST be assigned back to n, e.g.
261 // n.Left = typecheck1(n.Left, top)
262 func typecheck1(n *Node, top int) *Node {
264 case OXDOT, ODOT, ODOTPTR, ODOTMETH, ODOTINTER:
265 // n.Sym is a field/method name, not a variable.
268 if n.Op == ONAME && n.Etype != 0 && top&Ecall == 0 {
269 yyerror("use of builtin %v not in function call", n.Sym)
285 // until typecheck is complete, do nothing.
289 Fatalf("typecheck %v", n.Op)
295 if n.Type == nil && n.Val().Ctype() == CTSTR {
305 if n.Name.Decldepth == 0 {
306 n.Name.Decldepth = decldepth
314 // not a write to the variable
316 yyerror("cannot use _ as value")
328 yyerror("use of package %v without selector", n.Sym)
335 // types (OIND is with exprs)
345 r := typecheck(n.Right, Etype)
354 } else if n.Left.Op == ODDD {
355 if top&Ecomplit == 0 {
358 yyerror("use of [...] array outside of array literal")
363 t = typDDDArray(r.Type)
365 n.Left = indexlit(typecheck(n.Left, Erv))
367 if consttype(l) != CTINT {
368 if l.Type != nil && l.Type.IsInteger() && l.Op != OLITERAL {
369 yyerror("non-constant array bound %v", l)
371 yyerror("invalid array bound %v", l)
378 if doesoverflow(v, Types[TINT]) {
379 yyerror("array bound is too large")
384 bound := v.U.(*Mpint).Int64()
386 yyerror("array bound must be non-negative")
390 t = typArray(r.Type, bound)
403 n.Left = typecheck(n.Left, Etype)
404 n.Right = typecheck(n.Right, Etype)
407 if l.Type == nil || r.Type == nil {
411 if l.Type.NotInHeap {
412 yyerror("go:notinheap map key not allowed")
414 if r.Type.NotInHeap {
415 yyerror("go:notinheap map value not allowed")
418 n.Type = typMap(l.Type, r.Type)
420 // map key validation
421 alg, bad := algtype1(l.Type)
423 if bad.Etype == TFORW {
424 // queue check for map until all the types are done settling.
425 mapqueue = append(mapqueue, mapqueueval{l, n.Pos})
426 } else if bad.Etype != TANY {
427 // no need to queue, key is already bad
428 yyerror("invalid map key type %v", l.Type)
436 n.Left = typecheck(n.Left, Etype)
442 if l.Type.NotInHeap {
443 yyerror("chan of go:notinheap type not allowed")
445 t := typChan(l.Type, ChanDir(n.Etype)) // TODO(marvin): Fix Node.EType type union.
454 n.Type = tostruct(n.List.Slice())
455 if n.Type == nil || n.Type.Broke {
464 n.Type = tointerface(n.List.Slice())
472 n.Type = functype(n.Left, n.List.Slice(), n.Rlist.Slice())
482 n.Left = typecheck(n.Left, Erv|Etype|top&Ecomplit)
492 n.Type = ptrto(l.Type)
498 if top&(Erv|Etop) != 0 {
499 yyerror("invalid indirect of %L", n.Left)
538 n.Left = typecheck(n.Left, Erv)
539 n.Right = typecheck(n.Right, Erv)
542 checkassign(n, n.Left)
543 if l.Type == nil || r.Type == nil {
547 if n.Implicit && !okforarith[l.Type.Etype] {
548 yyerror("invalid operation: %v (non-numeric type %v)", n, l.Type)
552 // TODO(marvin): Fix Node.EType type union.
556 n.Left = typecheck(n.Left, Erv)
557 n.Right = typecheck(n.Right, Erv)
560 if l.Type == nil || r.Type == nil {
566 if op == OLSH || op == ORSH {
567 r = defaultlit(r, Types[TUINT])
570 if !t.IsInteger() || t.IsSigned() {
571 yyerror("invalid operation: %v (shift count type %v, must be unsigned integer)", n, r.Type)
577 if t != nil && t.Etype != TIDEAL && !t.IsInteger() {
578 yyerror("invalid operation: %v (shift of type %v)", n, t)
583 // no defaultlit for left
584 // the outer context gives the type
590 // ideal mixed with non-ideal
591 l, r = defaultlit2(l, r, false)
595 if l.Type == nil || r.Type == nil {
600 if t.Etype == TIDEAL {
608 if iscmp[n.Op] && t.Etype != TIDEAL && !eqtype(l.Type, r.Type) {
609 // comparison is okay as long as one side is
610 // assignable to the other. convert so they have
613 // the only conversion that isn't a no-op is concrete == interface.
614 // in that case, check comparability of the concrete type.
615 // The conversion allocates, so only do it if the concrete type is huge.
616 if r.Type.Etype != TBLANK {
617 aop = assignop(l.Type, r.Type, nil)
619 if r.Type.IsInterface() && !l.Type.IsInterface() && !l.Type.IsComparable() {
620 yyerror("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(l.Type))
626 if r.Type.IsInterface() == l.Type.IsInterface() || l.Type.Width >= 1<<16 {
638 if l.Type.Etype != TBLANK {
639 aop = assignop(r.Type, l.Type, nil)
641 if l.Type.IsInterface() && !r.Type.IsInterface() && !r.Type.IsComparable() {
642 yyerror("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(r.Type))
648 if r.Type.IsInterface() == l.Type.IsInterface() || r.Type.Width >= 1<<16 {
663 if t.Etype != TIDEAL && !eqtype(l.Type, r.Type) {
664 l, r = defaultlit2(l, r, true)
665 if r.Type.IsInterface() == l.Type.IsInterface() || aop == 0 {
666 yyerror("invalid operation: %v (mismatched types %v and %v)", n, l.Type, r.Type)
673 yyerror("invalid operation: %v (operator %v not defined on %s)", n, op, typekind(t))
678 // okfor allows any array == array, map == map, func == func.
679 // restrict to slice/map/func == nil and nil == slice/map/func.
680 if l.Type.IsArray() && !l.Type.IsComparable() {
681 yyerror("invalid operation: %v (%v cannot be compared)", n, l.Type)
686 if l.Type.IsSlice() && !isnil(l) && !isnil(r) {
687 yyerror("invalid operation: %v (slice can only be compared to nil)", n)
692 if l.Type.IsMap() && !isnil(l) && !isnil(r) {
693 yyerror("invalid operation: %v (map can only be compared to nil)", n)
698 if l.Type.Etype == TFUNC && !isnil(l) && !isnil(r) {
699 yyerror("invalid operation: %v (func can only be compared to nil)", n)
704 if l.Type.IsStruct() {
705 if f := l.Type.IncomparableField(); f != nil {
706 yyerror("invalid operation: %v (struct containing %v cannot be compared)", n, f.Type)
716 if n.Op != OLITERAL {
717 l, r = defaultlit2(l, r, true)
725 // TODO(marvin): Fix Node.EType type union.
726 n.Etype = EType(n.Op)
728 } else if n.Op == OADD {
729 // create OADDSTR node with list of strings in x + y + z + (w + v) + ...
733 n.List.Set(l.List.Slice())
738 n.List.AppendNodes(&r.List)
748 if l.Op == OLITERAL && l.Val().Ctype() == CTNIL {
753 } else if r.Op == OLITERAL && r.Val().Ctype() == CTNIL {
754 } else // leave alone for back end
755 if r.Type.IsInterface() == l.Type.IsInterface() {
756 // TODO(marvin): Fix Node.EType type union.
757 n.Etype = EType(n.Op)
762 if (op == ODIV || op == OMOD) && Isconst(r, CTINT) {
763 if r.Val().U.(*Mpint).CmpInt64(0) == 0 {
764 yyerror("division by zero")
773 case OCOM, OMINUS, ONOT, OPLUS:
775 n.Left = typecheck(n.Left, Erv)
782 if !okfor[n.Op][t.Etype] {
783 yyerror("invalid operation: %v %v", n.Op, t)
795 n.Left = typecheck(n.Left, Erv)
796 if n.Left.Type == nil {
800 checklvalue(n.Left, "take the address of")
801 r := outervalue(n.Left)
803 for l = n.Left; l != r; l = l.Left {
805 if l.isClosureVar() {
806 l.Name.Defn.Addrtaken = true
810 if l.Orig != l && l.Op == ONAME {
811 Fatalf("found non-orig name node %v", l)
814 if l.isClosureVar() {
815 l.Name.Defn.Addrtaken = true
817 n.Left = defaultlit(n.Left, nil)
829 n = typecheckcomplit(n)
845 n.Left = typecheck(n.Left, Erv|Etype)
847 n.Left = defaultlit(n.Left, nil)
858 if n.Left.Op == OTYPE {
859 if !looktypedot(n, t, 0) {
860 if looktypedot(n, t, 1) {
861 yyerror("%v undefined (cannot refer to unexported method %v)", n, n.Sym)
863 yyerror("%v undefined (type %v has no method %v)", n, t, n.Sym)
869 if n.Type.Etype != TFUNC || !n.IsMethod() {
870 yyerror("type %v has no method %S", n.Left.Type, n.Sym)
879 n.Right = newname(n.Sym)
880 n.Type = methodfunc(n.Type, n.Left.Type)
887 if t.IsPtr() && !t.Elem().IsInterface() {
897 if isblanksym(n.Sym) {
898 yyerror("cannot refer to blank field or method")
903 if lookdot(n, t, 0) == nil {
904 // Legitimate field or method lookup failed, try to explain the error
906 case t.IsEmptyInterface():
907 yyerror("%v undefined (type %v is interface with no methods)", n, n.Left.Type)
909 case t.IsPtr() && t.Elem().IsInterface():
910 // Pointer to interface is almost always a mistake.
911 yyerror("%v undefined (type %v is pointer to interface, not interface)", n, n.Left.Type)
913 case lookdot(n, t, 1) != nil:
914 // Field or method matches by name, but it is not exported.
915 yyerror("%v undefined (cannot refer to unexported field or method %v)", n, n.Sym)
918 if mt := lookdot(n, t, 2); mt != nil { // Case-insensitive lookup.
919 yyerror("%v undefined (type %v has no field or method %v, but does have %v)", n, n.Left.Type, n.Sym, mt.Sym)
921 yyerror("%v undefined (type %v has no field or method %v)", n, n.Left.Type, n.Sym)
929 case ODOTINTER, ODOTMETH:
933 typecheckpartialcall(n, s)
945 n.Left = typecheck(n.Left, Erv)
946 n.Left = defaultlit(n.Left, nil)
953 if !t.IsInterface() {
954 yyerror("invalid type assertion: %v (non-interface type %v on left)", n, t)
960 n.Right = typecheck(n.Right, Etype)
961 n.Type = n.Right.Type
968 if n.Type != nil && !n.Type.IsInterface() {
969 var missing, have *Field
971 if !implements(n.Type, t, &missing, &have, &ptr) {
972 if have != nil && have.Sym == missing.Sym {
973 yyerror("impossible type assertion:\n\t%v does not implement %v (wrong type for %v method)\n"+
974 "\t\thave %v%0S\n\t\twant %v%0S", n.Type, t, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
976 yyerror("impossible type assertion:\n\t%v does not implement %v (%v method has pointer receiver)", n.Type, t, missing.Sym)
977 } else if have != nil {
978 yyerror("impossible type assertion:\n\t%v does not implement %v (missing %v method)\n"+
979 "\t\thave %v%0S\n\t\twant %v%0S", n.Type, t, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
981 yyerror("impossible type assertion:\n\t%v does not implement %v (missing %v method)", n.Type, t, missing.Sym)
992 n.Left = typecheck(n.Left, Erv)
993 n.Left = defaultlit(n.Left, nil)
994 n.Left = implicitstar(n.Left)
996 n.Right = typecheck(n.Right, Erv)
999 if t == nil || r.Type == nil {
1005 yyerror("invalid operation: %v (type %v does not support indexing)", n, t)
1009 case TSTRING, TARRAY, TSLICE:
1010 n.Right = indexlit(n.Right)
1019 } else if t.IsSlice() {
1023 if n.Right.Type != nil && !n.Right.Type.IsInteger() {
1024 yyerror("non-integer %s index %v", why, n.Right)
1028 if !n.Bounded && Isconst(n.Right, CTINT) {
1029 x := n.Right.Int64()
1031 yyerror("invalid %s index %v (index must be non-negative)", why, n.Right)
1032 } else if t.IsArray() && x >= t.NumElem() {
1033 yyerror("invalid array index %v (out of bounds for %d-element array)", n.Right, t.NumElem())
1034 } else if Isconst(n.Left, CTSTR) && x >= int64(len(n.Left.Val().U.(string))) {
1035 yyerror("invalid string index %v (out of bounds for %d-byte string)", n.Right, len(n.Left.Val().U.(string)))
1036 } else if n.Right.Val().U.(*Mpint).Cmp(maxintval[TINT]) > 0 {
1037 yyerror("invalid %s index %v (index too large)", why, n.Right)
1043 n.Right = defaultlit(n.Right, t.Key())
1044 if n.Right.Type != nil {
1045 n.Right = assignconv(n.Right, t.Key(), "map index")
1055 n.Left = typecheck(n.Left, Erv)
1056 n.Left = defaultlit(n.Left, nil)
1064 yyerror("invalid operation: %v (receive from non-chan type %v)", n, t)
1069 if !t.ChanDir().CanRecv() {
1070 yyerror("invalid operation: %v (receive from send-only type %v)", n, t)
1080 n.Left = typecheck(n.Left, Erv)
1082 n.Right = typecheck(n.Right, Erv)
1083 n.Left = defaultlit(n.Left, nil)
1091 yyerror("invalid operation: %v (send to non-chan type %v)", n, t)
1096 if !t.ChanDir().CanSend() {
1097 yyerror("invalid operation: %v (send to receive-only type %v)", n, t)
1102 n.Right = defaultlit(n.Right, t.Elem())
1108 n.Right = assignconv(r, l.Type.Elem(), "send")
1110 // TODO: more aggressive
1116 case OSLICE, OSLICE3:
1118 n.Left = typecheck(n.Left, top)
1119 low, high, max := n.SliceBounds()
1120 hasmax := n.Op.IsSlice3()
1121 low = typecheck(low, Erv)
1122 high = typecheck(high, Erv)
1123 max = typecheck(max, Erv)
1124 n.Left = defaultlit(n.Left, nil)
1126 high = indexlit(high)
1128 n.SetSliceBounds(low, high, max)
1130 if l.Type.IsArray() {
1131 if !islvalue(n.Left) {
1132 yyerror("invalid operation %v (slice of unaddressable value)", n)
1137 n.Left = nod(OADDR, n.Left, nil)
1138 n.Left.Implicit = true
1139 n.Left = typecheck(n.Left, Erv)
1151 yyerror("invalid operation %v (3-index slice of string)", n)
1157 } else if t.IsPtr() && t.Elem().IsArray() {
1159 n.Type = typSlice(tp.Elem())
1166 } else if t.IsSlice() {
1169 yyerror("cannot slice %v (type %v)", l, t)
1174 if low != nil && !checksliceindex(l, low, tp) {
1178 if high != nil && !checksliceindex(l, high, tp) {
1182 if max != nil && !checksliceindex(l, max, tp) {
1186 if !checksliceconst(low, high) || !checksliceconst(low, max) || !checksliceconst(high, max) {
1192 // call and call like
1194 n.Left = typecheck(n.Left, Erv|Etype|Ecall)
1201 if l.Op == ONAME && l.Etype != 0 {
1202 // TODO(marvin): Fix Node.EType type union.
1203 if n.Isddd && Op(l.Etype) != OAPPEND {
1204 yyerror("invalid use of ... with builtin %v", l)
1207 // builtin: OLEN, OCAP, etc.
1208 // TODO(marvin): Fix Node.EType type union.
1212 n = typecheck1(n, top)
1216 n.Left = defaultlit(n.Left, nil)
1219 if n.Isddd || l.Type.isDDDArray() {
1221 yyerror("invalid use of ... in type conversion to %v", l.Type)
1226 // pick off before type-checking arguments
1229 // turn CALL(type, arg) into CONV(arg) w/ type
1234 if !onearg(n, "conversion to %v", l.Type) {
1238 n = typecheck1(n, top)
1242 if n.List.Len() == 1 && !n.Isddd {
1243 n.List.SetIndex(0, typecheck(n.List.Index(0), Erv|Efnstruct))
1245 typecheckslice(n.List.Slice(), Erv)
1261 // typecheckaste was used here but there wasn't enough
1262 // information further down the call chain to know if we
1263 // were testing a method receiver for unexported fields.
1264 // It isn't necessary, so just do a sanity check.
1267 if l.Left == nil || !eqtype(l.Left.Type, tp) {
1268 Fatalf("method receiver")
1273 if t.Etype != TFUNC {
1274 yyerror("cannot call non-function %v (type %v)", l, t)
1280 typecheckaste(OCALL, n.Left, n.Isddd, t.Params(), n.List, func() string { return fmt.Sprintf("argument to %v", n.Left) })
1282 if t.Results().NumFields() == 0 {
1286 if t.Results().NumFields() == 1 {
1287 n.Type = l.Type.Results().Field(0).Type
1289 if n.Op == OCALLFUNC && n.Left.Op == ONAME && (compiling_runtime || n.Left.Sym.Pkg == Runtimepkg) && n.Left.Sym.Name == "getg" {
1290 // Emit code for runtime.getg() directly instead of calling function.
1291 // Most such rewrites (for example the similar one for math.Sqrt) should be done in walk,
1292 // so that the ordering pass can make sure to preserve the semantics of the original code
1293 // (in particular, the exact time of the function call) by introducing temporaries.
1294 // In this case, we know getg() always returns the same result within a given function
1295 // and we want to avoid the temporaries, so we do the rewrite earlier than is typical.
1303 if top&(Efnstruct|Etop) == 0 {
1304 yyerror("multiple-value %v() in single-value context", l)
1308 n.Type = l.Type.Results()
1312 case OALIGNOF, OOFFSETOF, OSIZEOF:
1314 if !onearg(n, "%v", n.Op) {
1319 // any side effects disappear; ignore init
1321 Nodconst(&r, Types[TUINTPTR], evalunsafe(n))
1327 case OCAP, OLEN, OREAL, OIMAG:
1329 if !onearg(n, "%v", n.Op) {
1333 n.Left = typecheck(n.Left, Erv)
1334 n.Left = defaultlit(n.Left, nil)
1335 n.Left = implicitstar(n.Left)
1344 if !okforcap[t.Etype] {
1349 if !okforlen[t.Etype] {
1357 if Isconst(l, CTCPLX) {
1360 n = nodfltconst(&l.Val().U.(*Mpcplx).Real)
1362 n = nodfltconst(&l.Val().U.(*Mpcplx).Imag)
1367 n.Type = Types[cplxsubtype(t.Etype)]
1371 // might be constant
1374 if Isconst(l, CTSTR) {
1376 Nodconst(&r, Types[TINT], int64(len(l.Val().U.(string))))
1382 if callrecv(l) { // has call or receive
1386 Nodconst(&r, Types[TINT], t.NumElem())
1391 n.Type = Types[TINT]
1395 yyerror("invalid argument %L for %v", n.Left, n.Op)
1403 if n.List.Len() == 1 {
1404 typecheckslice(n.List.Slice(), Efnstruct)
1405 if n.List.First().Op != OCALLFUNC && n.List.First().Op != OCALLMETH {
1406 yyerror("invalid operation: complex expects two arguments")
1411 t := n.List.First().Left.Type
1412 if !t.IsKind(TFUNC) {
1413 // Bail. This error will be reported elsewhere.
1416 if t.Results().NumFields() != 2 {
1417 yyerror("invalid operation: complex expects two arguments, %v returns %d results", n.List.First(), t.Results().NumFields())
1422 t = n.List.First().Type
1423 l = t.Field(0).Nname
1424 r = t.Field(1).Nname
1430 n.Left = typecheck(n.Left, Erv)
1431 n.Right = typecheck(n.Right, Erv)
1434 if l.Type == nil || r.Type == nil {
1438 l, r = defaultlit2(l, r, false)
1439 if l.Type == nil || r.Type == nil {
1447 if !eqtype(l.Type, r.Type) {
1448 yyerror("invalid operation: %v (mismatched types %v and %v)", n, l.Type, r.Type)
1454 switch l.Type.Etype {
1456 yyerror("invalid operation: %v (arguments have type %v, expected floating-point)", n, l.Type)
1464 t = Types[TCOMPLEX64]
1467 t = Types[TCOMPLEX128]
1470 if l.Op == OLITERAL && r.Op == OLITERAL {
1471 // make it a complex literal
1472 r = nodcplxlit(l.Val(), r.Val())
1482 if !onearg(n, "%v", n.Op) {
1486 n.Left = typecheck(n.Left, Erv)
1487 n.Left = defaultlit(n.Left, nil)
1495 yyerror("invalid operation: %v (non-chan type %v)", n, t)
1500 if !t.ChanDir().CanSend() {
1501 yyerror("invalid operation: %v (cannot close receive-only channel)", n)
1511 if args.Len() == 0 {
1512 yyerror("missing arguments to delete")
1517 if args.Len() == 1 {
1518 yyerror("missing second (key) argument to delete")
1523 if args.Len() != 2 {
1524 yyerror("too many arguments to delete")
1530 typecheckslice(args.Slice(), Erv)
1533 if l.Type != nil && !l.Type.IsMap() {
1534 yyerror("first argument to delete must be map; have %L", l.Type)
1539 args.SetIndex(1, assignconv(r, l.Type.Key(), "delete"))
1545 if args.Len() == 0 {
1546 yyerror("missing arguments to append")
1551 if args.Len() == 1 && !n.Isddd {
1552 args.SetIndex(0, typecheck(args.Index(0), Erv|Efnstruct))
1554 typecheckslice(args.Slice(), Erv)
1557 t := args.First().Type
1563 // Unpack multiple-return result before type-checking.
1565 if t.IsFuncArgStruct() {
1572 if Isconst(args.First(), CTNIL) {
1573 yyerror("first argument to append must be typed slice; have untyped nil")
1578 yyerror("first argument to append must be slice; have %L", t)
1584 if args.Len() == 1 {
1585 yyerror("cannot use ... on first argument to append")
1590 if args.Len() != 2 {
1591 yyerror("too many arguments to append")
1596 if t.Elem().IsKind(TUINT8) && args.Second().Type.IsString() {
1597 args.SetIndex(1, defaultlit(args.Index(1), Types[TSTRING]))
1601 args.SetIndex(1, assignconv(args.Index(1), t.Orig, "append"))
1606 _, it := iterFields(funarg) // Skip first field
1607 for t := it.Next(); t != nil; t = it.Next() {
1608 if assignop(t.Type, n.Type.Elem(), nil) == 0 {
1609 yyerror("cannot append %v value to []%v", t.Type, n.Type.Elem())
1613 as := args.Slice()[1:]
1614 for i, n := range as {
1618 as[i] = assignconv(n, t.Elem(), "append")
1628 yyerror("missing arguments to copy")
1634 yyerror("too many arguments to copy")
1639 n.Left = args.First()
1640 n.Right = args.Second()
1642 n.Type = Types[TINT]
1643 n.Left = typecheck(n.Left, Erv)
1644 n.Right = typecheck(n.Right, Erv)
1645 if n.Left.Type == nil || n.Right.Type == nil {
1649 n.Left = defaultlit(n.Left, nil)
1650 n.Right = defaultlit(n.Right, nil)
1651 if n.Left.Type == nil || n.Right.Type == nil {
1656 // copy([]byte, string)
1657 if n.Left.Type.IsSlice() && n.Right.Type.IsString() {
1658 if eqtype(n.Left.Type.Elem(), bytetype) {
1661 yyerror("arguments to copy have different element types: %L and string", n.Left.Type)
1666 if !n.Left.Type.IsSlice() || !n.Right.Type.IsSlice() {
1667 if !n.Left.Type.IsSlice() && !n.Right.Type.IsSlice() {
1668 yyerror("arguments to copy must be slices; have %L, %L", n.Left.Type, n.Right.Type)
1669 } else if !n.Left.Type.IsSlice() {
1670 yyerror("first argument to copy should be slice; have %L", n.Left.Type)
1672 yyerror("second argument to copy should be slice or string; have %L", n.Right.Type)
1678 if !eqtype(n.Left.Type.Elem(), n.Right.Type.Elem()) {
1679 yyerror("arguments to copy have different element types: %L and %L", n.Left.Type, n.Right.Type)
1689 n.Left = typecheck(n.Left, Erv)
1690 n.Left = convlit1(n.Left, n.Type, true, noReuse)
1692 if t == nil || n.Type == nil {
1697 n.Op = convertop(t, n.Type, &why)
1699 if !n.Diag && !n.Type.Broke {
1700 yyerror("cannot convert %L to type %v%s", n.Left, n.Type, why)
1709 if n.Left.Op == OLITERAL {
1710 r := nod(OXXX, nil, nil)
1715 n.SetVal(n.Left.Val())
1718 // do not use stringtoarraylit.
1719 // generated code and compiler memory footprint is better without it.
1724 if n.Left.Op == OLITERAL {
1725 n = stringtoarraylit(n)
1733 args := n.List.Slice()
1735 yyerror("missing argument to make")
1742 l = typecheck(l, Etype)
1752 yyerror("cannot make type %v", t)
1758 yyerror("missing len argument to make(%v)", t)
1765 l = typecheck(l, Erv)
1770 r = typecheck(r, Erv)
1773 if l.Type == nil || (r != nil && r.Type == nil) {
1777 if !checkmake(t, "len", l) || r != nil && !checkmake(t, "cap", r) {
1781 if Isconst(l, CTINT) && r != nil && Isconst(r, CTINT) && l.Val().U.(*Mpint).Cmp(r.Val().U.(*Mpint)) > 0 {
1782 yyerror("len larger than cap in make(%v)", t)
1795 l = typecheck(l, Erv)
1796 l = defaultlit(l, Types[TINT])
1801 if !checkmake(t, "size", l) {
1807 n.Left = nodintconst(0)
1816 l = typecheck(l, Erv)
1817 l = defaultlit(l, Types[TINT])
1822 if !checkmake(t, "buffer", l) {
1828 n.Left = nodintconst(0)
1834 yyerror("too many arguments to make(%v)", t)
1846 if args.Len() == 0 {
1847 yyerror("missing argument to new")
1853 l = typecheck(l, Etype)
1860 yyerror("too many arguments to new(%v)", t)
1869 case OPRINT, OPRINTN:
1871 typecheckslice(n.List.Slice(), Erv)
1872 ls := n.List.Slice()
1873 for i1, n1 := range ls {
1874 // Special case for print: int constant is int64, not int.
1875 if Isconst(n1, CTINT) {
1876 ls[i1] = defaultlit(ls[i1], Types[TINT64])
1878 ls[i1] = defaultlit(ls[i1], nil)
1886 if !onearg(n, "panic") {
1890 n.Left = typecheck(n.Left, Erv)
1891 n.Left = defaultlit(n.Left, Types[TINTER])
1892 if n.Left.Type == nil {
1900 if n.List.Len() != 0 {
1901 yyerror("too many arguments to recover")
1906 n.Type = Types[TINTER]
1911 typecheckclosure(n, top)
1919 n.Left = typecheck(n.Left, Erv)
1925 if !t.IsInterface() {
1926 Fatalf("OITAB of %v", t)
1928 n.Type = ptrto(Types[TUINTPTR])
1932 // Whoever creates the OIDATA node must know a priori the concrete type at that moment,
1933 // usually by just having checked the OITAB.
1934 Fatalf("cannot typecheck interface data %v", n)
1939 n.Left = typecheck(n.Left, Erv)
1945 if !t.IsSlice() && !t.IsString() {
1946 Fatalf("OSPTR of %v", t)
1949 n.Type = ptrto(Types[TUINT8])
1951 n.Type = ptrto(t.Elem())
1961 n.Left = typecheck(n.Left, Erv)
1962 n.Type = Types[TUINTPTR]
1967 n.Left = typecheck(n.Left, Erv)
1976 // Code that creates temps does not bother to set defn, so do it here.
1977 if n.Left.Op == ONAME && n.Left.IsAutoTmp() {
1978 n.Left.Name.Defn = n
2005 n.Left = typecheck(n.Left, Etop|Erv)
2013 n.Left = typecheck(n.Left, Etop|Erv)
2019 typecheckslice(n.Ninit.Slice(), Etop)
2021 n.Left = typecheck(n.Left, Erv)
2024 if t != nil && !t.IsBoolean() {
2025 yyerror("non-bool %L used as for condition", n.Left)
2028 n.Right = typecheck(n.Right, Etop)
2029 typecheckslice(n.Nbody.Slice(), Etop)
2035 typecheckslice(n.Ninit.Slice(), Etop)
2036 n.Left = typecheck(n.Left, Erv)
2039 if t != nil && !t.IsBoolean() {
2040 yyerror("non-bool %L used as if condition", n.Left)
2043 typecheckslice(n.Nbody.Slice(), Etop)
2044 typecheckslice(n.Rlist.Slice(), Etop)
2049 if n.List.Len() == 1 {
2050 typecheckslice(n.List.Slice(), Erv|Efnstruct)
2052 typecheckslice(n.List.Slice(), Erv)
2055 yyerror("return outside function")
2060 if Curfn.Type.FuncType().Outnamed && n.List.Len() == 0 {
2063 typecheckaste(ORETURN, nil, false, Curfn.Type.Results(), n.List, func() string { return "return argument" })
2086 yyerror("use of .(type) outside type switch")
2092 typecheckslice(n.List.Slice(), Erv)
2093 typecheckslice(n.Nbody.Slice(), Etop)
2103 n.Left = typecheck(n.Left, Erv)
2108 n.Left = typecheck(n.Left, Etype)
2109 checkwidth(n.Left.Type)
2110 if n.Left.Type != nil && n.Left.Type.NotInHeap && n.Left.Name.Param.Pragma&NotInHeap == 0 {
2111 // The type contains go:notinheap types, so it
2112 // must be marked as such (alternatively, we
2113 // could silently propagate go:notinheap).
2114 yyerror("type %v must be go:notinheap", n.Left.Type)
2120 if t != nil && !t.IsFuncArgStruct() && n.Op != OTYPE {
2122 case TFUNC, // might have TANY; wait until it's called
2123 TANY, TFORW, TIDEAL, TNIL, TBLANK:
2131 if safemode && importpkg == nil && compiling_wrappers == 0 && t != nil && t.Etype == TUNSAFEPTR {
2132 yyerror("cannot use unsafe.Pointer")
2136 if n.Op == OTYPE && top&Etype == 0 {
2137 yyerror("type %v is not an expression", n.Type)
2142 if top&(Erv|Etype) == Etype && n.Op != OTYPE {
2143 yyerror("%v is not a type", n)
2148 // TODO(rsc): simplify
2149 if (top&(Ecall|Erv|Etype) != 0) && top&Etop == 0 && ok&(Erv|Etype|Ecall) == 0 {
2150 yyerror("%v used as value", n)
2155 if (top&Etop != 0) && top&(Ecall|Erv|Etype) == 0 && ok&Etop == 0 {
2157 yyerror("%v evaluated but not used", n)
2167 fatal("typecheck nil type");
2172 func checksliceindex(l *Node, r *Node, tp *Type) bool {
2178 yyerror("invalid slice index %v (type %v)", r, t)
2182 if r.Op == OLITERAL {
2184 yyerror("invalid slice index %v (index must be non-negative)", r)
2186 } else if tp != nil && tp.NumElem() > 0 && r.Int64() > tp.NumElem() {
2187 yyerror("invalid slice index %v (out of bounds for %d-element array)", r, tp.NumElem())
2189 } else if Isconst(l, CTSTR) && r.Int64() > int64(len(l.Val().U.(string))) {
2190 yyerror("invalid slice index %v (out of bounds for %d-byte string)", r, len(l.Val().U.(string)))
2192 } else if r.Val().U.(*Mpint).Cmp(maxintval[TINT]) > 0 {
2193 yyerror("invalid slice index %v (index too large)", r)
2201 func checksliceconst(lo *Node, hi *Node) bool {
2202 if lo != nil && hi != nil && lo.Op == OLITERAL && hi.Op == OLITERAL && lo.Val().U.(*Mpint).Cmp(hi.Val().U.(*Mpint)) > 0 {
2203 yyerror("invalid slice index: %v > %v", lo, hi)
2210 func checkdefergo(n *Node) {
2241 OLITERAL: // conversion or unsafe.Alignof, Offsetof, Sizeof
2242 if n.Left.Orig != nil && n.Left.Orig.Op == OCONV {
2245 yyerror("%s discards result of %v", what, n.Left)
2249 // type is broken or missing, most likely a method call on a broken type
2250 // we will warn about the broken type elsewhere. no need to emit a potentially confusing error
2251 if n.Left.Type == nil || n.Left.Type.Broke {
2256 // The syntax made sure it was a call, so this must be
2259 yyerror("%s requires function call, not conversion", what)
2263 // The result of implicitstar MUST be assigned back to n, e.g.
2264 // n.Left = implicitstar(n.Left)
2265 func implicitstar(n *Node) *Node {
2266 // insert implicit * if needed for fixed array
2268 if t == nil || !t.IsPtr() {
2278 n = nod(OIND, n, nil)
2280 n = typecheck(n, Erv)
2284 func onearg(n *Node, f string, args ...interface{}) bool {
2288 if n.List.Len() == 0 {
2289 p := fmt.Sprintf(f, args...)
2290 yyerror("missing argument to %s: %v", p, n)
2294 if n.List.Len() > 1 {
2295 p := fmt.Sprintf(f, args...)
2296 yyerror("too many arguments to %s: %v", p, n)
2297 n.Left = n.List.First()
2302 n.Left = n.List.First()
2307 func twoarg(n *Node) bool {
2311 if n.List.Len() == 0 {
2312 yyerror("missing argument to %v - %v", n.Op, n)
2316 n.Left = n.List.First()
2317 if n.List.Len() == 1 {
2318 yyerror("missing argument to %v - %v", n.Op, n)
2323 if n.List.Len() > 2 {
2324 yyerror("too many arguments to %v - %v", n.Op, n)
2329 n.Right = n.List.Second()
2334 func lookdot1(errnode *Node, s *Sym, t *Type, fs *Fields, dostrcmp int) *Field {
2336 for _, f := range fs.Slice() {
2337 if dostrcmp != 0 && f.Sym.Name == s.Name {
2340 if dostrcmp == 2 && strings.EqualFold(f.Sym.Name, s.Name) {
2348 yyerror("ambiguous selector %v", errnode)
2349 } else if t.IsPtr() {
2350 yyerror("ambiguous selector (%v).%v", t, s)
2352 yyerror("ambiguous selector %v.%v", t, s)
2363 func looktypedot(n *Node, t *Type, dostrcmp int) bool {
2366 if t.IsInterface() {
2367 f1 := lookdot1(n, s, t, t.Fields(), dostrcmp)
2372 n.Sym = methodsym(n.Sym, t, 0)
2373 n.Xoffset = f1.Offset
2379 // Find the base type: methtype will fail if t
2380 // is not of the form T or *T.
2387 f2 := lookdot1(n, s, mt, mt.AllMethods(), dostrcmp)
2392 // disallow T.m if m requires *T receiver
2393 if f2.Type.Recv().Type.IsPtr() && !t.IsPtr() && f2.Embedded != 2 && !isifacemethod(f2.Type) {
2394 yyerror("invalid method expression %v (needs pointer receiver: (*%v).%S)", n, t, f2.Sym)
2398 n.Sym = methodsym(n.Sym, t, 0)
2399 n.Xoffset = f2.Offset
2405 func derefall(t *Type) *Type {
2406 for t != nil && t.Etype == Tptr {
2412 type typeSym struct {
2417 // dotField maps (*Type, *Sym) pairs to the corresponding struct field (*Type with Etype==TFIELD).
2418 // It is a cache for use during usefield in walk.go, only enabled when field tracking.
2419 var dotField = map[typeSym]*Field{}
2421 func lookdot(n *Node, t *Type, dostrcmp int) *Field {
2426 if t.IsStruct() || t.IsInterface() {
2427 f1 = lookdot1(n, s, t, t.Fields(), dostrcmp)
2431 if n.Left.Type == t || n.Left.Type.Sym == nil {
2434 // Use f2->method, not f2->xmethod: adddot has
2435 // already inserted all the necessary embedded dots.
2436 f2 = lookdot1(n, s, mt, mt.Methods(), dostrcmp)
2442 // Already in the process of diagnosing an error.
2446 yyerror("%v is both field and method", n.Sym)
2448 if f1.Offset == BADWIDTH {
2449 Fatalf("lookdot badwidth %v %p", f1, f1)
2451 n.Xoffset = f1.Offset
2453 if obj.Fieldtrack_enabled > 0 {
2454 dotField[typeSym{t.Orig, s}] = f1
2456 if t.IsInterface() {
2457 if n.Left.Type.IsPtr() {
2458 n.Left = nod(OIND, n.Left, nil) // implicitstar
2459 n.Left.Implicit = true
2460 n.Left = typecheck(n.Left, Erv)
2471 // Already in the process of diagnosing an error.
2476 rcvr := f2.Type.Recv().Type
2477 if !eqtype(rcvr, tt) {
2478 if rcvr.Etype == Tptr && eqtype(rcvr.Elem(), tt) {
2479 checklvalue(n.Left, "call pointer method on")
2480 n.Left = nod(OADDR, n.Left, nil)
2481 n.Left.Implicit = true
2482 n.Left = typecheck(n.Left, Etype|Erv)
2483 } else if tt.Etype == Tptr && rcvr.Etype != Tptr && eqtype(tt.Elem(), rcvr) {
2484 n.Left = nod(OIND, n.Left, nil)
2485 n.Left.Implicit = true
2486 n.Left = typecheck(n.Left, Etype|Erv)
2487 } else if tt.Etype == Tptr && tt.Elem().Etype == Tptr && eqtype(derefall(tt), derefall(rcvr)) {
2488 yyerror("calling method %v with receiver %L requires explicit dereference", n.Sym, n.Left)
2489 for tt.Etype == Tptr {
2490 // Stop one level early for method with pointer receiver.
2491 if rcvr.Etype == Tptr && tt.Elem().Etype != Tptr {
2494 n.Left = nod(OIND, n.Left, nil)
2495 n.Left.Implicit = true
2496 n.Left = typecheck(n.Left, Etype|Erv)
2500 Fatalf("method mismatch: %v for %v", rcvr, tt)
2506 for ll.Left != nil && (ll.Op == ODOT || ll.Op == ODOTPTR || ll.Op == OIND) {
2510 if pll.Implicit && ll.Type.IsPtr() && ll.Type.Sym != nil && ll.Type.Sym.Def != nil && ll.Type.Sym.Def.Op == OTYPE {
2511 // It is invalid to automatically dereference a named pointer type when selecting a method.
2512 // Make n->left == ll to clarify error message.
2517 n.Sym = methodsym(n.Sym, n.Left.Type, 0)
2518 n.Xoffset = f2.Offset
2521 // print("lookdot found [%p] %T\n", f2->type, f2->type);
2530 func nokeys(l Nodes) bool {
2531 for _, n := range l.Slice() {
2532 if n.Op == OKEY || n.Op == OSTRUCTKEY {
2539 func hasddd(t *Type) bool {
2540 for _, tl := range t.Fields().Slice() {
2549 // typecheck assignment: type list = expression list
2550 func typecheckaste(op Op, call *Node, isddd bool, tstruct *Type, nl Nodes, desc func() string) {
2567 if n.Type.IsFuncArgStruct() {
2568 if !hasddd(tstruct) {
2569 n1 := tstruct.NumFields()
2570 n2 := n.Type.NumFields()
2579 tn, it := iterFields(n.Type)
2581 for _, tl := range tstruct.Fields().Slice() {
2583 for ; tn != nil; tn = it.Next() {
2584 if assignop(tn.Type, tl.Type.Elem(), &why) == 0 {
2586 yyerror("cannot use %v as type %v in argument to %v%s", tn.Type, tl.Type.Elem(), call, why)
2588 yyerror("cannot use %v as type %v in %s%s", tn.Type, tl.Type.Elem(), desc(), why)
2599 if assignop(tn.Type, tl.Type, &why) == 0 {
2601 yyerror("cannot use %v as type %v in argument to %v%s", tn.Type, tl.Type, call, why)
2603 yyerror("cannot use %v as type %v in %s%s", tn.Type, tl.Type, desc(), why)
2618 n1 = tstruct.NumFields()
2620 if !hasddd(tstruct) {
2643 for _, tl := range tstruct.Fields().Slice() {
2656 nl.SetIndex(i, assignconvfn(n, t, desc))
2661 for ; i < nl.Len(); i++ {
2665 nl.SetIndex(i, assignconvfn(n, t.Elem(), desc))
2678 nl.SetIndex(i, assignconvfn(n, t, desc))
2688 yyerror("invalid use of ... in call to %v", call)
2690 yyerror("invalid use of ... in %v", op)
2699 if n == nil || !n.Diag {
2701 // call is the expression being called, not the overall call.
2702 // Method expressions have the form T.M, and the compiler has
2703 // rewritten those to ONAME nodes but left T in Left.
2704 if call.Op == ONAME && call.Left != nil && call.Left.Op == OTYPE {
2705 yyerror("not enough arguments in call to method expression %v\n\thave %s\n\twant %v", call, nl.retsigerr(isddd), tstruct)
2707 yyerror("not enough arguments in call to %v\n\thave %s\n\twant %v", call, nl.retsigerr(isddd), tstruct)
2710 yyerror("not enough arguments to %v\n\thave %s\n\twant %v", op, nl.retsigerr(isddd), tstruct)
2721 yyerror("too many arguments in call to %v\n\thave %s\n\twant %v", call, nl.retsigerr(isddd), tstruct)
2723 yyerror("too many arguments to %v\n\thave %s\n\twant %v", op, nl.retsigerr(isddd), tstruct)
2728 // sigrepr is a type's representation to the outside world,
2729 // in string representations of return signatures
2730 // e.g in error messages about wrong arguments to return.
2731 func (t *Type) sigrepr() string {
2737 // "untyped number" is not commonly used
2738 // outside of the compiler, so let's use "number".
2749 // retsigerr returns the signature of the types
2750 // at the respective return call site of a function.
2751 func (nl Nodes) retsigerr(isddd bool) string {
2756 var typeStrings []string
2757 if nl.Len() == 1 && nl.First().Type != nil && nl.First().Type.IsFuncArgStruct() {
2758 for _, f := range nl.First().Type.Fields().Slice() {
2759 typeStrings = append(typeStrings, f.Type.sigrepr())
2762 for _, n := range nl.Slice() {
2763 typeStrings = append(typeStrings, n.Type.sigrepr())
2771 return fmt.Sprintf("(%s%s)", strings.Join(typeStrings, ", "), ddd)
2774 // type check composite
2775 func fielddup(name string, hash map[string]bool) {
2777 yyerror("duplicate field name in struct literal: %s", name)
2783 func keydup(n *Node, hash map[uint32][]*Node) {
2785 if n.Op == OCONVIFACE {
2789 if n.Op != OLITERAL {
2790 return // we don't check variables
2796 switch v := n.Val().U.(type) {
2797 default: // unknown, bool, nil
2801 h = uint32(v.Int64())
2804 x := math.Float64bits(v.Float64())
2805 for i := 0; i < 8; i++ {
2806 h = h*PRIME1 + uint32(x&0xFF)
2811 for i := 0; i < len(v); i++ {
2812 h = h*PRIME1 + uint32(v[i])
2817 for _, a := range hash[h] {
2820 if a.Op == OCONVIFACE && orign.Op == OCONVIFACE {
2823 if !eqtype(a.Type, n.Type) {
2828 if cmp.Op != OLITERAL {
2829 // Sometimes evconst fails. See issue 12536.
2832 if cmp.Val().U.(bool) {
2833 yyerror("duplicate key %v in map literal", n)
2838 hash[h] = append(hash[h], orign)
2841 // iscomptype reports whether type t is a composite literal type
2842 // or a pointer to one.
2843 func iscomptype(t *Type) bool {
2849 case TARRAY, TSLICE, TSTRUCT, TMAP:
2856 func pushtype(n *Node, t *Type) {
2857 if n == nil || n.Op != OCOMPLIT || !iscomptype(t) {
2862 n.Right = typenod(t)
2863 n.Implicit = true // don't print
2864 n.Right.Implicit = true // * is okay
2865 } else if Debug['s'] != 0 {
2866 n.Right = typecheck(n.Right, Etype)
2867 if n.Right.Type != nil && eqtype(n.Right.Type, t) {
2868 fmt.Printf("%v: redundant type: %v\n", n.Line(), t)
2873 // The result of typecheckcomplit MUST be assigned back to n, e.g.
2874 // n.Left = typecheckcomplit(n.Left)
2875 func typecheckcomplit(n *Node) *Node {
2882 if n.List.Len() != 0 {
2883 setlineno(n.List.First())
2885 yyerror("missing type in composite literal")
2890 // Save original node (including n->right)
2891 norig := nod(n.Op, nil, nil)
2896 n.Right = typecheck(n.Right, Etype|Ecomplit)
2907 // For better or worse, we don't allow pointers as the composite literal type,
2908 // except when using the &T syntax, which sets implicit on the OIND.
2909 if !n.Right.Implicit {
2910 yyerror("invalid pointer type %v for composite literal (use &%v instead)", t, t.Elem())
2915 // Also, the underlying type must be a struct, map, slice, or array.
2917 yyerror("invalid pointer type %v for composite literal", t)
2927 yyerror("invalid type for composite literal: %v", t)
2930 case TARRAY, TSLICE:
2931 // If there are key/value pairs, create a map to keep seen
2932 // keys so we can check for duplicate indices.
2933 var indices map[int64]bool
2934 for _, n1 := range n.List.Slice() {
2936 indices = make(map[int64]bool)
2942 checkBounds := t.IsArray() && !t.isDDDArray()
2943 nl := n.List.Slice()
2944 for i2, l := range nl {
2948 l.Left = typecheck(l.Left, Erv)
2950 i = nonnegintconst(l.Left)
2951 if i < 0 && !l.Left.Diag {
2952 yyerror("index must be non-negative integer constant")
2954 i = -(1 << 30) // stay negative for a while
2959 if i >= 0 && indices != nil {
2961 yyerror("duplicate index in array literal: %d", i)
2968 pushtype(r, t.Elem())
2969 r = typecheck(r, Erv)
2970 r = defaultlit(r, t.Elem())
2971 *vp = assignconv(r, t.Elem(), "array or slice literal")
2976 if checkBounds && length > t.NumElem() {
2978 yyerror("array index %d out of bounds [0:%d]", length-1, t.NumElem())
2985 t.SetNumElem(length)
2988 n.Right = nodintconst(length)
2995 hash := make(map[uint32][]*Node)
2996 for i3, l := range n.List.Slice() {
2999 n.List.SetIndex(i3, typecheck(n.List.Index(i3), Erv))
3000 yyerror("missing key in map literal")
3005 pushtype(r, t.Key())
3006 r = typecheck(r, Erv)
3007 r = defaultlit(r, t.Key())
3008 l.Left = assignconv(r, t.Key(), "map key")
3009 if l.Left.Op != OCONV {
3010 keydup(l.Left, hash)
3014 pushtype(r, t.Val())
3015 r = typecheck(r, Erv)
3016 r = defaultlit(r, t.Val())
3017 l.Right = assignconv(r, t.Val(), "map value")
3023 // Need valid field offsets for Xoffset below.
3027 if n.List.Len() != 0 && nokeys(n.List) {
3028 // simple list of variables
3029 f, it := iterFields(t)
3031 ls := n.List.Slice()
3032 for i1, n1 := range ls {
3034 ls[i1] = typecheck(ls[i1], Erv)
3038 yyerror("too many values in struct initializer")
3045 if s != nil && !exportname(s.Name) && s.Pkg != localpkg {
3046 yyerror("implicit assignment of unexported field '%s' in %v literal", s.Name, t)
3048 // No pushtype allowed here. Must name fields for that.
3049 n1 = assignconv(n1, f.Type, "field value")
3050 n1 = nodSym(OSTRUCTKEY, n1, f.Sym)
3051 n1.Xoffset = f.Offset
3057 yyerror("too few values in struct initializer")
3060 hash := make(map[string]bool)
3063 ls := n.List.Slice()
3064 for i, l := range ls {
3074 // An OXDOT uses the Sym field to hold
3075 // the field to the right of the dot,
3076 // so s will be non-nil, but an OXDOT
3077 // is never a valid struct literal key.
3078 if key.Sym == nil || key.Op == OXDOT {
3079 yyerror("invalid field name %v in struct initializer", key)
3080 l.Left = typecheck(l.Left, Erv)
3084 // Sym might have resolved to name in other top-level
3085 // package, because of import dot. Redirect to correct sym
3086 // before we do the lookup.
3088 if s.Pkg != localpkg && exportname(s.Name) {
3089 s1 := lookup(s.Name)
3090 if s1.Origpkg == s.Pkg {
3097 if l.Op != OSTRUCTKEY {
3099 yyerror("mixture of field:value and value initializers")
3102 ls[i] = typecheck(ls[i], Erv)
3106 f := lookdot1(nil, l.Sym, t, t.Fields(), 0)
3108 yyerror("unknown field '%v' in struct literal of type %v", l.Sym, t)
3111 fielddup(f.Sym.Name, hash)
3112 l.Xoffset = f.Offset
3114 // No pushtype allowed here. Tried and rejected.
3115 l.Left = typecheck(l.Left, Erv)
3116 l.Left = assignconv(l.Left, f.Type, "field value")
3123 if nerr != nerrors {
3129 n = nod(OPTRLIT, n, nil)
3131 n.Type = n.Left.Type
3133 n.Left.Typecheck = 1
3141 func islvalue(n *Node) bool {
3144 if n.Left.Type != nil && n.Left.Type.IsArray() {
3145 return islvalue(n.Left)
3147 if n.Left.Type != nil && n.Left.Type.IsString() {
3151 case OIND, ODOTPTR, OCLOSUREVAR:
3155 return islvalue(n.Left)
3158 if n.Class == PFUNC {
3167 func checklvalue(n *Node, verb string) {
3169 yyerror("cannot %s %v", verb, n)
3173 func checkassign(stmt *Node, n *Node) {
3174 // Variables declared in ORANGE are assigned on every iteration.
3175 if n.Name == nil || n.Name.Defn != stmt || stmt.Op == ORANGE {
3178 for l = n; l != r; l = l.Left {
3180 if l.isClosureVar() {
3181 l.Name.Defn.Assigned = true
3186 if l.isClosureVar() {
3187 l.Name.Defn.Assigned = true
3194 if n.Op == OINDEXMAP {
3199 // have already complained about n being undefined
3200 if n.Op == ONONAME {
3204 if n.Op == ODOT && n.Left.Op == OINDEXMAP {
3205 yyerror("cannot assign to struct field %v in map", n)
3209 yyerror("cannot assign to %v", n)
3212 func checkassignlist(stmt *Node, l Nodes) {
3213 for _, n := range l.Slice() {
3214 checkassign(stmt, n)
3218 // Check whether l and r are the same side effect-free expression,
3219 // so that it is safe to reuse one instead of computing both.
3220 func samesafeexpr(l *Node, r *Node) bool {
3221 if l.Op != r.Op || !eqtype(l.Type, r.Type) {
3226 case ONAME, OCLOSUREVAR:
3230 return l.Sym != nil && r.Sym != nil && l.Sym == r.Sym && samesafeexpr(l.Left, r.Left)
3232 case OIND, OCONVNOP:
3233 return samesafeexpr(l.Left, r.Left)
3236 // Some conversions can't be reused, such as []byte(str).
3237 // Allow only numeric-ish types. This is a bit conservative.
3238 return issimple[l.Type.Etype] && samesafeexpr(l.Left, r.Left)
3241 return samesafeexpr(l.Left, r.Left) && samesafeexpr(l.Right, r.Right)
3244 return eqval(l.Val(), r.Val())
3250 // type check assignment.
3251 // if this assignment is the definition of a var on the left side,
3252 // fill in the var's type.
3253 func typecheckas(n *Node) {
3254 // delicate little dance.
3255 // the definition of n may refer to this assignment
3256 // as its definition, in which case it will call typecheckas.
3257 // in that case, do not call typecheck back, or it will cycle.
3258 // if the variable has a type (ntype) then typechecking
3259 // will not look at defn, so it is okay (and desirable,
3260 // so that the conversion below happens).
3261 n.Left = resolve(n.Left)
3263 if n.Left.Name == nil || n.Left.Name.Defn != n || n.Left.Name.Param.Ntype != nil {
3264 n.Left = typecheck(n.Left, Erv|Easgn)
3267 n.Right = typecheck(n.Right, Erv)
3268 checkassign(n, n.Left)
3269 if n.Right != nil && n.Right.Type != nil {
3270 if n.Left.Type != nil {
3271 n.Right = assignconv(n.Right, n.Left.Type, "assignment")
3275 if n.Left.Name != nil && n.Left.Name.Defn == n && n.Left.Name.Param.Ntype == nil {
3276 n.Right = defaultlit(n.Right, nil)
3277 n.Left.Type = n.Right.Type
3280 // second half of dance.
3281 // now that right is done, typecheck the left
3282 // just to get it over with. see dance above.
3285 if n.Left.Typecheck == 0 {
3286 n.Left = typecheck(n.Left, Erv|Easgn)
3290 func checkassignto(src *Type, dst *Node) {
3293 if assignop(src, dst.Type, &why) == 0 {
3294 yyerror("cannot assign %v to %L in multiple assignment%s", src, dst, why)
3299 func typecheckas2(n *Node) {
3300 ls := n.List.Slice()
3301 for i1, n1 := range ls {
3302 // delicate little dance.
3306 if n1.Name == nil || n1.Name.Defn != n || n1.Name.Param.Ntype != nil {
3307 ls[i1] = typecheck(ls[i1], Erv|Easgn)
3313 if cl > 1 && cr == 1 {
3314 n.Rlist.SetIndex(0, typecheck(n.Rlist.Index(0), Erv|Efnstruct))
3316 typecheckslice(n.Rlist.Slice(), Erv)
3318 checkassignlist(n, n.List)
3324 ls := n.List.Slice()
3325 rs := n.Rlist.Slice()
3326 for il, nl := range ls {
3328 if nl.Type != nil && nr.Type != nil {
3329 rs[il] = assignconv(nr, nl.Type, "assignment")
3331 if nl.Name != nil && nl.Name.Defn == n && nl.Name.Param.Ntype == nil {
3332 rs[il] = defaultlit(rs[il], nil)
3333 nl.Type = rs[il].Type
3349 case OCALLMETH, OCALLINTER, OCALLFUNC:
3350 if !r.Type.IsFuncArgStruct() {
3353 cr = r.Type.NumFields()
3358 t, s := iterFields(r.Type)
3359 for _, n3 := range n.List.Slice() {
3360 if t.Type != nil && n3.Type != nil {
3361 checkassignto(t.Type, n3)
3363 if n3.Name != nil && n3.Name.Defn == n && n3.Name.Param.Ntype == nil {
3374 if cl == 2 && cr == 1 {
3379 case OINDEXMAP, ORECV, ODOTTYPE:
3393 checkassignto(r.Type, l)
3395 if l.Name != nil && l.Name.Defn == n {
3398 l := n.List.Second()
3399 if l.Type != nil && !l.Type.IsBoolean() {
3400 checkassignto(Types[TBOOL], l)
3402 if l.Name != nil && l.Name.Defn == n && l.Name.Param.Ntype == nil {
3403 l.Type = Types[TBOOL]
3410 yyerror("assignment count mismatch: %d = %d", cl, cr)
3412 // second half of dance
3416 for i1, n1 := range ls {
3417 if n1.Typecheck == 0 {
3418 ls[i1] = typecheck(ls[i1], Erv|Easgn)
3423 // type check function definition
3424 func typecheckfunc(n *Node) {
3425 for _, ln := range n.Func.Dcl {
3426 if ln.Op == ONAME && (ln.Class == PPARAM || ln.Class == PPARAMOUT) {
3427 ln.Name.Decldepth = 1
3431 n.Func.Nname = typecheck(n.Func.Nname, Erv|Easgn)
3432 t := n.Func.Nname.Type
3437 t.SetNname(n.Func.Nname)
3439 if rcvr != nil && n.Func.Shortname != nil {
3440 n.Func.Nname.Sym = methodname(n.Func.Shortname, rcvr.Type)
3441 declare(n.Func.Nname, PFUNC)
3443 addmethod(n.Func.Shortname, t, true, n.Func.Pragma&Nointerface != 0)
3446 if Ctxt.Flag_dynlink && importpkg == nil && n.Func.Nname != nil {
3447 makefuncsym(n.Func.Nname.Sym)
3451 // The result of stringtoarraylit MUST be assigned back to n, e.g.
3452 // n.Left = stringtoarraylit(n.Left)
3453 func stringtoarraylit(n *Node) *Node {
3454 if n.Left.Op != OLITERAL || n.Left.Val().Ctype() != CTSTR {
3455 Fatalf("stringtoarraylit %v", n)
3458 s := n.Left.Val().U.(string)
3460 if n.Type.Elem().Etype == TUINT8 {
3462 for i := 0; i < len(s); i++ {
3463 l = append(l, nod(OKEY, nodintconst(int64(i)), nodintconst(int64(s[0]))))
3468 for _, r := range s {
3469 l = append(l, nod(OKEY, nodintconst(int64(i)), nodintconst(int64(r))))
3474 nn := nod(OCOMPLIT, nil, typenod(n.Type))
3476 nn = typecheck(nn, Erv)
3480 var ntypecheckdeftype int
3482 var methodqueue []*Node
3484 func domethod(n *Node) {
3485 nt := n.Type.Nname()
3486 nt = typecheck(nt, Etype)
3488 // type check failed; leave empty func
3489 // TODO(mdempsky): Fix Type rekinding.
3490 n.Type.Etype = TFUNC
3496 // type I interface {
3499 // then even though I.M looks like it doesn't care about the
3500 // value of its argument, a specific implementation of I may
3501 // care. The _ would suppress the assignment to that argument
3502 // while generating a call, so remove it.
3503 for _, t := range nt.Type.Params().Fields().Slice() {
3504 if t.Sym != nil && t.Sym.Name == "_" {
3509 // TODO(mdempsky): Fix Type rekinding.
3515 type mapqueueval struct {
3520 // tracks the line numbers at which forward types are first used as map keys
3521 var mapqueue []mapqueueval
3523 func copytype(n *Node, t *Type) {
3524 if t.Etype == TFORW {
3525 // This type isn't computed yet; when it is, update n.
3526 t.ForwardType().Copyto = append(t.ForwardType().Copyto, n)
3530 embedlineno := n.Type.ForwardType().Embedlineno
3531 l := n.Type.ForwardType().Copyto
3533 ptrTo := n.Type.ptrTo
3534 sliceOf := n.Type.sliceOf
3536 // TODO(mdempsky): Fix Type rekinding.
3543 t.Vargen = n.Name.Vargen
3545 t.methods = Fields{}
3546 t.allMethods = Fields{}
3548 t.Deferwidth = false
3552 // Propagate go:notinheap pragma from the Name to the Type.
3553 if n.Name != nil && n.Name.Param != nil && n.Name.Param.Pragma&NotInHeap != 0 {
3557 // Update nodes waiting on this type.
3558 for _, n := range l {
3562 // Double-check use of type as embedded type.
3565 if embedlineno.IsKnown() {
3566 lineno = embedlineno
3567 if t.IsPtr() || t.IsUnsafePtr() {
3568 yyerror("embedded type cannot be a pointer")
3575 func typecheckdeftype(n *Node) {
3581 n.Name.Param.Ntype = typecheck(n.Name.Param.Ntype, Etype)
3582 t := n.Name.Param.Ntype.Type
3594 // copy new type and clear fields
3595 // that don't come along.
3601 // if there are no type definitions going on, it's safe to
3602 // try to resolve the method types for the interfaces
3604 if ntypecheckdeftype == 1 {
3611 for _, n := range s {
3615 for _, e := range mapqueue {
3617 if !e.n.Type.IsComparable() {
3618 yyerror("invalid map key type %v", e.n.Type)
3628 func queuemethod(n *Node) {
3629 if ntypecheckdeftype == 0 {
3634 methodqueue = append(methodqueue, n)
3637 func typecheckdef(n *Node) *Node {
3641 if n.Op == ONONAME {
3644 if n.Pos.IsKnown() {
3648 // Note: adderrorname looks for this string and
3649 // adds context about the outer expression
3650 yyerror("undefined: %v", n.Sym)
3660 typecheckdefstack = append(typecheckdefstack, n)
3663 fmt.Printf("typecheckdef loop:")
3664 for i := len(typecheckdefstack) - 1; i >= 0; i-- {
3665 n := typecheckdefstack[i]
3666 fmt.Printf(" %v", n.Sym)
3669 Fatalf("typecheckdef loop")
3674 if n.Type != nil || n.Sym == nil { // builtin or no name
3680 Fatalf("typecheckdef %v", n.Op)
3682 case OGOTO, OLABEL, OPACK:
3683 // nothing to do here
3686 if n.Name.Param.Ntype != nil {
3687 n.Name.Param.Ntype = typecheck(n.Name.Param.Ntype, Etype)
3688 n.Type = n.Name.Param.Ntype.Type
3689 n.Name.Param.Ntype = nil
3700 Dump("typecheckdef nil defn", n)
3704 e = typecheck(e, Erv)
3705 if Isconst(e, CTNIL) {
3706 yyerror("const initializer cannot be nil")
3710 if e.Type != nil && e.Op != OLITERAL || !isgoconst(e) {
3712 yyerror("const initializer %v is not a constant", e)
3721 if !okforconst[t.Etype] {
3722 yyerror("invalid constant type %v", t)
3726 if !e.Type.IsUntyped() && !eqtype(t, e.Type) {
3727 yyerror("cannot use %L as type %v in const initializer", e, t)
3738 if n.Name.Param.Ntype != nil {
3739 n.Name.Param.Ntype = typecheck(n.Name.Param.Ntype, Etype)
3740 n.Type = n.Name.Param.Ntype.Type
3750 if n.Name.Defn == nil {
3751 if n.Etype != 0 { // like OPRINTN
3754 if nsavederrors+nerrors > 0 {
3755 // Can have undefined variables in x := foo
3756 // that make x have an n->ndefn == nil.
3757 // If there are other errors anyway, don't
3758 // bother adding to the noise.
3762 Fatalf("var without type, init: %v", n.Sym)
3765 if n.Name.Defn.Op == ONAME {
3766 n.Name.Defn = typecheck(n.Name.Defn, Erv)
3767 n.Type = n.Name.Defn.Type
3771 n.Name.Defn = typecheck(n.Name.Defn, Etop) // fills in n->type
3774 if p := n.Name.Param; p.Alias {
3775 // Type alias declaration: Simply use the rhs type - no need
3776 // to create a new type.
3777 // If we have a syntax error, p.Ntype may be nil.
3779 p.Ntype = typecheck(p.Ntype, Etype)
3780 n.Type = p.Ntype.Type
3790 // regular type declaration
3796 n.Type.Sym = n.Sym // TODO(gri) this also happens in typecheckdeftype(n) - where should it happen?
3799 if n.Type.Etype == TFORW && nerrors > nerrors0 {
3800 // Something went wrong during type-checking,
3801 // but it was reported. Silence future errors.
3810 if n.Op != OLITERAL && n.Type != nil && n.Type.IsUntyped() {
3811 Fatalf("got %v for %v", n.Type, n)
3813 last := len(typecheckdefstack) - 1
3814 if typecheckdefstack[last] != n {
3815 Fatalf("typecheckdefstack mismatch")
3817 typecheckdefstack[last] = nil
3818 typecheckdefstack = typecheckdefstack[:last]
3825 func checkmake(t *Type, arg string, n *Node) bool {
3826 if !n.Type.IsInteger() && n.Type.Etype != TIDEAL {
3827 yyerror("non-integer %s argument in make(%v) - %v", arg, t, n.Type)
3831 // Do range checks for constants before defaultlit
3832 // to avoid redundant "constant NNN overflows int" errors.
3833 switch consttype(n) {
3834 case CTINT, CTRUNE, CTFLT, CTCPLX:
3835 n.SetVal(toint(n.Val()))
3836 if n.Val().U.(*Mpint).CmpInt64(0) < 0 {
3837 yyerror("negative %s argument in make(%v)", arg, t)
3840 if n.Val().U.(*Mpint).Cmp(maxintval[TINT]) > 0 {
3841 yyerror("%s argument too large in make(%v)", arg, t)
3846 // defaultlit is necessary for non-constants too: n might be 1.1<<k.
3847 n = defaultlit(n, Types[TINT])
3852 func markbreak(n *Node, implicit *Node) {
3860 if implicit != nil {
3861 implicit.SetHasBreak(true)
3864 lab := n.Left.Sym.Label
3866 lab.SetHasBreak(true)
3878 markbreak(n.Left, implicit)
3879 markbreak(n.Right, implicit)
3880 markbreaklist(n.Ninit, implicit)
3881 markbreaklist(n.Nbody, implicit)
3882 markbreaklist(n.List, implicit)
3883 markbreaklist(n.Rlist, implicit)
3887 func markbreaklist(l Nodes, implicit *Node) {
3889 for i := 0; i < len(s); i++ {
3894 if n.Op == OLABEL && i+1 < len(s) && n.Name.Defn == s[i+1] {
3895 switch n.Name.Defn.Op {
3896 case OFOR, OSWITCH, OTYPESW, OSELECT, ORANGE:
3897 n.Left.Sym.Label = n.Name.Defn
3898 markbreak(n.Name.Defn, n.Name.Defn)
3899 n.Left.Sym.Label = nil
3905 markbreak(n, implicit)
3909 // Isterminating whether the Nodes list ends with a terminating
3911 func (l Nodes) isterminating() bool {
3917 return s[c-1].isterminating()
3920 // Isterminating returns whether the node n, the last one in a
3921 // statement list, is a terminating statement.
3922 func (n *Node) isterminating() bool {
3924 // NOTE: OLABEL is treated as a separate statement,
3925 // not a separate prefix, so skipping to the last statement
3926 // in the block handles the labeled statement case by
3927 // skipping over the label. No case OLABEL here.
3930 return n.List.isterminating()
3949 return n.Nbody.isterminating() && n.Rlist.isterminating()
3951 case OSWITCH, OTYPESW, OSELECT:
3956 for _, n1 := range n.List.Slice() {
3957 if !n1.Nbody.isterminating() {
3960 if n1.List.Len() == 0 { // default
3965 if n.Op != OSELECT && def == 0 {
3974 func checkreturn(fn *Node) {
3975 if fn.Type.Results().NumFields() != 0 && fn.Nbody.Len() != 0 {
3976 markbreaklist(fn.Nbody, nil)
3977 if !fn.Nbody.isterminating() {
3978 yyerrorl(fn.Func.Endlineno, "missing return at end of function")