Debian Codegraph @

interp/typecheck.go

raw symbols SCIP
1 package interp
2
3 import (
4 "errors"
5 "go/constant"
6 "go/token"
7 "math"
8 "reflect"
9 )
10
11 type opPredicates map[action]func(reflect.Type) bool
12
13 // typecheck handles all type checking following "go/types" logic.
14 //
15 // Due to variant type systems (itype vs reflect.Type) a single
16 // type system should used, namely reflect.Type with exception
17 // of the untyped flag on itype.
18 type typecheck struct {
19 scope *scope
20 }
21
22 // op type checks an expression against a set of expression predicates.
23 func (check typecheck) op(p opPredicates, a action, n, c *node, t reflect.Type) error {
24 if pred := p[a]; pred != nil {
25 if !pred(t) {
26 return n.cfgErrorf("invalid operation: operator %v not defined on %s", n.action, c.typ.id())
27 }
28 } else {
29 return n.cfgErrorf("invalid operation: unknown operator %v", n.action)
30 }
31 return nil
32 }
33
34 // assignment checks if n can be assigned to typ.
35 //
36 // Use typ == nil to indicate assignment to an untyped blank identifier.
37 func (check typecheck) assignment(n *node, typ *itype, context string) error {
38 if n.typ == nil {
39 return n.cfgErrorf("invalid type in %s", context)
40 }
41 if n.typ.untyped {
42 if typ == nil || isInterface(typ) {
43 if typ == nil && n.typ.cat == nilT {
44 return n.cfgErrorf("use of untyped nil in %s", context)
45 }
46 typ = n.typ.defaultType(n.rval, check.scope)
47 }
48 if err := check.convertUntyped(n, typ); err != nil {
49 return err
50 }
51 }
52
53 if typ == nil {
54 return nil
55 }
56
57 if !n.typ.assignableTo(typ) && typ.str != "*unsafe2.dummy" {
58 if context == "" {
59 return n.cfgErrorf("cannot use type %s as type %s", n.typ.id(), typ.id())
60 }
61 return n.cfgErrorf("cannot use type %s as type %s in %s", n.typ.id(), typ.id(), context)
62 }
63 return nil
64 }
65
66 // assignExpr type checks an assign expression.
67 //
68 // This is done per pair of assignments.
69 func (check typecheck) assignExpr(n, dest, src *node) error {
70 if n.action == aAssign {
71 isConst := n.anc.kind == constDecl
72 if !isConst {
73 // var operations must be typed
74 dest.typ = dest.typ.defaultType(src.rval, check.scope)
75 }
76
77 return check.assignment(src, dest.typ, "assignment")
78 }
79
80 // assignment operations.
81 if n.nleft > 1 || n.nright > 1 {
82 return n.cfgErrorf("assignment operation %s requires single-valued expressions", n.action)
83 }
84
85 return check.binaryExpr(n)
86 }
87
88 // addressExpr type checks a unary address expression.
89 func (check typecheck) addressExpr(n *node) error {
90 c0 := n.child[0]
91 found := false
92 for !found {
93 switch c0.kind {
94 case parenExpr:
95 c0 = c0.child[0]
96 continue
97 case selectorExpr:
98 c0 = c0.child[1]
99 continue
100 case starExpr:
101 c0 = c0.child[0]
102 continue
103 case indexExpr, sliceExpr:
104 c := c0.child[0]
105 if isArray(c.typ) || isMap(c.typ) {
106 c0 = c
107 found = true
108 continue
109 }
110 case compositeLitExpr, identExpr:
111 found = true
112 continue
113 }
114 return n.cfgErrorf("invalid operation: cannot take address of %s [kind: %s]", c0.typ.id(), kinds[c0.kind])
115 }
116 return nil
117 }
118
119 // starExpr type checks a star expression on a variable.
120 func (check typecheck) starExpr(n *node) error {
121 if n.typ.TypeOf().Kind() != reflect.Ptr {
122 return n.cfgErrorf("invalid operation: cannot indirect %q", n.name())
123 }
124 return nil
125 }
126
127 var unaryOpPredicates = opPredicates{
128 aInc: isNumber,
129 aDec: isNumber,
130 aPos: isNumber,
131 aNeg: isNumber,
132 aBitNot: isInt,
133 aNot: isBoolean,
134 }
135
136 // unaryExpr type checks a unary expression.
137 func (check typecheck) unaryExpr(n *node) error {
138 c0 := n.child[0]
139 if isBlank(c0) {
140 return n.cfgErrorf("cannot use _ as value")
141 }
142 t0 := c0.typ.TypeOf()
143
144 if n.action == aRecv {
145 if !isChan(c0.typ) {
146 return n.cfgErrorf("invalid operation: cannot receive from non-channel %s", c0.typ.id())
147 }
148 if isSendChan(c0.typ) {
149 return n.cfgErrorf("invalid operation: cannot receive from send-only channel %s", c0.typ.id())
150 }
151 return nil
152 }
153
154 return check.op(unaryOpPredicates, n.action, n, c0, t0)
155 }
156
157 // shift type checks a shift binary expression.
158 func (check typecheck) shift(n *node) error {
159 c0, c1 := n.child[0], n.child[1]
160 t0, t1 := c0.typ.TypeOf(), c1.typ.TypeOf()
161
162 var v0 constant.Value
163 if c0.typ.untyped && c0.rval.IsValid() {
164 v0 = constant.ToInt(c0.rval.Interface().(constant.Value))
165 c0.rval = reflect.ValueOf(v0)
166 }
167
168 if !(c0.typ.untyped && v0 != nil && v0.Kind() == constant.Int || isInt(t0)) {
169 return n.cfgErrorf("invalid operation: shift of type %v", c0.typ.id())
170 }
171
172 switch {
173 case c1.typ.untyped:
174 if err := check.convertUntyped(c1, check.scope.getType("uint")); err != nil {
175 return n.cfgErrorf("invalid operation: shift count type %v, must be integer", c1.typ.id())
176 }
177 case isInt(t1):
178 // nothing to do
179 default:
180 return n.cfgErrorf("invalid operation: shift count type %v, must be integer", c1.typ.id())
181 }
182 return nil
183 }
184
185 // comparison type checks a comparison binary expression.
186 func (check typecheck) comparison(n *node) error {
187 t0, t1 := n.child[0].typ, n.child[1].typ
188
189 if !t0.assignableTo(t1) && !t1.assignableTo(t0) {
190 return n.cfgErrorf("invalid operation: mismatched types %s and %s", t0.id(), t1.id())
191 }
192
193 ok := false
194
195 if !isInterface(t0) && !isInterface(t1) && !t0.isNil() && !t1.isNil() && t0.untyped == t1.untyped && t0.id() != t1.id() && !typeDefined(t0, t1) {
196 // Non interface types must be really equals.
197 return n.cfgErrorf("invalid operation: mismatched types %s and %s", t0.id(), t1.id())
198 }
199
200 switch n.action {
201 case aEqual, aNotEqual:
202 ok = t0.comparable() && t1.comparable() || t0.isNil() && t1.hasNil() || t1.isNil() && t0.hasNil()
203 case aLower, aLowerEqual, aGreater, aGreaterEqual:
204 ok = t0.ordered() && t1.ordered()
205 }
206 if !ok {
207 typ := t0
208 if typ.isNil() {
209 typ = t1
210 }
211 return n.cfgErrorf("invalid operation: operator %v not defined on %s", n.action, typ.id())
212 }
213 return nil
214 }
215
216 var binaryOpPredicates = opPredicates{
217 aAdd: func(typ reflect.Type) bool { return isNumber(typ) || isString(typ) },
218 aSub: isNumber,
219 aMul: isNumber,
220 aQuo: isNumber,
221 aRem: isInt,
222
223 aAnd: isInt,
224 aOr: isInt,
225 aXor: isInt,
226 aAndNot: isInt,
227
228 aLand: isBoolean,
229 aLor: isBoolean,
230 }
231
232 // binaryExpr type checks a binary expression.
233 func (check typecheck) binaryExpr(n *node) error {
234 c0, c1 := n.child[0], n.child[1]
235
236 if isBlank(c0) || isBlank(c1) {
237 return n.cfgErrorf("cannot use _ as value")
238 }
239
240 a := n.action
241 if isAssignAction(a) {
242 a--
243 }
244
245 if isShiftAction(a) {
246 return check.shift(n)
247 }
248
249 switch n.action {
250 case aAdd:
251 if n.typ == nil {
252 break
253 }
254 // Catch mixing string and number for "+" operator use.
255 k, k0, k1 := isNumber(n.typ.TypeOf()), isNumber(c0.typ.TypeOf()), isNumber(c1.typ.TypeOf())
256 if k != k0 || k != k1 {
257 return n.cfgErrorf("cannot use type %s as type %s in assignment", c0.typ.id(), n.typ.id())
258 }
259 case aRem:
260 if zeroConst(c1) {
261 return n.cfgErrorf("invalid operation: division by zero")
262 }
263 case aQuo:
264 if zeroConst(c1) {
265 return n.cfgErrorf("invalid operation: division by zero")
266 }
267 if c0.rval.IsValid() && c1.rval.IsValid() {
268 // Avoid constant conversions below to ensure correct constant integer quotient.
269 return nil
270 }
271 }
272
273 // Ensure that if values are untyped, both are converted to the same type
274 _ = check.convertUntyped(c0, c1.typ)
275 _ = check.convertUntyped(c1, c0.typ)
276
277 if isComparisonAction(a) {
278 return check.comparison(n)
279 }
280
281 if !c0.typ.equals(c1.typ) {
282 return n.cfgErrorf("invalid operation: mismatched types %s and %s", c0.typ.id(), c1.typ.id())
283 }
284
285 t0 := c0.typ.TypeOf()
286
287 return check.op(binaryOpPredicates, a, n, c0, t0)
288 }
289
290 func zeroConst(n *node) bool {
291 return n.typ.untyped && constant.Sign(n.rval.Interface().(constant.Value)) == 0
292 }
293
294 func (check typecheck) index(n *node, max int) error {
295 if err := check.convertUntyped(n, check.scope.getType("int")); err != nil {
296 return err
297 }
298
299 if !isInt(n.typ.TypeOf()) {
300 return n.cfgErrorf("index %s must be integer", n.typ.id())
301 }
302
303 if !n.rval.IsValid() || max < 1 {
304 return nil
305 }
306
307 if int(vInt(n.rval)) >= max {
308 return n.cfgErrorf("index %s is out of bounds", n.typ.id())
309 }
310
311 return nil
312 }
313
314 // arrayLitExpr type checks an array composite literal expression.
315 func (check typecheck) arrayLitExpr(child []*node, typ *itype) error {
316 cat := typ.cat
317 length := typ.length
318 typ = typ.val
319 visited := make(map[int]bool, len(child))
320 index := 0
321 for _, c := range child {
322 n := c
323 switch {
324 case c.kind == keyValueExpr:
325 if err := check.index(c.child[0], length); err != nil {
326 return c.cfgErrorf("index %s must be integer constant", c.child[0].typ.id())
327 }
328 n = c.child[1]
329 index = int(vInt(c.child[0].rval))
330 case cat == arrayT && index >= length:
331 return c.cfgErrorf("index %d is out of bounds (>= %d)", index, length)
332 }
333
334 if visited[index] {
335 return n.cfgErrorf("duplicate index %d in array or slice literal", index)
336 }
337 visited[index] = true
338 index++
339
340 if err := check.assignment(n, typ, "array or slice literal"); err != nil {
341 return err
342 }
343 }
344 return nil
345 }
346
347 // mapLitExpr type checks an map composite literal expression.
348 func (check typecheck) mapLitExpr(child []*node, ktyp, vtyp *itype) error {
349 visited := make(map[interface{}]bool, len(child))
350 for _, c := range child {
351 if c.kind != keyValueExpr {
352 return c.cfgErrorf("missing key in map literal")
353 }
354
355 key, val := c.child[0], c.child[1]
356 if err := check.assignment(key, ktyp, "map literal"); err != nil {
357 return err
358 }
359
360 if key.rval.IsValid() {
361 kval := key.rval.Interface()
362 if visited[kval] {
363 return c.cfgErrorf("duplicate key %s in map literal", kval)
364 }
365 visited[kval] = true
366 }
367
368 if err := check.assignment(val, vtyp, "map literal"); err != nil {
369 return err
370 }
371 }
372 return nil
373 }
374
375 // structLitExpr type checks a struct composite literal expression.
376 func (check typecheck) structLitExpr(child []*node, typ *itype) error {
377 if len(child) == 0 {
378 return nil
379 }
380
381 if child[0].kind == keyValueExpr {
382 // All children must be keyValueExpr
383 visited := make([]bool, len(typ.field))
384 for _, c := range child {
385 if c.kind != keyValueExpr {
386 return c.cfgErrorf("mixture of field:value and value elements in struct literal")
387 }
388
389 key, val := c.child[0], c.child[1]
390 name := key.ident
391 if name == "" {
392 return c.cfgErrorf("invalid field name %s in struct literal", key.typ.id())
393 }
394 i := typ.fieldIndex(name)
395 if i < 0 {
396 return c.cfgErrorf("unknown field %s in struct literal", name)
397 }
398 field := typ.field[i]
399
400 if err := check.assignment(val, field.typ, "struct literal"); err != nil {
401 return err
402 }
403
404 if visited[i] {
405 return c.cfgErrorf("duplicate field name %s in struct literal", name)
406 }
407 visited[i] = true
408 }
409 return nil
410 }
411
412 // No children can be keyValueExpr
413 for i, c := range child {
414 if c.kind == keyValueExpr {
415 return c.cfgErrorf("mixture of field:value and value elements in struct literal")
416 }
417
418 if i >= len(typ.field) {
419 return c.cfgErrorf("too many values in struct literal")
420 }
421 field := typ.field[i]
422 // TODO(nick): check if this field is not exported and in a different package.
423
424 if err := check.assignment(c, field.typ, "struct literal"); err != nil {
425 return err
426 }
427 }
428 if len(child) < len(typ.field) {
429 return child[len(child)-1].cfgErrorf("too few values in struct literal")
430 }
431 return nil
432 }
433
434 // structBinLitExpr type checks a struct composite literal expression on a binary type.
435 func (check typecheck) structBinLitExpr(child []*node, typ reflect.Type) error {
436 if len(child) == 0 {
437 return nil
438 }
439
440 if child[0].kind == keyValueExpr {
441 // All children must be keyValueExpr
442 visited := make(map[string]bool, typ.NumField())
443 for _, c := range child {
444 if c.kind != keyValueExpr {
445 return c.cfgErrorf("mixture of field:value and value elements in struct literal")
446 }
447
448 key, val := c.child[0], c.child[1]
449 name := key.ident
450 if name == "" {
451 return c.cfgErrorf("invalid field name %s in struct literal", key.typ.id())
452 }
453 field, ok := typ.FieldByName(name)
454 if !ok {
455 return c.cfgErrorf("unknown field %s in struct literal", name)
456 }
457
458 if err := check.assignment(val, valueTOf(field.Type), "struct literal"); err != nil {
459 return err
460 }
461
462 if visited[field.Name] {
463 return c.cfgErrorf("duplicate field name %s in struct literal", name)
464 }
465 visited[field.Name] = true
466 }
467 return nil
468 }
469
470 // No children can be keyValueExpr
471 for i, c := range child {
472 if c.kind == keyValueExpr {
473 return c.cfgErrorf("mixture of field:value and value elements in struct literal")
474 }
475
476 if i >= typ.NumField() {
477 return c.cfgErrorf("too many values in struct literal")
478 }
479 field := typ.Field(i)
480 if !canExport(field.Name) {
481 return c.cfgErrorf("implicit assignment to unexported field %s in %s literal", field.Name, typ)
482 }
483
484 if err := check.assignment(c, valueTOf(field.Type), "struct literal"); err != nil {
485 return err
486 }
487 }
488 if len(child) < typ.NumField() {
489 return child[len(child)-1].cfgErrorf("too few values in struct literal")
490 }
491 return nil
492 }
493
494 // sliceExpr type checks a slice expression.
495 func (check typecheck) sliceExpr(n *node) error {
496 for _, c := range n.child {
497 if isBlank(c) {
498 return n.cfgErrorf("cannot use _ as value")
499 }
500 }
501
502 c, child := n.child[0], n.child[1:]
503
504 t := c.typ.TypeOf()
505 var low, high, max *node
506 if len(child) >= 1 {
507 if n.action == aSlice {
508 low = child[0]
509 } else {
510 high = child[0]
511 }
512 }
513 if len(child) >= 2 {
514 if n.action == aSlice {
515 high = child[1]
516 } else {
517 max = child[1]
518 }
519 }
520 if len(child) == 3 && n.action == aSlice {
521 max = child[2]
522 }
523
524 l := -1
525 valid := false
526 switch t.Kind() {
527 case reflect.String:
528 valid = true
529 if c.rval.IsValid() {
530 l = len(vString(c.rval))
531 }
532 if max != nil {
533 return max.cfgErrorf("invalid operation: 3-index slice of string")
534 }
535 case reflect.Array:
536 valid = true
537 l = t.Len()
538 // TODO(marc): check addressable status of array object (i.e. composite arrays are not).
539 case reflect.Slice:
540 valid = true
541 case reflect.Ptr:
542 if t.Elem().Kind() == reflect.Array {
543 valid = true
544 l = t.Elem().Len()
545 }
546 }
547 if !valid {
548 return c.cfgErrorf("cannot slice type %s", c.typ.id())
549 }
550
551 var ind [3]int64
552 for i, nod := range []*node{low, high, max} {
553 x := int64(-1)
554 switch {
555 case nod != nil:
556 max := -1
557 if l >= 0 {
558 max = l + 1
559 }
560 if err := check.index(nod, max); err != nil {
561 return err
562 }
563 if nod.rval.IsValid() {
564 x = vInt(nod.rval)
565 }
566 case i == 0:
567 x = 0
568 case l >= 0:
569 x = int64(l)
570 }
571 ind[i] = x
572 }
573
574 for i, x := range ind[:len(ind)-1] {
575 if x <= 0 {
576 continue
577 }
578 for _, y := range ind[i+1:] {
579 if y < 0 || x <= y {
580 continue
581 }
582 return n.cfgErrorf("invalid index values, must be low <= high <= max")
583 }
584 }
585 return nil
586 }
587
588 // typeAssertionExpr type checks a type assert expression.
589 func (check typecheck) typeAssertionExpr(n *node, typ *itype) error {
590 // TODO(nick): This type check is not complete and should be revisited once
591 // https://github.com/golang/go/issues/39717 lands. It is currently impractical to
592 // type check Named types as they cannot be asserted.
593
594 if rt := n.typ.TypeOf(); rt.Kind() != reflect.Interface && rt != valueInterfaceType {
595 return n.cfgErrorf("invalid type assertion: non-interface type %s on left", n.typ.id())
596 }
597 ims := n.typ.methods()
598 if len(ims) == 0 {
599 // Empty interface must be a dynamic check.
600 return nil
601 }
602
603 if isInterface(typ) {
604 // Asserting to an interface is a dynamic check as we must look to the
605 // underlying struct.
606 return nil
607 }
608
609 for name := range ims {
610 im := lookupFieldOrMethod(n.typ, name)
611 tm := lookupFieldOrMethod(typ, name)
612 if im == nil {
613 // This should not be possible.
614 continue
615 }
616 if tm == nil {
617 // Lookup for non-exported methods is impossible
618 // for bin types, ignore them as they can't be used
619 // directly by the interpreted programs.
620 if !token.IsExported(name) && isBin(typ) {
621 continue
622 }
623 return n.cfgErrorf("impossible type assertion: %s does not implement %s (missing %v method)", typ.id(), n.typ.id(), name)
624 }
625 if tm.recv != nil && tm.recv.TypeOf().Kind() == reflect.Ptr && typ.TypeOf().Kind() != reflect.Ptr {
626 return n.cfgErrorf("impossible type assertion: %s does not implement %s as %q method has a pointer receiver", typ.id(), n.typ.id(), name)
627 }
628
629 if im.cat != funcT || tm.cat != funcT {
630 // It only makes sense to compare in/out parameter types if both types are functions.
631 continue
632 }
633
634 err := n.cfgErrorf("impossible type assertion: %s does not implement %s", typ.id(), n.typ.id())
635 if im.numIn() != tm.numIn() || im.numOut() != tm.numOut() {
636 return err
637 }
638 for i := 0; i < im.numIn(); i++ {
639 if !im.in(i).equals(tm.in(i)) {
640 return err
641 }
642 }
643 for i := 0; i < im.numOut(); i++ {
644 if !im.out(i).equals(tm.out(i)) {
645 return err
646 }
647 }
648 }
649 return nil
650 }
651
652 // conversion type checks the conversion of n to typ.
653 func (check typecheck) conversion(n *node, typ *itype) error {
654 var c constant.Value
655 if n.rval.IsValid() {
656 if con, ok := n.rval.Interface().(constant.Value); ok {
657 c = con
658 }
659 }
660
661 var ok bool
662 switch {
663 case c != nil && isConstType(typ):
664 switch t := typ.TypeOf(); {
665 case representableConst(c, t):
666 ok = true
667 case isInt(n.typ.TypeOf()) && isString(t):
668 codepoint := int64(-1)
669 if i, ok := constant.Int64Val(c); ok {
670 codepoint = i
671 }
672 n.rval = reflect.ValueOf(constant.MakeString(string(rune(codepoint))))
673 ok = true
674 }
675
676 case n.typ.convertibleTo(typ):
677 ok = true
678 }
679 if !ok {
680 return n.cfgErrorf("cannot convert expression of type %s to type %s", n.typ.id(), typ.id())
681 }
682 if !n.typ.untyped || c == nil {
683 return nil
684 }
685 if isInterface(typ) || !isConstType(typ) {
686 typ = n.typ.defaultType(n.rval, check.scope)
687 }
688 return check.convertUntyped(n, typ)
689 }
690
691 type param struct {
692 nod *node
693 typ *itype
694 }
695
696 func (p param) Type() *itype {
697 if p.typ != nil {
698 return p.typ
699 }
700 return p.nod.typ
701 }
702
703 // unpackParams unpacks child parameters into a slice of param.
704 // If there is only 1 child and it is a callExpr with an n-value return,
705 // the return types are returned, otherwise the original child nodes are
706 // returned with nil typ.
707 func (check typecheck) unpackParams(child []*node) (params []param) {
708 if len(child) == 1 && isCall(child[0]) && child[0].child[0].typ.numOut() > 1 {
709 c0 := child[0]
710 ftyp := child[0].child[0].typ
711 for i := 0; i < ftyp.numOut(); i++ {
712 params = append(params, param{nod: c0, typ: ftyp.out(i)})
713 }
714 return params
715 }
716
717 for _, c := range child {
718 params = append(params, param{nod: c})
719 }
720 return params
721 }
722
723 var builtinFuncs = map[string]struct {
724 args int
725 variadic bool
726 }{
727 bltnAlignof: {args: 1, variadic: false},
728 bltnAppend: {args: 1, variadic: true},
729 bltnCap: {args: 1, variadic: false},
730 bltnClose: {args: 1, variadic: false},
731 bltnComplex: {args: 2, variadic: false},
732 bltnImag: {args: 1, variadic: false},
733 bltnCopy: {args: 2, variadic: false},
734 bltnDelete: {args: 2, variadic: false},
735 bltnLen: {args: 1, variadic: false},
736 bltnMake: {args: 1, variadic: true},
737 bltnNew: {args: 1, variadic: false},
738 bltnOffsetof: {args: 1, variadic: false},
739 bltnPanic: {args: 1, variadic: false},
740 bltnPrint: {args: 0, variadic: true},
741 bltnPrintln: {args: 0, variadic: true},
742 bltnReal: {args: 1, variadic: false},
743 bltnRecover: {args: 0, variadic: false},
744 bltnSizeof: {args: 1, variadic: false},
745 }
746
747 func (check typecheck) builtin(name string, n *node, child []*node, ellipsis bool) error {
748 fun := builtinFuncs[name]
749 if ellipsis && name != bltnAppend {
750 return n.cfgErrorf("invalid use of ... with builtin %s", name)
751 }
752
753 var params []param
754 nparams := len(child)
755 switch name {
756 case bltnMake, bltnNew:
757 // Special param handling
758 default:
759 params = check.unpackParams(child)
760 nparams = len(params)
761 }
762
763 if nparams < fun.args {
764 return n.cfgErrorf("not enough arguments in call to %s", name)
765 } else if !fun.variadic && nparams > fun.args {
766 return n.cfgErrorf("too many arguments for %s", name)
767 }
768
769 switch name {
770 case bltnAppend:
771 typ := params[0].Type()
772 t := typ.TypeOf()
773 if t == nil || t.Kind() != reflect.Slice {
774 return params[0].nod.cfgErrorf("first argument to append must be slice; have %s", typ.id())
775 }
776
777 if nparams == 1 {
778 return nil
779 }
780 // Special case append([]byte, "test"...) is allowed.
781 t1 := params[1].Type()
782 if nparams == 2 && ellipsis && t.Elem().Kind() == reflect.Uint8 && t1.TypeOf().Kind() == reflect.String {
783 if t1.untyped {
784 return check.convertUntyped(params[1].nod, check.scope.getType("string"))
785 }
786 return nil
787 }
788
789 fun := &node{
790 typ: &itype{
791 cat: funcT,
792 arg: []*itype{
793 typ,
794 {cat: variadicT, val: valueTOf(t.Elem())},
795 },
796 ret: []*itype{typ},
797 },
798 ident: "append",
799 }
800 return check.arguments(n, child, fun, ellipsis)
801 case bltnCap, bltnLen:
802 typ := arrayDeref(params[0].Type())
803 ok := false
804 switch typ.TypeOf().Kind() {
805 case reflect.Array, reflect.Slice, reflect.Chan:
806 ok = true
807 case reflect.String, reflect.Map:
808 ok = name == bltnLen
809 }
810 if !ok {
811 return params[0].nod.cfgErrorf("invalid argument for %s", name)
812 }
813 case bltnClose:
814 p := params[0]
815 typ := p.Type()
816 t := typ.TypeOf()
817 if t.Kind() != reflect.Chan {
818 return p.nod.cfgErrorf("invalid operation: non-chan type %s", p.nod.typ.id())
819 }
820 if t.ChanDir() == reflect.RecvDir {
821 return p.nod.cfgErrorf("invalid operation: cannot close receive-only channel")
822 }
823 case bltnComplex:
824 var err error
825 p0, p1 := params[0], params[1]
826 typ0, typ1 := p0.Type(), p1.Type()
827 switch {
828 case typ0.untyped && !typ1.untyped:
829 err = check.convertUntyped(p0.nod, typ1)
830 case !typ0.untyped && typ1.untyped:
831 err = check.convertUntyped(p1.nod, typ0)
832 case typ0.untyped && typ1.untyped:
833 fltType := untypedFloat(nil)
834 err = check.convertUntyped(p0.nod, fltType)
835 if err != nil {
836 break
837 }
838 err = check.convertUntyped(p1.nod, fltType)
839 }
840 if err != nil {
841 return err
842 }
843
844 // check we have the correct types after conversion.
845 typ0, typ1 = p0.Type(), p1.Type()
846 if !typ0.equals(typ1) {
847 return n.cfgErrorf("invalid operation: mismatched types %s and %s", typ0.id(), typ1.id())
848 }
849 if !isFloat(typ0.TypeOf()) {
850 return n.cfgErrorf("invalid operation: arguments have type %s, expected floating-point", typ0.id())
851 }
852 case bltnImag, bltnReal:
853 p := params[0]
854 typ := p.Type()
855 if typ.untyped {
856 if err := check.convertUntyped(p.nod, untypedComplex(nil)); err != nil {
857 return err
858 }
859 }
860 typ = p.Type()
861 if !isComplex(typ.TypeOf()) {
862 return p.nod.cfgErrorf("invalid argument type %s for %s", typ.id(), name)
863 }
864 case bltnCopy:
865 typ0, typ1 := params[0].Type(), params[1].Type()
866 var t0, t1 reflect.Type
867 if t := typ0.TypeOf(); t.Kind() == reflect.Slice {
868 t0 = t.Elem()
869 }
870
871 switch t := typ1.TypeOf(); t.Kind() {
872 case reflect.String:
873 t1 = reflect.TypeOf(byte(1))
874 case reflect.Slice:
875 t1 = t.Elem()
876 }
877
878 if t0 == nil || t1 == nil {
879 return n.cfgErrorf("copy expects slice arguments")
880 }
881 if !reflect.DeepEqual(t0, t1) {
882 return n.cfgErrorf("arguments to copy have different element types %s and %s", typ0.id(), typ1.id())
883 }
884 case bltnDelete:
885 typ := params[0].Type()
886 if typ.TypeOf().Kind() != reflect.Map {
887 return params[0].nod.cfgErrorf("first argument to delete must be map; have %s", typ.id())
888 }
889 ktyp := params[1].Type()
890 if typ.key != nil && !ktyp.assignableTo(typ.key) {
891 return params[1].nod.cfgErrorf("cannot use %s as type %s in delete", ktyp.id(), typ.key.id())
892 }
893 case bltnMake:
894 var min int
895 switch child[0].typ.TypeOf().Kind() {
896 case reflect.Slice:
897 min = 2
898 case reflect.Map, reflect.Chan:
899 min = 1
900 default:
901 return child[0].cfgErrorf("cannot make %s; type must be slice, map, or channel", child[0].typ.id())
902 }
903 if nparams < min {
904 return n.cfgErrorf("not enough arguments in call to make")
905 } else if nparams > min+1 {
906 return n.cfgErrorf("too many arguments for make")
907 }
908
909 var sizes []int
910 for _, c := range child[1:] {
911 if err := check.index(c, -1); err != nil {
912 return err
913 }
914 if c.rval.IsValid() {
915 sizes = append(sizes, int(vInt(c.rval)))
916 }
917 }
918 for len(sizes) == 2 && sizes[0] > sizes[1] {
919 return n.cfgErrorf("len larger than cap in make")
920 }
921
922 case bltnPanic:
923 return check.assignment(params[0].nod, check.scope.getType("interface{}"), "argument to panic")
924 case bltnPrint, bltnPrintln:
925 for _, param := range params {
926 if param.typ != nil {
927 continue
928 }
929
930 if err := check.assignment(param.nod, nil, "argument to "+name); err != nil {
931 return err
932 }
933 }
934 case bltnRecover, bltnNew, bltnAlignof, bltnOffsetof, bltnSizeof:
935 // Nothing to do.
936 default:
937 return n.cfgErrorf("unsupported builtin %s", name)
938 }
939 return nil
940 }
941
942 // arrayDeref returns A if typ is *A, otherwise typ.
943 func arrayDeref(typ *itype) *itype {
944 if typ.cat == valueT && typ.TypeOf().Kind() == reflect.Ptr {
945 t := typ.TypeOf()
946 if t.Elem().Kind() == reflect.Array {
947 return valueTOf(t.Elem())
948 }
949 return typ
950 }
951
952 if typ.cat == ptrT && typ.val.cat == arrayT {
953 return typ.val
954 }
955 return typ
956 }
957
958 // arguments type checks the call expression arguments.
959 func (check typecheck) arguments(n *node, child []*node, fun *node, ellipsis bool) error {
960 params := check.unpackParams(child)
961 l := len(child)
962 if ellipsis {
963 if !fun.typ.isVariadic() {
964 return n.cfgErrorf("invalid use of ..., corresponding parameter is non-variadic")
965 }
966 if len(params) > l {
967 return child[0].cfgErrorf("cannot use ... with %d-valued %s", child[0].child[0].typ.numOut(), child[0].child[0].typ.id())
968 }
969 }
970
971 var cnt int
972 for i, param := range params {
973 ellip := i == l-1 && ellipsis
974 if err := check.argument(param, fun.typ, cnt, l, ellip); err != nil {
975 return err
976 }
977 cnt++
978 }
979
980 if fun.typ.isVariadic() {
981 cnt++
982 }
983 if cnt < fun.typ.numIn() {
984 return n.cfgErrorf("not enough arguments in call to %s", fun.name())
985 }
986 return nil
987 }
988
989 func (check typecheck) argument(p param, ftyp *itype, i, l int, ellipsis bool) error {
990 atyp := getArg(ftyp, i)
991 if atyp == nil {
992 return p.nod.cfgErrorf("too many arguments")
993 }
994
995 if p.typ == nil && isCall(p.nod) && p.nod.child[0].typ.numOut() != 1 {
996 if l == 1 {
997 return p.nod.cfgErrorf("cannot use %s as type %s", p.nod.child[0].typ.id(), getArgsID(ftyp))
998 }
999 return p.nod.cfgErrorf("cannot use %s as type %s", p.nod.child[0].typ.id(), atyp.id())
1000 }
1001
1002 if ellipsis {
1003 if i != ftyp.numIn()-1 {
1004 return p.nod.cfgErrorf("can only use ... with matching parameter")
1005 }
1006 t := p.Type().TypeOf()
1007 if t.Kind() != reflect.Slice || !(valueTOf(t.Elem())).assignableTo(atyp) {
1008 return p.nod.cfgErrorf("cannot use %s as type %s", p.nod.typ.id(), (sliceOf(atyp)).id())
1009 }
1010 return nil
1011 }
1012
1013 if p.typ != nil {
1014 if !p.typ.assignableTo(atyp) {
1015 return p.nod.cfgErrorf("cannot use %s as type %s", p.nod.child[0].typ.id(), getArgsID(ftyp))
1016 }
1017 return nil
1018 }
1019 return check.assignment(p.nod, atyp, "")
1020 }
1021
1022 func getArg(ftyp *itype, i int) *itype {
1023 l := ftyp.numIn()
1024 switch {
1025 case ftyp.isVariadic() && i >= l-1:
1026 arg := ftyp.in(l - 1).val
1027 return arg
1028 case i < l:
1029 return ftyp.in(i)
1030 case ftyp.cat == valueT && i < ftyp.rtype.NumIn():
1031 return valueTOf(ftyp.rtype.In(i))
1032 default:
1033 return nil
1034 }
1035 }
1036
1037 func getArgsID(ftyp *itype) string {
1038 res := "("
1039 for i, arg := range ftyp.arg {
1040 if i > 0 {
1041 res += ","
1042 }
1043 res += arg.id()
1044 }
1045 res += ")"
1046 return res
1047 }
1048
1049 var errCantConvert = errors.New("cannot convert")
1050
1051 func (check typecheck) convertUntyped(n *node, typ *itype) error {
1052 if n.typ == nil || !n.typ.untyped || typ == nil {
1053 return nil
1054 }
1055
1056 convErr := n.cfgErrorf("cannot convert %s to %s", n.typ.id(), typ.id())
1057
1058 ntyp, ttyp := n.typ.TypeOf(), typ.TypeOf()
1059 if typ.untyped {
1060 // Both n and target are untyped.
1061 nkind, tkind := ntyp.Kind(), ttyp.Kind()
1062 if isNumber(ntyp) && isNumber(ttyp) {
1063 if nkind <= tkind {
1064 n.typ = typ
1065 }
1066 } else if nkind != tkind {
1067 return convErr
1068 }
1069 return nil
1070 }
1071
1072 var (
1073 ityp *itype
1074 rtyp reflect.Type
1075 err error
1076 )
1077 switch {
1078 case typ.isNil() && n.typ.isNil():
1079 n.typ = typ
1080 return nil
1081 case isNumber(ttyp) || isString(ttyp) || isBoolean(ttyp):
1082 ityp = typ
1083 rtyp = ttyp
1084 case isInterface(typ):
1085 if n.typ.isNil() {
1086 return nil
1087 }
1088 if len(n.typ.methods()) > 0 { // untyped cannot be set to iface
1089 return convErr
1090 }
1091 ityp = n.typ.defaultType(n.rval, check.scope)
1092 rtyp = ntyp
1093 case isArray(typ) || isMap(typ) || isChan(typ) || isFunc(typ) || isPtr(typ):
1094 // TODO(nick): above we are acting on itype, but really it is an rtype check. This is not clear which type
1095 // plain we are in. Fix this later.
1096 if !n.typ.isNil() {
1097 return convErr
1098 }
1099 return nil
1100 case n.typ.isNil() && typ.id() == "unsafe.Pointer":
1101 n.typ = typ
1102 return nil
1103 default:
1104 return convErr
1105 }
1106
1107 if err := check.representable(n, rtyp); err != nil {
1108 return err
1109 }
1110 n.rval, err = check.convertConst(n.rval, rtyp)
1111 if err != nil {
1112 if errors.Is(err, errCantConvert) {
1113 return convErr
1114 }
1115 return n.cfgErrorf(err.Error())
1116 }
1117 n.typ = ityp
1118 return nil
1119 }
1120
1121 func (check typecheck) representable(n *node, t reflect.Type) error {
1122 if !n.rval.IsValid() {
1123 // TODO(nick): This should be an error as the const is in the frame which is undesirable.
1124 return nil
1125 }
1126 c, ok := n.rval.Interface().(constant.Value)
1127 if !ok {
1128 // TODO(nick): This should be an error as untyped strings and bools should be constant.Values.
1129 return nil
1130 }
1131
1132 if !representableConst(c, t) {
1133 typ := n.typ.TypeOf()
1134 if isNumber(typ) && isNumber(t) {
1135 // numeric conversion : error msg
1136 //
1137 // integer -> integer : overflows
1138 // integer -> float : overflows (actually not possible)
1139 // float -> integer : truncated
1140 // float -> float : overflows
1141 //
1142 if !isInt(typ) && isInt(t) {
1143 return n.cfgErrorf("%s truncated to %s", c.ExactString(), t.Kind().String())
1144 }
1145 return n.cfgErrorf("%s overflows %s", c.ExactString(), t.Kind().String())
1146 }
1147 return n.cfgErrorf("cannot convert %s to %s", c.ExactString(), t.Kind().String())
1148 }
1149 return nil
1150 }
1151
1152 func (check typecheck) convertConst(v reflect.Value, t reflect.Type) (reflect.Value, error) {
1153 if !v.IsValid() {
1154 // TODO(nick): This should be an error as the const is in the frame which is undesirable.
1155 return v, nil
1156 }
1157 c, ok := v.Interface().(constant.Value)
1158 if !ok {
1159 // TODO(nick): This should be an error as untyped strings and bools should be constant.Values.
1160 return v, nil
1161 }
1162
1163 kind := t.Kind()
1164 switch kind {
1165 case reflect.Bool:
1166 v = reflect.ValueOf(constant.BoolVal(c))
1167 case reflect.String:
1168 v = reflect.ValueOf(constant.StringVal(c))
1169 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1170 i, _ := constant.Int64Val(constant.ToInt(c))
1171 v = reflect.ValueOf(i).Convert(t)
1172 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1173 i, _ := constant.Uint64Val(constant.ToInt(c))
1174 v = reflect.ValueOf(i).Convert(t)
1175 case reflect.Float32:
1176 f, _ := constant.Float32Val(constant.ToFloat(c))
1177 v = reflect.ValueOf(f)
1178 case reflect.Float64:
1179 f, _ := constant.Float64Val(constant.ToFloat(c))
1180 v = reflect.ValueOf(f)
1181 case reflect.Complex64:
1182 r, _ := constant.Float32Val(constant.Real(c))
1183 i, _ := constant.Float32Val(constant.Imag(c))
1184 v = reflect.ValueOf(complex(r, i)).Convert(t)
1185 case reflect.Complex128:
1186 r, _ := constant.Float64Val(constant.Real(c))
1187 i, _ := constant.Float64Val(constant.Imag(c))
1188 v = reflect.ValueOf(complex(r, i)).Convert(t)
1189 default:
1190 return v, errCantConvert
1191 }
1192 return v, nil
1193 }
1194
1195 var bitlen = [...]int{
1196 reflect.Int: 64,
1197 reflect.Int8: 8,
1198 reflect.Int16: 16,
1199 reflect.Int32: 32,
1200 reflect.Int64: 64,
1201 reflect.Uint: 64,
1202 reflect.Uint8: 8,
1203 reflect.Uint16: 16,
1204 reflect.Uint32: 32,
1205 reflect.Uint64: 64,
1206 reflect.Uintptr: 64,
1207 }
1208
1209 func representableConst(c constant.Value, t reflect.Type) bool {
1210 switch {
1211 case isInt(t):
1212 x := constant.ToInt(c)
1213 if x.Kind() != constant.Int {
1214 return false
1215 }
1216 switch t.Kind() {
1217 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1218 if _, ok := constant.Int64Val(x); !ok {
1219 return false
1220 }
1221 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1222 if _, ok := constant.Uint64Val(x); !ok {
1223 return false
1224 }
1225 default:
1226 return false
1227 }
1228 return constant.BitLen(x) <= bitlen[t.Kind()]
1229 case isFloat(t):
1230 x := constant.ToFloat(c)
1231 if x.Kind() != constant.Float {
1232 return false
1233 }
1234 switch t.Kind() {
1235 case reflect.Float32:
1236 f, _ := constant.Float32Val(x)
1237 return !math.IsInf(float64(f), 0)
1238 case reflect.Float64:
1239 f, _ := constant.Float64Val(x)
1240 return !math.IsInf(f, 0)
1241 default:
1242 return false
1243 }
1244 case isComplex(t):
1245 x := constant.ToComplex(c)
1246 if x.Kind() != constant.Complex {
1247 return false
1248 }
1249 switch t.Kind() {
1250 case reflect.Complex64:
1251 r, _ := constant.Float32Val(constant.Real(x))
1252 i, _ := constant.Float32Val(constant.Imag(x))
1253 return !math.IsInf(float64(r), 0) && !math.IsInf(float64(i), 0)
1254 case reflect.Complex128:
1255 r, _ := constant.Float64Val(constant.Real(x))
1256 i, _ := constant.Float64Val(constant.Imag(x))
1257 return !math.IsInf(r, 0) && !math.IsInf(i, 0)
1258 default:
1259 return false
1260 }
1261 case isString(t):
1262 return c.Kind() == constant.String
1263 case isBoolean(t):
1264 return c.Kind() == constant.Bool
1265 default:
1266 return false
1267 }
1268 }
1269
1270 func isShiftAction(a action) bool {
1271 switch a {
1272 case aShl, aShr, aShlAssign, aShrAssign:
1273 return true
1274 }
1275 return false
1276 }
1277
1278 func isComparisonAction(a action) bool {
1279 switch a {
1280 case aEqual, aNotEqual, aGreater, aGreaterEqual, aLower, aLowerEqual:
1281 return true
1282 }
1283 return false
1284 }