pacc logo
pacc v0.3: Alternatives

Next: , Previous: , Up: Top   [Contents][Index]


4 Alternatives

An absolutely crucial point to understand about pacc grammars is that alternatives are tried in order. The first alternative which matches successfully is the one that “wins”, and later alternatives aren’t considered at all.

Let’s go multi-lingual. (There are more elegant ways to write this, which we’ll come to soon.)

Start <- "yes" {1} / "oui" {1} / "no" {0} / "non" {0} # wrong!

That may look like it should work, but this is what happens when we try it:

  $ french0 oui
  parsed with value 1
  $ french0 no
  parsed with value 0
  $ french0 non
  arg:1:3: expected end-of-input

What went wrong there? The problem is that the third alternative ‘"no"’ matches the first two characters of the input ‘non’, and so that becomes the winning alternative, even though that leads to an overall failure. Pacc parsers never “back up” once an alternative has completely matched.

For this simple grammar, the obvious fix is simply to swap the order of these two alternatives. We’ll see similar problems, and other fixes, later on.

Start <- "yes" {1} / "oui" {1} / "non" {0} / "no" {0}

This grammar works as intended:

$ french1 no
parsed with value 0
$ french1 non
parsed with value 0

This behaviour is the fundamental difference between PEGs (the style of grammars that pacc uses) and CFGs (the more traditional alternative), so it may take you a while to get used to it. (This paragraph needs rewriting and expanding.)

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