feat: add support for builtin new (#125)
This commit is contained in:
committed by
Ludovic Fernandez
parent
6a546062c1
commit
a1bfe7c989
10
_test/new0.go
Normal file
10
_test/new0.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
a := new(int)
|
||||
*a = 3
|
||||
println(*a)
|
||||
}
|
||||
|
||||
// Output:
|
||||
// 3
|
||||
@@ -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{}")
|
||||
}
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user