Add tons of builtin helpers and array operations.
This commit is contained in:
29
vm/vm.go
29
vm/vm.go
@@ -527,8 +527,29 @@ func (vm *VM) executeBinaryOperation(op code.Opcode) error {
|
||||
|
||||
switch {
|
||||
|
||||
// {"a": 1} + {"b": 2}
|
||||
case op == code.OpAdd && left.Type() == object.HASH_OBJ && right.Type() == object.HASH_OBJ:
|
||||
leftVal := left.(*object.Hash).Pairs
|
||||
rightVal := right.(*object.Hash).Pairs
|
||||
pairs := make(map[object.HashKey]object.HashPair)
|
||||
for k, v := range leftVal {
|
||||
pairs[k] = v
|
||||
}
|
||||
for k, v := range rightVal {
|
||||
pairs[k] = v
|
||||
}
|
||||
return vm.push(&object.Hash{Pairs: pairs})
|
||||
|
||||
// [1] + [2]
|
||||
case op == code.OpAdd && left.Type() == object.ARRAY_OBJ && right.Type() == object.ARRAY_OBJ:
|
||||
leftVal := left.(*object.Array).Elements
|
||||
rightVal := right.(*object.Array).Elements
|
||||
elements := make([]object.Object, len(leftVal)+len(rightVal))
|
||||
elements = append(leftVal, rightVal...)
|
||||
return vm.push(&object.Array{Elements: elements})
|
||||
|
||||
// [1] * 3
|
||||
case left.Type() == object.ARRAY_OBJ && right.Type() == object.INTEGER_OBJ:
|
||||
case op == code.OpMul && left.Type() == object.ARRAY_OBJ && right.Type() == object.INTEGER_OBJ:
|
||||
leftVal := left.(*object.Array).Elements
|
||||
rightVal := int(right.(*object.Integer).Value)
|
||||
elements := leftVal
|
||||
@@ -537,7 +558,7 @@ func (vm *VM) executeBinaryOperation(op code.Opcode) error {
|
||||
}
|
||||
return vm.push(&object.Array{Elements: elements})
|
||||
// 3 * [1]
|
||||
case left.Type() == object.INTEGER_OBJ && right.Type() == object.ARRAY_OBJ:
|
||||
case op == code.OpMul && left.Type() == object.INTEGER_OBJ && right.Type() == object.ARRAY_OBJ:
|
||||
leftVal := int(left.(*object.Integer).Value)
|
||||
rightVal := right.(*object.Array).Elements
|
||||
elements := rightVal
|
||||
@@ -547,12 +568,12 @@ func (vm *VM) executeBinaryOperation(op code.Opcode) error {
|
||||
return vm.push(&object.Array{Elements: elements})
|
||||
|
||||
// " " * 4
|
||||
case left.Type() == object.STRING_OBJ && right.Type() == object.INTEGER_OBJ:
|
||||
case op == code.OpMul && left.Type() == object.STRING_OBJ && right.Type() == object.INTEGER_OBJ:
|
||||
leftVal := left.(*object.String).Value
|
||||
rightVal := right.(*object.Integer).Value
|
||||
return vm.push(&object.String{Value: strings.Repeat(leftVal, int(rightVal))})
|
||||
// 4 * " "
|
||||
case left.Type() == object.INTEGER_OBJ && right.Type() == object.STRING_OBJ:
|
||||
case op == code.OpMul && left.Type() == object.INTEGER_OBJ && right.Type() == object.STRING_OBJ:
|
||||
leftVal := left.(*object.Integer).Value
|
||||
rightVal := right.(*object.String).Value
|
||||
return vm.push(&object.String{Value: strings.Repeat(rightVal, int(leftVal))})
|
||||
|
||||
Reference in New Issue
Block a user