Skip to content

ast: print expressions that parse back to the same nodes - #1026

Merged
antonmedv merged 2 commits into
expr-lang:masterfrom
bardrop-oss:fix-print-parentheses
Nov 25, 2026
Merged

antonmedv merged 2 commits into
expr-lang:masterfrom
bardrop-oss:fix-print-parentheses

Conversation

@bardrop

@bardrop bardrop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Node.String() leaves out parentheses that the parser needs, so many expressions print as a different one:

expression printed before
(a ? b : c)[1:] a ? b : c[1:]
(a + b)[1:2] a + b[1:2]
(-a).b -a.b
(a < b) < c a < b < c, which is a < b && b < c
(a * not b) * c a * not b * c, which is a * not (b * c)
(a?.b)["c"] a?.b.c
(let x = a; x) + b let x = a; x + b
2.0 * a 2 * a
reduce(a, #acc.b) reduce(a, .b)
map(a, {{b: #}}) map(a, {b: #}), a syntax error
{"not": a} {not: a}, a syntax error

This also gives wrong results, because predicateCombination compares the collections by their string. With cond = true, a = [-1, 5] and b = [7, 8]:

all((cond ? a : b)[1:], # > 0) && all(cond ? a : b[1:], # > 0)

is true, and false with expr.Optimize(false). The second collection is a, which has a -1, so false is right.

The printer now adds parentheses wherever the parser needs them. The output of all expressions in the existing print tests is the same as before. The visible changes for other expressions are the extra parentheses, 2.0 for a float that is a whole number, and braces around a predicate that is a list of expressions or starts with a map.

To find the cases I generated random expressions, and compared the nodes with those of the printed expression: 184480 of 269828 were equal before, and all 265254 are now (the second run also has reduce, more pointers and escapes). TestPrint_parse has one of each kind, and checks that it parses back to the same nodes: 34 of the 40 fail before. 3 of the 4 cases of the optimizer test fail before.

bardrop and others added 2 commits November 25, 2026 01:49
Node.String() left out parentheses that change the meaning, for example
in (a ? b : c)[1:] and (a < b) < c, and wrote 2.0 as 2.

The optimizer compares the collections of all, any and none by their
string, so it combined calls on different collections.
@antonmedv
antonmedv merged commit 1716531 into expr-lang:master Nov 25, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants