2021-12-28 20:18:01 +00:00
|
|
|
package vm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2023-10-28 07:53:37 +00:00
|
|
|
"code.betamike.com/mediocregopher/ginger/gg"
|
2021-12-28 20:18:01 +00:00
|
|
|
)
|
|
|
|
|
2023-10-16 15:15:51 +00:00
|
|
|
func globalFn(fn func(Value) (Value, error)) Value {
|
2022-03-31 15:18:02 +00:00
|
|
|
return Value{
|
2023-10-16 15:15:51 +00:00
|
|
|
Function: FunctionFunc(func(in Value) Value {
|
2022-03-31 15:18:02 +00:00
|
|
|
res, err := fn(in)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-28 20:18:01 +00:00
|
|
|
// GlobalScope contains operations and values which are available from within
|
|
|
|
// any operation in a ginger program.
|
|
|
|
var GlobalScope = ScopeMap{
|
|
|
|
|
2023-10-29 20:42:41 +00:00
|
|
|
"!add": globalFn(func(val Value) (Value, error) {
|
2021-12-28 20:18:01 +00:00
|
|
|
|
|
|
|
var sum int64
|
|
|
|
|
|
|
|
for _, tupVal := range val.Tuple {
|
|
|
|
|
|
|
|
if tupVal.Number == nil {
|
|
|
|
return Value{}, fmt.Errorf("add requires a non-zero tuple of numbers as an argument")
|
|
|
|
}
|
|
|
|
|
|
|
|
sum += *tupVal.Number
|
|
|
|
}
|
|
|
|
|
|
|
|
return Value{Value: gg.Value{Number: &sum}}, nil
|
|
|
|
|
2022-03-31 15:18:02 +00:00
|
|
|
}),
|
2021-12-30 22:10:25 +00:00
|
|
|
|
2023-10-29 20:42:41 +00:00
|
|
|
"!tupEl": globalFn(func(val Value) (Value, error) {
|
2021-12-30 22:10:25 +00:00
|
|
|
|
|
|
|
tup, i := val.Tuple[0], val.Tuple[1]
|
|
|
|
|
|
|
|
return tup.Tuple[int(*i.Number)], nil
|
|
|
|
|
2022-03-31 15:18:02 +00:00
|
|
|
}),
|
2021-12-30 22:10:25 +00:00
|
|
|
|
2023-10-29 20:42:41 +00:00
|
|
|
"!isZero": globalFn(func(val Value) (Value, error) {
|
2021-12-30 22:10:25 +00:00
|
|
|
|
|
|
|
if *val.Number == 0 {
|
|
|
|
one := int64(1)
|
|
|
|
return Value{Value: gg.Value{Number: &one}}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
zero := int64(0)
|
|
|
|
return Value{Value: gg.Value{Number: &zero}}, nil
|
|
|
|
|
2022-03-31 15:18:02 +00:00
|
|
|
}),
|
2021-12-28 20:18:01 +00:00
|
|
|
}
|