Skip to content

Commit

Permalink
Improve coverage for expressions, specifically Print
Browse files Browse the repository at this point in the history
  • Loading branch information
ysheffer authored and ysheffer committed Apr 24, 2024
1 parent 2776d1f commit eacf8ac
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
7 changes: 3 additions & 4 deletions datalog/expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,6 @@ func (e *Expression) Print(symbols *SymbolTable) string {
return "<invalid expression: unary operation failed to pop value>"
}
res := op.(UnaryOp).Print(v)
if err != nil {
return "<invalid expression: binary operation failed to pop right value>"
}
s.Push(res)
case OpTypeBinary:
right, err := s.Pop()
Expand Down Expand Up @@ -160,6 +157,8 @@ func (op UnaryOp) Print(value string) string {
out = fmt.Sprintf("!%s", value)
case UnaryParens:
out = fmt.Sprintf("(%s)", value)
case UnaryLength:
out = fmt.Sprintf("%s.length()", value)
default:
out = fmt.Sprintf("unknown(%s)", value)
}
Expand Down Expand Up @@ -228,7 +227,7 @@ func (Length) Eval(value Term, symbols *SymbolTable) (Term, error) {
case TermTypeSet:
out = Integer(len(value.(Set)))
default:
return nil, fmt.Errorf("datalog: unexpected Negate value type: %d", value.Type())
return nil, fmt.Errorf("datalog: unexpected Length value type: %d", value.Type())
}
return out, nil
}
Expand Down
49 changes: 49 additions & 0 deletions datalog/expressions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1188,3 +1188,52 @@ func TestBinaryOr(t *testing.T) {
})
}
}

func TestPrint(t *testing.T) {
syms := SymbolTable{}
syms.Insert("abc")
testCases := []struct {
desc string
expr Expression
res string
}{
{
desc: "number",
expr: Expression{Value{Integer(9)}},
res: "9",
},
{
desc: "string",
expr: Expression{Value{syms.Sym("abc")}},
res: "\"abc\"",
},
{
desc: "unary",
expr: Expression{Value{syms.Sym("abc")}, UnaryOp{Length{}}},
res: "\"abc\".length()",
},
{
desc: "binary",
expr: Expression{Value{Integer(9)}, Value{Integer(4)}, BinaryOp{Mul{}}},
res: "9 * 4",
},
{
desc: "parens",
expr: Expression{
Value{Integer(9)},
Value{Integer(3)},
BinaryOp{Add{}},
UnaryOp{Parens{}},
Value{Integer(4)},
BinaryOp{Div{}},
},
res: "(9 + 3) / 4",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
p := tc.expr.Print(&syms)
require.Equal(t, tc.res, p)
})
}
}

0 comments on commit eacf8ac

Please sign in to comment.