Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
268 changes: 143 additions & 125 deletions ast/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}

Expand All @@ -144,83 +168,83 @@ 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 {
op := ""
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 {
return fmt.Sprintf("#%s", n.Name)
}

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())
Expand All @@ -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 {
Expand All @@ -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
}
Loading
Loading