pacc logo
pacc v0.3: Handling whitespace

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


12 Handling whitespace

So far, our example grammar insists that everything is squashed together. Normally, we want to allow arbitrary whitespace to appear wherever it makes sense. That usually means between the lexical elements that make up the language. For example, we would like to be able to write ‘12 + 34’ or ‘ 12 +34’ as well as ‘12+34’. Generally, we don’t allow whitespace to appear inside those lexical elements, so we don’t want to accept ‘1 2 + 3 4’.

There are two steps. The first is to define a rule that matches whitespace. Normally it will match at least ‘[ \t\n]*’, that is, zero or more occurences of space, tab, and newline. If the language being defined includes comments, they will usually be matched by this rule too (reflecting the fact that comments are considered equivalent to whitespace by most languages: they separate lexical elements). Conventionally the whitespace-matching rule is given the unobtrusive name ‘_’ (a single underscore), although you can of course choose any name you like.

The second step is to modify the grammar to use the whitespace rule. We will need to define a separate rule for each lexical element in our grammar. Each such rule will match the element in question, followed by our whitespace rule. For example, ‘+’ is a lexical element in our calculator’s grammar, so we will define the rule ‘Plus <- "+" _’ to match it. Also, the start rule will need to permit whitespace at the beginning of an input. Here’s what it looks like.

Expression <- _ s:Sum -> s
Sum <- p:Product Plus s:Sum -> { p + s }
       / Product
Product <- t:Term Star p:Product -> { t * p }
         / Term
Term <- Decimal / lBrace s:Sum rBrace -> s
# lexical elements
Decimal <- [0-9]+ _ -> { atoi(ref_str()) }
Plus :: void <- "+" _
Star <- "*" _
lBrace <- "(" _
rBrace <- ")" _
_ <- [ \t\n]*

This simple example demonstrates another important and powerful feature of PEG parsing: there is no need for a separate “lexer” to assemble characters into lexical tokens. Pacc can do both jobs, and a single grammar specification describes the entire language, from input characters, through lexical elements, all the way up to complete programs.


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

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