Commit fa027f71 authored by Antoine Martin's avatar Antoine Martin Committed by Etienne Renault

desugar: support bool exprs with 2 variables

Previously only lhs could be expanded
parent 660971ac
......@@ -125,23 +125,48 @@ func (sv *simpleVar) Expand(aliases map[string][]string, op string) (string, err
return b.String(), nil
}
// Expand the boolExpression by replacing a variable by all of its aliases. At
// least lhs needs to be a key in aliases.
//
// If rhs is also a key, it needs to have as many aliases as lhs, meaning it is
// present in as many recursive calls as the other variable. If rhs isn't a key,
// it will be left as is in the resulting expansion.
func (bx *boolExpression) Expand(aliases map[string][]string, op string) (string, error) {
al, ok := aliases[bx.lhs]
lhsAl, ok := aliases[bx.lhs]
if !ok {
return "", fmt.Errorf("couldn't find aliases for %s", bx.lhs)
}
if len(al) == 0 {
if len(lhsAl) == 0 {
return "", fmt.Errorf("aliases list for %s is empty", bx.lhs)
}
// determine whether to use aliases for rhs or keep it verbatim
rhsAl, useRhsAlias := aliases[bx.rhs]
if useRhsAlias {
if len(rhsAl) != len(lhsAl) {
return "", fmt.Errorf(
"`%s` and `%s` need to belong to the same recursive calls",
bx.lhs,
bx.rhs,
)
}
}
var b strings.Builder
rhs := bx.rhs
b.WriteString("(")
for i, alias := range al {
for i, alias := range lhsAl {
if i != 0 {
fmt.Fprintf(&b, " %s ", op)
}
fmt.Fprintf(&b, "(\"%s %s %s\")", alias, bx.operator, bx.rhs)
// if expanding rhs as well
if useRhsAlias {
rhs = rhsAl[i]
}
fmt.Fprintf(&b, "(\"%s %s %s\")", alias, bx.operator, rhs)
}
b.WriteString(")")
......
......@@ -131,6 +131,47 @@ func TestBoolExpressionExpand(t *testing.T) {
expected: "",
shouldFail: true,
},
// 3
{
expr: boolExpression{
lhs: "a",
operator: "==",
rhs: "b",
},
aliases: map[string][]string{
"a": []string{
"a1",
"a2",
},
"b": []string{
"b1",
"b2",
},
},
expected: `(("a1 == b1") || ("a2 == b2"))`,
shouldFail: false,
},
// 4
{
expr: boolExpression{
lhs: "a",
operator: "==",
rhs: "b",
},
aliases: map[string][]string{
"a": []string{
"a1",
"a2",
},
"b": []string{
"b1",
"b2",
"b3",
},
},
expected: "",
shouldFail: true,
},
}
for i, test := range tests {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment