diff --git a/ast/print.go b/ast/print.go index c7f7e890..348f30a1 100644 --- a/ast/print.go +++ b/ast/print.go @@ -9,6 +9,54 @@ import ( "github.com/expr-lang/expr/parser/utils" ) +// wrapIf returns the node as a string, in parentheses if cond is true. +func wrapIf(cond bool, node Node) string { + if cond { + return fmt.Sprintf("(%s)", node.String()) + } + return node.String() +} + +// isSequence reports whether the node is a list of expressions. It can only be +// written at the top level, in parentheses or in braces. +func isSequence(node Node) bool { + _, ok := node.(*SequenceNode) + return ok +} + +// isStatement reports whether the node is a list of expressions, or a variable +// declaration, which takes everything that follows it. +func isStatement(node Node) bool { + _, ok := node.(*VariableDeclaratorNode) + return ok || isSequence(node) +} + +// isOpen reports whether the node ends where an operator starts, or the other +// way around, so it can not be an operand without parentheses. +func isOpen(node Node) bool { + _, ok := node.(*ConditionalNode) + return ok || isStatement(node) +} + +// wrapBase returns the string of a node to which a member, a slice or a call is +// added. +func wrapBase(node Node) string { + switch node.(type) { + case *UnaryNode, *BinaryNode, *NilNode, *BoolNode, *IntegerNode, *FloatNode: + return wrapIf(true, node) + } + return wrapIf(isOpen(node), node) +} + +// list returns the nodes as a list of elements or arguments. +func list(nodes []Node) string { + items := make([]string, len(nodes)) + for i, node := range nodes { + items[i] = wrapIf(isSequence(node), node) + } + return strings.Join(items, ", ") +} + func (n *NilNode) String() string { return "nil" } @@ -22,7 +70,11 @@ func (n *IntegerNode) String() string { } func (n *FloatNode) String() string { - return fmt.Sprintf("%v", n.Value) + str := fmt.Sprintf("%v", n.Value) + if !strings.ContainsAny(str, ".eIN") { + str += ".0" // Keep it a float: 2.0 is not 2. + } + return str } func (n *BoolNode) String() string { @@ -57,85 +109,57 @@ func (n *UnaryNode) String() string { if n.Operator == "not" { op = fmt.Sprintf("%s ", n.Operator) } - wrap := false + wrap := isOpen(n.Node) switch b := n.Node.(type) { case *BinaryNode: - if operator.Binary[b.Operator].Precedence < - operator.Unary[n.Operator].Precedence { - wrap = true - } - case *ConditionalNode: - wrap = true + wrap = operator.Binary[b.Operator].Precedence < + operator.Unary[n.Operator].Precedence + case *UnaryNode: + wrap = operator.Unary[b.Operator].Precedence < + operator.Unary[n.Operator].Precedence } - if wrap { - return fmt.Sprintf("%s(%s)", op, n.Node.String()) - } - return fmt.Sprintf("%s%s", op, n.Node.String()) + return op + wrapIf(wrap, n.Node) } func (n *BinaryNode) String() string { - if n.Operator == ".." { - return fmt.Sprintf("%s..%s", n.Left, n.Right) - } + op := operator.Binary[n.Operator] - var lhs, rhs string - var lwrap, rwrap bool + lwrap, rwrap := isOpen(n.Left), isOpen(n.Right) - if l, ok := n.Left.(*UnaryNode); ok { - if operator.Unary[l.Operator].Precedence < - operator.Binary[n.Operator].Precedence { - lwrap = true - } - } - if lb, ok := n.Left.(*BinaryNode); ok { - if operator.Less(lb.Operator, n.Operator) { - lwrap = true - } - if operator.Binary[lb.Operator].Precedence == - operator.Binary[n.Operator].Precedence && - operator.Binary[n.Operator].Associativity == operator.Right { - lwrap = true - } - if lb.Operator == "??" { - lwrap = true - } - if operator.IsBoolean(lb.Operator) && n.Operator != lb.Operator { - lwrap = true - } - } - if rb, ok := n.Right.(*BinaryNode); ok { - if operator.Less(rb.Operator, n.Operator) { - rwrap = true - } - if operator.Binary[rb.Operator].Precedence == - operator.Binary[n.Operator].Precedence && - operator.Binary[n.Operator].Associativity == operator.Left { - rwrap = true - } - if operator.IsBoolean(rb.Operator) && n.Operator != rb.Operator { - rwrap = true - } + switch l := n.Left.(type) { + case *UnaryNode: + lwrap = operator.Unary[l.Operator].Precedence < op.Precedence + case *BinaryNode: + lop := operator.Binary[l.Operator] + lwrap = operator.Less(l.Operator, n.Operator) || + lop.Precedence == op.Precedence && op.Associativity == operator.Right || + l.Operator == "??" || + operator.IsBoolean(l.Operator) && n.Operator != l.Operator || + // a < b < c is a < b && b < c + operator.IsComparison(l.Operator) && operator.IsComparison(n.Operator) } - if _, ok := n.Left.(*ConditionalNode); ok { - lwrap = true - } - if _, ok := n.Right.(*ConditionalNode); ok { - rwrap = true + switch r := n.Right.(type) { + case *UnaryNode: + // Without parentheses, "not" would also take the operators that follow + // and bind tighter than it does: (a * (not b)) * c. + rwrap = operator.Unary[r.Operator].Precedence < op.Precedence && + operator.Unary[r.Operator].Precedence <= operator.Binary["*"].Precedence + case *BinaryNode: + rop := operator.Binary[r.Operator] + rwrap = operator.Less(r.Operator, n.Operator) || + rop.Precedence == op.Precedence && op.Associativity == operator.Left || + operator.IsBoolean(r.Operator) && n.Operator != r.Operator } - if lwrap { - lhs = fmt.Sprintf("(%s)", n.Left.String()) - } else { - lhs = n.Left.String() - } + lhs, rhs := wrapIf(lwrap, n.Left), wrapIf(rwrap, n.Right) - if rwrap { - rhs = fmt.Sprintf("(%s)", n.Right.String()) - } else { - rhs = n.Right.String() + if n.Operator == ".." { + if strings.HasPrefix(rhs, ".") { + rhs = fmt.Sprintf("(%s)", rhs) // 1..(.foo) + } + return fmt.Sprintf("%s..%s", lhs, rhs) } - return fmt.Sprintf("%s %s %s", lhs, n.Operator, rhs) } @@ -144,25 +168,29 @@ func (n *ChainNode) String() string { } func (n *MemberNode) String() string { - node := n.Node.String() - if _, ok := n.Node.(*BinaryNode); ok { - node = fmt.Sprintf("(%s)", node) + node := wrapBase(n.Node) + + str, ok := n.Property.(*StringNode) + ok = ok && utils.IsValidIdentifier(str.Value) + if _, chain := n.Node.(*ChainNode); chain { + ok = false // A name would be a part of the chain: a?.b["c"] is not a?.b.c. } - if n.Optional { - if str, ok := n.Property.(*StringNode); ok && utils.IsValidIdentifier(str.Value) { + if ok { + if n.Optional { return fmt.Sprintf("%s?.%s", node, str.Value) - } else { - return fmt.Sprintf("%s?.[%s]", node, n.Property.String()) } - } - if str, ok := n.Property.(*StringNode); ok && utils.IsValidIdentifier(str.Value) { - if _, ok := n.Node.(*PointerNode); ok { + if pointer, ok := n.Node.(*PointerNode); ok && pointer.Name == "" { return fmt.Sprintf(".%s", str.Value) } return fmt.Sprintf("%s.%s", node, str.Value) } - return fmt.Sprintf("%s[%s]", node, n.Property.String()) + + property := wrapIf(isSequence(n.Property), n.Property) + if n.Optional { + return fmt.Sprintf("%s?.[%s]", node, property) + } + return fmt.Sprintf("%s[%s]", node, property) } func (n *SliceNode) String() string { @@ -170,36 +198,31 @@ func (n *SliceNode) String() string { if n.Optional { op = "?." } - if n.From == nil && n.To == nil { - return fmt.Sprintf("%s%s[:]", n.Node.String(), op) + var from, to string + if n.From != nil { + from = wrapIf(isOpen(n.From), n.From) } - if n.From == nil { - return fmt.Sprintf("%s%s[:%s]", n.Node.String(), op, n.To.String()) + if n.To != nil { + to = wrapIf(isOpen(n.To), n.To) } - if n.To == nil { - return fmt.Sprintf("%s%s[%s:]", n.Node.String(), op, n.From.String()) - } - return fmt.Sprintf("%s%s[%s:%s]", n.Node.String(), op, n.From.String(), n.To.String()) + return fmt.Sprintf("%s%s[%s:%s]", wrapBase(n.Node), op, from, to) } func (n *CallNode) String() string { - arguments := make([]string, len(n.Arguments)) - for i, arg := range n.Arguments { - arguments[i] = arg.String() - } - return fmt.Sprintf("%s(%s)", n.Callee.String(), strings.Join(arguments, ", ")) + return fmt.Sprintf("%s(%s)", wrapBase(n.Callee), list(n.Arguments)) } func (n *BuiltinNode) String() string { - arguments := make([]string, len(n.Arguments)) - for i, arg := range n.Arguments { - arguments[i] = arg.String() - } - return fmt.Sprintf("%s(%s)", n.Name, strings.Join(arguments, ", ")) + return fmt.Sprintf("%s(%s)", n.Name, list(n.Arguments)) } func (n *PredicateNode) String() string { - return n.Node.String() + str := n.Node.String() + // The braces of a map would be taken as those of the predicate. + if isSequence(n.Node) || strings.HasPrefix(str, "{") { + return fmt.Sprintf("{ %s }", str) + } + return str } func (n *PointerNode) String() string { @@ -207,20 +230,21 @@ func (n *PointerNode) String() string { } func (n *VariableDeclaratorNode) String() string { - return fmt.Sprintf("let %s = %s; %s", n.Name, n.Value.String(), n.Expr.String()) + return fmt.Sprintf("let %s = %s; %s", n.Name, wrapIf(isStatement(n.Value), n.Value), n.Expr.String()) } func (n *SequenceNode) String() string { nodes := make([]string, len(n.Nodes)) for i, node := range n.Nodes { - nodes[i] = node.String() + last := i == len(n.Nodes)-1 + nodes[i] = wrapIf(isSequence(node) || isStatement(node) && !last, node) } return strings.Join(nodes, "; ") } func (n *ConditionalNode) String() string { if !n.Ternary { - cond := n.Cond.String() + cond := wrapIf(isStatement(n.Cond), n.Cond) exp1 := n.Exp1.String() if c2, ok := n.Exp2.(*ConditionalNode); ok && !c2.Ternary { return fmt.Sprintf("if %s { %s } else %s", cond, exp1, c2.String()) @@ -229,31 +253,15 @@ func (n *ConditionalNode) String() string { return fmt.Sprintf("if %s { %s } else { %s }", cond, exp1, exp2) } - var cond, exp1, exp2 string - if _, ok := n.Cond.(*ConditionalNode); ok { - cond = fmt.Sprintf("(%s)", n.Cond.String()) - } else { - cond = n.Cond.String() - } - if _, ok := n.Exp1.(*ConditionalNode); ok { - exp1 = fmt.Sprintf("(%s)", n.Exp1.String()) - } else { - exp1 = n.Exp1.String() - } - if _, ok := n.Exp2.(*ConditionalNode); ok { - exp2 = fmt.Sprintf("(%s)", n.Exp2.String()) - } else { - exp2 = n.Exp2.String() - } - return fmt.Sprintf("%s ? %s : %s", cond, exp1, exp2) + return fmt.Sprintf("%s ? %s : %s", + wrapIf(isOpen(n.Cond), n.Cond), + wrapIf(isOpen(n.Exp1), n.Exp1), + wrapIf(isOpen(n.Exp2), n.Exp2), + ) } func (n *ArrayNode) String() string { - nodes := make([]string, len(n.Nodes)) - for i, node := range n.Nodes { - nodes[i] = node.String() - } - return fmt.Sprintf("[%s]", strings.Join(nodes, ", ")) + return fmt.Sprintf("[%s]", list(n.Nodes)) } func (n *MapNode) String() string { @@ -265,11 +273,21 @@ func (n *MapNode) String() string { } func (n *PairNode) String() string { + value := wrapIf(isSequence(n.Value), n.Value) if str, ok := n.Key.(*StringNode); ok { - if utils.IsValidIdentifier(str.Value) { - return fmt.Sprintf("%s: %s", str.Value, n.Value.String()) + if utils.IsValidIdentifier(str.Value) && !isKeyword(str.Value) { + return fmt.Sprintf("%s: %s", str.Value, value) } - return fmt.Sprintf("%s: %s", str.String(), n.Value.String()) + return fmt.Sprintf("%s: %s", str.String(), value) + } + return fmt.Sprintf("(%s): %s", n.Key.String(), value) +} + +// isKeyword reports whether the word is not read as an identifier. +func isKeyword(word string) bool { + switch word { + case "not", "in", "or", "and", "matches", "contains", "startsWith", "endsWith", "let", "if", "else": + return true } - return fmt.Sprintf("(%s): %s", n.Key.String(), n.Value.String()) + return false } diff --git a/ast/print_test.go b/ast/print_test.go index 8087e9dd..533d4634 100644 --- a/ast/print_test.go +++ b/ast/print_test.go @@ -101,6 +101,66 @@ func TestPrint(t *testing.T) { } } +func TestPrint_parse(t *testing.T) { + tests := []struct { + input string + want string + }{ + {`(a + b)[1:2]`, `(a + b)[1:2]`}, + {`(a ? b : c)[1:]`, `(a ? b : c)[1:]`}, + {`(a ?? b)[0]`, `(a ?? b)[0]`}, + {`(-a).b`, `(-a).b`}, + {`(a ? b : c).d`, `(a ? b : c).d`}, + {`(a ? b : c).d()`, `(a ? b : c).d()`}, + {`(1).a`, `(1).a`}, + {`-((1)[a])`, `-(1)[a]`}, + {`(nil)?.a`, `(nil)?.a`}, + {`(a?.b)["c"]`, `a?.b["c"]`}, + {`a?.b.c`, `a?.b.c`}, + {`(a?.["b"])?.["c"]`, `a?.b?.["c"]`}, + {`2.0 * a`, `2.0 * a`}, + {`1e21`, `1e+21`}, + {`(a < b) < c`, `(a < b) < c`}, + {`a < b < c`, `a < b && b < c`}, + {`(a > b)..c`, `(a > b)..c`}, + {`a..(b ? c : d)`, `a..(b ? c : d)`}, + {`map(a, 1..(.b))`, `map(a, 1..(.b))`}, + {`(a * not b) * c`, `a * (not b) * c`}, + {`-(not a) * b`, `-(not a) * b`}, + {`(a ** -b) * c`, `a ** -b * c`}, + {`(let x = a; x) + b`, `(let x = a; x) + b`}, + {`-(a; b)`, `-(a; b)`}, + {`f((a; b), c)`, `f((a; b), c)`}, + {`[(a; b), c]`, `[(a; b), c]`}, + {`{a: (b; c)}`, `{a: (b; c)}`}, + {`a[(b; c)]`, `a[(b; c)]`}, + {`a[(b; c):]`, `a[(b; c):]`}, + {`(a; b) ? (c; d) : (e; f)`, `(a; b) ? (c; d) : (e; f)`}, + {`if (a; b) { c; d } else { e; f }`, `if (a; b) { c; d } else { e; f }`}, + {`let x = (let y = a; y); x`, `let x = (let y = a; y); x`}, + {`(let x = a; x); b`, `(let x = a; x); b`}, + {`a; let x = b; x`, `a; let x = b; x`}, + {`(a; b); c`, `(a; b); c`}, + {`map(a, {b; #})`, `map(a, { b; # })`}, + {`map(a, {{b: #}})`, `map(a, { {b: #} })`}, + {`map(a, {{b: #}.b})`, `map(a, { {b: #}.b })`}, + {`reduce(a, #acc.b + #.c)`, `reduce(a, #acc.b + .c)`}, + {`{"not": a, "b c": d}`, `{"not": a, "b c": d}`}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + tree, err := parser.Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.want, tree.Node.String()) + + printed, err := parser.Parse(tree.Node.String()) + require.NoError(t, err) + assert.Equal(t, ast.Dump(tree.Node), ast.Dump(printed.Node)) + }) + } +} + func TestPrint_MemberNode(t *testing.T) { node := &ast.MemberNode{ Node: &ast.IdentifierNode{ diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index 5d7b4b8c..9c5cd68e 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -459,6 +459,31 @@ func TestOptimize_predicate_combination_nested(t *testing.T) { assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node)) } +func TestOptimize_predicate_combination_different_collections(t *testing.T) { + env := map[string]any{ + "cond": true, + "a": []int{-1, 5}, + "b": []int{7, 8}, + } + for code, want := range map[string]bool{ + `all((cond ? a : b)[1:], # > 0) && all(cond ? a : b[1:], # > 0)`: false, + `any(cond ? a : b[1:], # == -5) || any((cond ? b : a)[1:], # == 8)`: true, + `any((cond ? a : b)[1:], # == -1) || any(cond ? a : b[1:], # == -1)`: true, + `none((cond ? a : b)[1:], # < 0) && none(cond ? a : b[1:], # < 0)`: false, + } { + t.Run(code, func(t *testing.T) { + for _, optimize := range []bool{false, true} { + program, err := expr.Compile(code, expr.Env(env), expr.Optimize(optimize)) + require.NoError(t, err) + + got, err := expr.Run(program, env) + require.NoError(t, err) + require.Equal(t, want, got) + } + }) + } +} + func TestOptimize_predicate_combination_with_non_json_float(t *testing.T) { // Constant folding turns [0/0] into a ConstantNode holding []any{NaN}. // predicateCombination compares the collection arguments via String(),