1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 "golang.org/x/tools/go/ssa"
22 // If the target program panics, the interpreter panics with this type.
23 type targetPanic struct {
27 func (p targetPanic) String() string {
31 // If the target program calls exit, the interpreter panics with this type.
34 // constValue returns the value of the constant with the
35 // dynamic type tag appropriate for c.Type().
36 func constValue(c *ssa.Const) value {
38 return zero(c.Type()) // typed nil
41 if t, ok := c.Type().Underlying().(*types.Basic); ok {
42 // TODO(adonovan): eliminate untyped constants from SSA form.
44 case types.Bool, types.UntypedBool:
45 return constant.BoolVal(c.Value)
46 case types.Int, types.UntypedInt:
47 // Assume sizeof(int) is same on host and target.
50 return int8(c.Int64())
52 return int16(c.Int64())
53 case types.Int32, types.UntypedRune:
54 return int32(c.Int64())
58 // Assume sizeof(uint) is same on host and target.
59 return uint(c.Uint64())
61 return uint8(c.Uint64())
63 return uint16(c.Uint64())
65 return uint32(c.Uint64())
69 // Assume sizeof(uintptr) is same on host and target.
70 return uintptr(c.Uint64())
72 return float32(c.Float64())
73 case types.Float64, types.UntypedFloat:
76 return complex64(c.Complex128())
77 case types.Complex128, types.UntypedComplex:
79 case types.String, types.UntypedString:
80 if c.Value.Kind() == constant.String {
81 return constant.StringVal(c.Value)
83 return string(rune(c.Int64()))
87 panic(fmt.Sprintf("constValue: %s", c))
90 // asInt converts x, which must be an integer, to an int suitable for
91 // use as a slice or array index or operand to make().
92 func asInt(x value) int {
93 switch x := x.(type) {
117 panic(fmt.Sprintf("cannot convert %T to int", x))
120 // asUint64 converts x, which must be an unsigned integer, to a uint64
121 // suitable for use as a bitwise shift count.
122 func asUint64(x value) uint64 {
123 switch x := x.(type) {
137 panic(fmt.Sprintf("cannot convert %T to uint64", x))
140 // zero returns a new "zero" value of the specified type.
141 func zero(t types.Type) value {
142 switch t := t.(type) {
144 if t.Kind() == types.UntypedNil {
145 panic("untyped nil has no zero value")
147 if t.Info()&types.IsUntyped != 0 {
148 // TODO(adonovan): make it an invariant that
149 // this is unreachable. Currently some
150 // constants have 'untyped' types when they
151 // should be defaulted by the typechecker.
152 t = types.Default(t).(*types.Basic)
183 case types.Complex64:
185 case types.Complex128:
189 case types.UnsafePointer:
190 return unsafe.Pointer(nil)
192 panic(fmt.Sprint("zero for unexpected type:", t))
197 a := make(array, t.Len())
199 a[i] = zero(t.Elem())
203 return zero(t.Underlying())
204 case *types.Interface:
205 return iface{} // nil type, methodset and value
209 s := make(structure, t.NumFields())
211 s[i] = zero(t.Field(i).Type())
216 return zero(t.At(0).Type())
218 s := make(tuple, t.Len())
220 s[i] = zero(t.At(i).Type())
224 return chan value(nil)
226 if usesBuiltinMap(t.Key()) {
227 return map[value]value(nil)
229 return (*hashmap)(nil)
230 case *types.Signature:
231 return (*ssa.Function)(nil)
233 panic(fmt.Sprint("zero: unexpected ", t))
236 // slice returns x[lo:hi:max]. Any of lo, hi and max may be nil.
237 func slice(x, lo, hi, max value) value {
239 switch x := x.(type) {
245 case *value: // *array
266 switch x := x.(type) {
271 case *value: // *array
273 return []value(a)[l:h:m]
275 panic(fmt.Sprintf("slice: unexpected X type: %T", x))
278 // lookup returns x[idx] where x is a map or string.
279 func lookup(instr *ssa.Lookup, x, idx value) value {
280 switch x := x.(type) { // map or string
281 case map[value]value, *hashmap:
284 switch x := x.(type) {
285 case map[value]value:
288 v = x.lookup(idx.(hashable))
292 v = zero(instr.X.Type().Underlying().(*types.Map).Elem())
301 panic(fmt.Sprintf("unexpected x type in Lookup: %T", x))
304 // binop implements all arithmetic and logical binary operators for
305 // numeric datatypes and strings. Both operands must have identical
308 func binop(op token.Token, t types.Type, x, y value) value {
313 return x.(int) + y.(int)
315 return x.(int8) + y.(int8)
317 return x.(int16) + y.(int16)
319 return x.(int32) + y.(int32)
321 return x.(int64) + y.(int64)
323 return x.(uint) + y.(uint)
325 return x.(uint8) + y.(uint8)
327 return x.(uint16) + y.(uint16)
329 return x.(uint32) + y.(uint32)
331 return x.(uint64) + y.(uint64)
333 return x.(uintptr) + y.(uintptr)
335 return x.(float32) + y.(float32)
337 return x.(float64) + y.(float64)
339 return x.(complex64) + y.(complex64)
341 return x.(complex128) + y.(complex128)
343 return x.(string) + y.(string)
349 return x.(int) - y.(int)
351 return x.(int8) - y.(int8)
353 return x.(int16) - y.(int16)
355 return x.(int32) - y.(int32)
357 return x.(int64) - y.(int64)
359 return x.(uint) - y.(uint)
361 return x.(uint8) - y.(uint8)
363 return x.(uint16) - y.(uint16)
365 return x.(uint32) - y.(uint32)
367 return x.(uint64) - y.(uint64)
369 return x.(uintptr) - y.(uintptr)
371 return x.(float32) - y.(float32)
373 return x.(float64) - y.(float64)
375 return x.(complex64) - y.(complex64)
377 return x.(complex128) - y.(complex128)
383 return x.(int) * y.(int)
385 return x.(int8) * y.(int8)
387 return x.(int16) * y.(int16)
389 return x.(int32) * y.(int32)
391 return x.(int64) * y.(int64)
393 return x.(uint) * y.(uint)
395 return x.(uint8) * y.(uint8)
397 return x.(uint16) * y.(uint16)
399 return x.(uint32) * y.(uint32)
401 return x.(uint64) * y.(uint64)
403 return x.(uintptr) * y.(uintptr)
405 return x.(float32) * y.(float32)
407 return x.(float64) * y.(float64)
409 return x.(complex64) * y.(complex64)
411 return x.(complex128) * y.(complex128)
417 return x.(int) / y.(int)
419 return x.(int8) / y.(int8)
421 return x.(int16) / y.(int16)
423 return x.(int32) / y.(int32)
425 return x.(int64) / y.(int64)
427 return x.(uint) / y.(uint)
429 return x.(uint8) / y.(uint8)
431 return x.(uint16) / y.(uint16)
433 return x.(uint32) / y.(uint32)
435 return x.(uint64) / y.(uint64)
437 return x.(uintptr) / y.(uintptr)
439 return x.(float32) / y.(float32)
441 return x.(float64) / y.(float64)
443 return x.(complex64) / y.(complex64)
445 return x.(complex128) / y.(complex128)
451 return x.(int) % y.(int)
453 return x.(int8) % y.(int8)
455 return x.(int16) % y.(int16)
457 return x.(int32) % y.(int32)
459 return x.(int64) % y.(int64)
461 return x.(uint) % y.(uint)
463 return x.(uint8) % y.(uint8)
465 return x.(uint16) % y.(uint16)
467 return x.(uint32) % y.(uint32)
469 return x.(uint64) % y.(uint64)
471 return x.(uintptr) % y.(uintptr)
477 return x.(int) & y.(int)
479 return x.(int8) & y.(int8)
481 return x.(int16) & y.(int16)
483 return x.(int32) & y.(int32)
485 return x.(int64) & y.(int64)
487 return x.(uint) & y.(uint)
489 return x.(uint8) & y.(uint8)
491 return x.(uint16) & y.(uint16)
493 return x.(uint32) & y.(uint32)
495 return x.(uint64) & y.(uint64)
497 return x.(uintptr) & y.(uintptr)
503 return x.(int) | y.(int)
505 return x.(int8) | y.(int8)
507 return x.(int16) | y.(int16)
509 return x.(int32) | y.(int32)
511 return x.(int64) | y.(int64)
513 return x.(uint) | y.(uint)
515 return x.(uint8) | y.(uint8)
517 return x.(uint16) | y.(uint16)
519 return x.(uint32) | y.(uint32)
521 return x.(uint64) | y.(uint64)
523 return x.(uintptr) | y.(uintptr)
529 return x.(int) ^ y.(int)
531 return x.(int8) ^ y.(int8)
533 return x.(int16) ^ y.(int16)
535 return x.(int32) ^ y.(int32)
537 return x.(int64) ^ y.(int64)
539 return x.(uint) ^ y.(uint)
541 return x.(uint8) ^ y.(uint8)
543 return x.(uint16) ^ y.(uint16)
545 return x.(uint32) ^ y.(uint32)
547 return x.(uint64) ^ y.(uint64)
549 return x.(uintptr) ^ y.(uintptr)
555 return x.(int) &^ y.(int)
557 return x.(int8) &^ y.(int8)
559 return x.(int16) &^ y.(int16)
561 return x.(int32) &^ y.(int32)
563 return x.(int64) &^ y.(int64)
565 return x.(uint) &^ y.(uint)
567 return x.(uint8) &^ y.(uint8)
569 return x.(uint16) &^ y.(uint16)
571 return x.(uint32) &^ y.(uint32)
573 return x.(uint64) &^ y.(uint64)
575 return x.(uintptr) &^ y.(uintptr)
586 return x.(int16) << y
588 return x.(int32) << y
590 return x.(int64) << y
594 return x.(uint8) << y
596 return x.(uint16) << y
598 return x.(uint32) << y
600 return x.(uint64) << y
602 return x.(uintptr) << y
613 return x.(int16) >> y
615 return x.(int32) >> y
617 return x.(int64) >> y
621 return x.(uint8) >> y
623 return x.(uint16) >> y
625 return x.(uint32) >> y
627 return x.(uint64) >> y
629 return x.(uintptr) >> y
635 return x.(int) < y.(int)
637 return x.(int8) < y.(int8)
639 return x.(int16) < y.(int16)
641 return x.(int32) < y.(int32)
643 return x.(int64) < y.(int64)
645 return x.(uint) < y.(uint)
647 return x.(uint8) < y.(uint8)
649 return x.(uint16) < y.(uint16)
651 return x.(uint32) < y.(uint32)
653 return x.(uint64) < y.(uint64)
655 return x.(uintptr) < y.(uintptr)
657 return x.(float32) < y.(float32)
659 return x.(float64) < y.(float64)
661 return x.(string) < y.(string)
667 return x.(int) <= y.(int)
669 return x.(int8) <= y.(int8)
671 return x.(int16) <= y.(int16)
673 return x.(int32) <= y.(int32)
675 return x.(int64) <= y.(int64)
677 return x.(uint) <= y.(uint)
679 return x.(uint8) <= y.(uint8)
681 return x.(uint16) <= y.(uint16)
683 return x.(uint32) <= y.(uint32)
685 return x.(uint64) <= y.(uint64)
687 return x.(uintptr) <= y.(uintptr)
689 return x.(float32) <= y.(float32)
691 return x.(float64) <= y.(float64)
693 return x.(string) <= y.(string)
697 return eqnil(t, x, y)
700 return !eqnil(t, x, y)
705 return x.(int) > y.(int)
707 return x.(int8) > y.(int8)
709 return x.(int16) > y.(int16)
711 return x.(int32) > y.(int32)
713 return x.(int64) > y.(int64)
715 return x.(uint) > y.(uint)
717 return x.(uint8) > y.(uint8)
719 return x.(uint16) > y.(uint16)
721 return x.(uint32) > y.(uint32)
723 return x.(uint64) > y.(uint64)
725 return x.(uintptr) > y.(uintptr)
727 return x.(float32) > y.(float32)
729 return x.(float64) > y.(float64)
731 return x.(string) > y.(string)
737 return x.(int) >= y.(int)
739 return x.(int8) >= y.(int8)
741 return x.(int16) >= y.(int16)
743 return x.(int32) >= y.(int32)
745 return x.(int64) >= y.(int64)
747 return x.(uint) >= y.(uint)
749 return x.(uint8) >= y.(uint8)
751 return x.(uint16) >= y.(uint16)
753 return x.(uint32) >= y.(uint32)
755 return x.(uint64) >= y.(uint64)
757 return x.(uintptr) >= y.(uintptr)
759 return x.(float32) >= y.(float32)
761 return x.(float64) >= y.(float64)
763 return x.(string) >= y.(string)
766 panic(fmt.Sprintf("invalid binary op: %T %s %T", x, op, y))
769 // eqnil returns the comparison x == y using the equivalence relation
770 // appropriate for type t.
771 // If t is a reference type, at most one of x or y may be a nil value
774 func eqnil(t types.Type, x, y value) bool {
775 switch t.Underlying().(type) {
776 case *types.Map, *types.Signature, *types.Slice:
777 // Since these types don't support comparison,
778 // one of the operands must be a literal nil.
779 switch x := x.(type) {
781 return (x != nil) == (y.(*hashmap) != nil)
782 case map[value]value:
783 return (x != nil) == (y.(map[value]value) != nil)
785 switch y := y.(type) {
787 return (x != nil) == (y != nil)
792 return (x != nil) == (y.(*ssa.Function) != nil)
794 return (x != nil) == (y.([]value) != nil)
796 panic(fmt.Sprintf("eqnil(%s): illegal dynamic type: %T", t, x))
799 return equals(t, x, y)
802 func unop(instr *ssa.UnOp, x value) value {
804 case token.ARROW: // receive
805 v, ok := <-x.(chan value)
807 v = zero(instr.X.Type().Underlying().(*types.Chan).Elem())
814 switch x := x.(type) {
847 return load(deref(instr.X.Type()), x.(*value))
851 switch x := x.(type) {
876 panic(fmt.Sprintf("invalid unary op %s %T", instr.Op, x))
879 // typeAssert checks whether dynamic type of itf is instr.AssertedType.
880 // It returns the extracted value on success, and panics on failure,
881 // unless instr.CommaOk, in which case it always returns a "value,ok" tuple.
883 func typeAssert(i *interpreter, instr *ssa.TypeAssert, itf iface) value {
887 err = fmt.Sprintf("interface conversion: interface is nil, not %s", instr.AssertedType)
889 } else if idst, ok := instr.AssertedType.Underlying().(*types.Interface); ok {
891 err = checkInterface(i, idst, itf)
893 } else if types.Identical(itf.t, instr.AssertedType) {
894 v = itf.v // extract value
897 err = fmt.Sprintf("interface conversion: interface is %s, not %s", itf.t, instr.AssertedType)
904 return tuple{zero(instr.AssertedType), false}
907 return tuple{v, true}
912 // If CapturedOutput is non-nil, all writes by the interpreted program
913 // to file descriptors 1 and 2 will also be written to CapturedOutput.
915 // (The $GOROOT/test system requires that the test be considered a
916 // failure if "BUG" appears in the combined stdout/stderr output, even
917 // if it exits zero. This is a global variable shared by all
918 // interpreters in the same process.)
920 var CapturedOutput *bytes.Buffer
921 var capturedOutputMu sync.Mutex
923 // write writes bytes b to the target program's standard output.
924 // The print/println built-ins and the write() system call funnel
925 // through here so they can be captured by the test driver.
926 func print(b []byte) (int, error) {
927 if CapturedOutput != nil {
928 capturedOutputMu.Lock()
929 CapturedOutput.Write(b) // ignore errors
930 capturedOutputMu.Unlock()
932 return os.Stdout.Write(b)
935 // callBuiltin interprets a call to builtin fn with arguments args,
936 // returning its result.
937 func callBuiltin(caller *frame, callpos token.Pos, fn *ssa.Builtin, args []value) value {
943 if s, ok := args[1].(string); ok {
944 // append([]byte, ...string) []byte
945 arg0 := args[0].([]value)
946 for i := 0; i < len(s); i++ {
947 arg0 = append(arg0, s[i])
951 // append([]T, ...[]T) []T
952 return append(args[0].([]value), args[1].([]value)...)
954 case "copy": // copy([]T, []T) int or copy([]byte, string) int
956 if _, ok := src.(string); ok {
957 params := fn.Type().(*types.Signature).Params()
958 src = conv(params.At(0).Type(), params.At(1).Type(), src)
960 return copy(args[0].([]value), src.([]value))
962 case "close": // close(chan T)
963 close(args[0].(chan value))
966 case "delete": // delete(map[K]value, K)
967 switch m := args[0].(type) {
968 case map[value]value:
971 m.delete(args[1].(hashable))
973 panic(fmt.Sprintf("illegal map type: %T", m))
977 case "print", "println": // print(any, ...)
978 ln := fn.Name() == "println"
980 for i, arg := range args {
984 buf.WriteString(toString(arg))
993 switch x := args[0].(type) {
999 return len((*x).(array))
1002 case map[value]value:
1009 panic(fmt.Sprintf("len: illegal operand: %T", x))
1013 switch x := args[0].(type) {
1017 return cap((*x).(array))
1023 panic(fmt.Sprintf("cap: illegal operand: %T", x))
1027 switch c := args[0].(type) {
1033 panic(fmt.Sprintf("real: illegal operand: %T", c))
1037 switch c := args[0].(type) {
1043 panic(fmt.Sprintf("imag: illegal operand: %T", c))
1047 switch f := args[0].(type) {
1049 return complex(f, args[1].(float32))
1051 return complex(f, args[1].(float64))
1053 panic(fmt.Sprintf("complex: illegal operand: %T", f))
1057 // ssa.Panic handles most cases; this is only for "go
1058 // panic" or "defer panic".
1059 panic(targetPanic{args[0]})
1062 return doRecover(caller)
1064 case "ssa:wrapnilchk":
1066 if recv.(*value) == nil {
1068 methodName := args[2]
1069 panic(fmt.Sprintf("value method (%s).%s called using nil *%s pointer",
1070 recvType, methodName, recvType))
1075 panic("unknown built-in: " + fn.Name())
1078 func rangeIter(x value, t types.Type) iter {
1079 switch x := x.(type) {
1080 case map[value]value:
1081 return &mapIter{iter: reflect.ValueOf(x).MapRange()}
1083 return &hashmapIter{iter: reflect.ValueOf(x.entries()).MapRange()}
1085 return &stringIter{Reader: strings.NewReader(x)}
1087 panic(fmt.Sprintf("cannot range over %T", x))
1090 // widen widens a basic typed value x to the widest type of its
1091 // category, one of:
1092 // bool, int64, uint64, float64, complex128, string.
1093 // This is inefficient but reduces the size of the cross-product of
1094 // cases we have to consider.
1096 func widen(x value) value {
1097 switch y := x.(type) {
1098 case bool, int64, uint64, float64, complex128, string, unsafe.Pointer:
1121 return complex128(y)
1123 panic(fmt.Sprintf("cannot widen %T", x))
1126 // conv converts the value x of type t_src to type t_dst and returns
1128 // Possible cases are described with the ssa.Convert operator.
1130 func conv(t_dst, t_src types.Type, x value) value {
1131 ut_src := t_src.Underlying()
1132 ut_dst := t_dst.Underlying()
1134 // Destination type is not an "untyped" type.
1135 if b, ok := ut_dst.(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
1136 panic("oops: conversion to 'untyped' type: " + b.String())
1139 // Nor is it an interface type.
1140 if _, ok := ut_dst.(*types.Interface); ok {
1141 if _, ok := ut_src.(*types.Interface); ok {
1142 panic("oops: Convert should be ChangeInterface")
1144 panic("oops: Convert should be MakeInterface")
1148 // Remaining conversions:
1149 // + untyped string/number/bool constant to a specific
1151 // + conversions between non-complex numeric types.
1152 // + conversions between complex numeric types.
1153 // + integer/[]byte/[]rune -> string.
1154 // + string -> []byte/[]rune.
1156 // All are treated the same: first we extract the value to the
1157 // widest representation (int64, uint64, float64, complex128,
1158 // or string), then we convert it to the desired type.
1160 switch ut_src := ut_src.(type) {
1161 case *types.Pointer:
1162 switch ut_dst := ut_dst.(type) {
1164 // *value to unsafe.Pointer?
1165 if ut_dst.Kind() == types.UnsafePointer {
1166 return unsafe.Pointer(x.(*value))
1171 // []byte or []rune -> string
1172 // TODO(adonovan): fix: type B byte; conv([]B -> string).
1173 switch ut_src.Elem().(*types.Basic).Kind() {
1176 b := make([]byte, 0, len(x))
1178 b = append(b, x[i].(byte))
1184 r := make([]rune, 0, len(x))
1186 r = append(r, x[i].(rune))
1194 // integer -> string?
1195 // TODO(adonovan): fix: test integer -> named alias of string.
1196 if ut_src.Info()&types.IsInteger != 0 {
1197 if ut_dst, ok := ut_dst.(*types.Basic); ok && ut_dst.Kind() == types.String {
1198 return fmt.Sprintf("%c", x)
1202 // string -> []rune, []byte or string?
1203 if s, ok := x.(string); ok {
1204 switch ut_dst := ut_dst.(type) {
1207 // TODO(adonovan): fix: test named alias of rune, byte.
1208 switch ut_dst.Elem().(*types.Basic).Kind() {
1210 for _, r := range []rune(s) {
1211 res = append(res, r)
1215 for _, b := range []byte(s) {
1216 res = append(res, b)
1221 if ut_dst.Kind() == types.String {
1225 break // fail: no other conversions for string
1228 // unsafe.Pointer -> *value
1229 if ut_src.Kind() == types.UnsafePointer {
1230 // TODO(adonovan): this is wrong and cannot
1231 // really be fixed with the current design.
1233 // return (*value)(x.(unsafe.Pointer))
1234 // creates a new pointer of a different
1235 // type but the underlying interface value
1236 // knows its "true" type and so cannot be
1237 // meaningfully used through the new pointer.
1239 // To make this work, the interpreter needs to
1240 // simulate the memory layout of a real
1241 // compiled implementation.
1243 // To at least preserve type-safety, we'll
1244 // just return the zero value of the
1245 // destination type.
1249 // Conversions between complex numeric types?
1250 if ut_src.Info()&types.IsComplex != 0 {
1251 switch ut_dst.(*types.Basic).Kind() {
1252 case types.Complex64:
1253 return complex64(x.(complex128))
1254 case types.Complex128:
1255 return x.(complex128)
1257 break // fail: no other conversions for complex
1260 // Conversions between non-complex numeric types?
1261 if ut_src.Info()&types.IsNumeric != 0 {
1262 kind := ut_dst.(*types.Basic).Kind()
1263 switch x := x.(type) {
1264 case int64: // signed integer -> numeric?
1294 case uint64: // unsigned integer -> numeric?
1324 case float64: // floating point -> numeric?
1357 panic(fmt.Sprintf("unsupported conversion: %s -> %s, dynamic type %T", t_src, t_dst, x))
1360 // checkInterface checks that the method set of x implements the
1362 // On success it returns "", on failure, an error message.
1364 func checkInterface(i *interpreter, itype *types.Interface, x iface) string {
1365 if meth, _ := types.MissingMethod(x.t, itype, true); meth != nil {
1366 return fmt.Sprintf("interface conversion: %v is not %v: missing method %s",
1367 x.t, itype, meth.Name())