pacc logo
pacc v0.3: Expressing precedence

11 Expressing precedence

Now let’s expand our calculator example to include multiplication. This introduces the notion of precedence. Multiplication is considered to have higher precedence than addition. So in an expression such as ‘2+3*4’, the multiplication is performed first, and the answer is ‘14’ (not ‘20’).

Some parser generators have explicit notation to express precedence, but in pacc we do it simply by using rules. Here’s how we add multiplication to the calculator.

Sum <- p:Product "+" s:Sum -> { p + s }
    / Product
Product <- d:Decimal "*" p:Product -> { d * p }
    / Decimal
Decimal <- [0-9]+ -> { atoi(ref_str()) }

Simply because of the way the rules are set out, pacc is obliged to perform the higher precedence ‘*’ operator before the lower precedence ‘+’ operator: it needs a ‘Product’ before it can begin evaluating a ‘Sum’.

Of course, as soon as we have precedence, we want to offer the option to override it with brackets. That’s easy to implement too.

Sum <- p:Product "+" s:Sum -> { p + s }
    / Product
Product <- t:Term "*" p:Product -> { t * p }
    / Term
Term <- Decimal / "(" s:Sum ")" -> s
Decimal <- [0-9]+ -> { atoi(ref_str()) }

Again, the higher precedence operation (in this case bracketing) appears lower down the grammar, and everything works out. This grammar can parse ‘2+3*4’ with a value of 14, and ‘(2+3)*4’ with a value of 20.

Last updated: 2016-08-03 21:39:50 UTC

News

Porting and packaging

One thing pacc needs is more users. And, perhaps, one way to get more users is to reduce the friction in getting started with pacc. An obvious lubricant is packaging. Read More...

Release relief

Looking at _pacc_coords(), I noticed that it seemed to have the same realloc() bug that I'd just fixed in _pacc_result(). However, the "list of arrays" trick really wasn't going to work here. Read More...

See more news articles

feed