Proposal: Binary operator precedence in pest grammar g

To exemplify, let us consider (generic) grammar rules

<primary> ::= <identifier> |  "(" <expression> ")" | ...
<multiplication> ::= <primary> |  <multiplication> "*" <primary>
<additition> ::= <multiplication> | <addition> "+" <multiplication>

These rules implicitly define the relative precedence of addition and multiplication, and the fact that they are left-associative.

For instance, according to the rules, the expression

x + y * z

can only be parsed as

tree 1:
  +
 / \
x   *
   / \
  y   z

and not as

tree 2:
    *
   / \
  +   z
 / \
x   y

because for tree 2 the expression x + y * z would have to be a <multiplication>, but then x + y cannot be a <primary>. Instead, for tree 1 the expression x + y * z is an <addition>.

Similar situation for x * y + z.

Also similarly, the rules force x + y + x to be parsed as (x + y) + z and x * y * z as (x * y) * z – i.e. to be left-associative.

The above rules are left-recursive though, so they need to be modified for Pest. Techniques to eliminate left recursion may change the desired associativity (requiring some post-parsing adaptation), but may still preserve the desired precedence. This page Left recursion - Wikipedia explains and exemplifies. So we’ll need to think this though a bit more, and ponder the tradeoffs. (The current parser + precedence climber work fine, so this does not seem urgent.)

The left-recursive rules may be used as is for user-oriented documentation – as done in the Java and C specifications, for example. We could also consider formally proving the equivalence of the left-recursive user-oriented grammar to the Pest grammar.

1 Like

2022-04-03T22:00:00Z2022-04-22T22:00:00Z
BUBBLE SORT
We implement a bubble sorting algorithm on an array of u32 elements. Bubble sort is a standard algorithm that works by examining each set of adjacent elements, from left to right, and swapping positions if they are out of order. This process is repeated until there are no more swaps to be made, resulting in a sorted array.