diff --git a/_test/new0.go b/_test/new0.go new file mode 100644 index 00000000..f7265682 --- /dev/null +++ b/_test/new0.go @@ -0,0 +1,10 @@ +package main + +func main() { + a := new(int) + *a = 3 + println(*a) +} + +// Output: +// 3 diff --git a/interp/cfg.go b/interp/cfg.go index 4134316d..0e4e973c 100644 --- a/interp/cfg.go +++ b/interp/cfg.go @@ -540,6 +540,9 @@ func (interp *Interpreter) Cfg(root *Node) ([]*Node, error) { } n.child[1].val = n.typ n.child[1].kind = BasicLit + case "new": + n.typ, err = nodeType(interp, scope, n.child[1]) + n.typ = &Type{cat: PtrT, val: n.typ} case "recover": n.typ = scope.getType("interface{}") } diff --git a/interp/interp.go b/interp/interp.go index df79ffba..12bbb86a 100644 --- a/interp/interp.go +++ b/interp/interp.go @@ -156,6 +156,7 @@ func initUniverse() *Scope { "close": &Symbol{kind: Bltn, builtin: _close}, "len": &Symbol{kind: Bltn, builtin: _len}, "make": &Symbol{kind: Bltn, builtin: _make}, + "new": &Symbol{kind: Bltn, builtin: _new}, "panic": &Symbol{kind: Bltn, builtin: _panic}, "println": &Symbol{kind: Bltn, builtin: _println}, "recover": &Symbol{kind: Bltn, builtin: _recover}, diff --git a/interp/interp_test.go b/interp/interp_test.go index 24ff0995..d8bfdcdc 100644 --- a/interp/interp_test.go +++ b/interp/interp_test.go @@ -3909,6 +3909,27 @@ func main() { // -1 } +func Example_new0() { + src := ` +package main + +func main() { + a := new(int) + *a = 3 + println(*a) +} +` + i := interp.New(interp.Opt{Entry: "main"}) + i.Use(stdlib.Value) + _, err := i.Eval(src) + if err != nil { + panic(err) + } + + // Output: + // 3 +} + func Example_op0() { src := ` package main diff --git a/interp/run.go b/interp/run.go index c2088e25..b0a94dda 100644 --- a/interp/run.go +++ b/interp/run.go @@ -1321,6 +1321,17 @@ func _len(n *Node) { } } +func _new(n *Node) { + i := n.findex + next := getExec(n.tnext) + typ := n.child[1].typ.TypeOf() + + n.exec = func(f *Frame) Builtin { + f.data[i] = reflect.New(typ) + return next + } +} + // _make allocates and initializes a slice, a map or a chan. func _make(n *Node) { i := n.findex