Skip to content

Commit

Permalink
feat: overload "+" with strings
Browse files Browse the repository at this point in the history
  • Loading branch information
ascandone committed Dec 6, 2024
1 parent 9bf4d35 commit 77b673d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions internal/interpreter/evaluate_expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ func (st *programState) plusOp(left parser.ValueExpr, right parser.ValueExpr) (V
expectMapped(expectNumber, func(bi big.Int) opAdd {
return MonetaryInt(bi)
}),

expectMapped(expectString, func(str string) opAdd {
return String(str)
}),
))

if err != nil {
Expand Down
10 changes: 10 additions & 0 deletions internal/interpreter/infix.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type opAdd interface {

var _ opAdd = (*MonetaryInt)(nil)
var _ opAdd = (*Monetary)(nil)
var _ opAdd = (*String)(nil)

func (m MonetaryInt) evalAdd(st *programState, other parser.ValueExpr) (Value, InterpreterError) {
m1 := big.Int(m)
Expand All @@ -24,6 +25,15 @@ func (m MonetaryInt) evalAdd(st *programState, other parser.ValueExpr) (Value, I
return MonetaryInt(*sum), nil
}

func (m String) evalAdd(st *programState, other parser.ValueExpr) (Value, InterpreterError) {
m1 := string(m)
m2, err := evaluateExprAs(st, other, expectString)
if err != nil {
return nil, err
}
return String(string(m1) + *m2), nil
}

func (m Monetary) evalAdd(st *programState, other parser.ValueExpr) (Value, InterpreterError) {
m2, err := evaluateExprAs(st, other, expectMonetary)
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions internal/interpreter/interpreter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3543,3 +3543,20 @@ func TestSubMonetaries(t *testing.T) {
}
test(t, tc)
}

func TestPlusStringOverload(t *testing.T) {
script := `
set_tx_meta("k", "a" + "b")
`

tc := NewTestCase()
tc.compile(t, script)

tc.expected = CaseResult{
Postings: []Posting{},
TxMetadata: map[string]machine.Value{
"k": machine.String("ab"),
},
}
test(t, tc)
}

0 comments on commit 77b673d

Please sign in to comment.