[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: [lpeg] How to implement a "fallback/onerror/panic" function in lpeg?
- From: "Robert G. Jakabosky" <bobby@...>
- Date: Tue, 30 Aug 2011 04:30:41 -0700
On Monday 29, Xavier Wang wrote:
> Hi all,
> In MoonScript's inspired, I'm trying to make a tiny compiler with
> lpeg, but I found a problem: when the subject is incorrect, or I write
> a wrong pattern, the match just return nil, not any other things, It
> makes debug program very difficult, So I had to ask, has any idea to
> implement a fallback function for the pattern match?
> the fallback function may get some information, e.g. failure position,
> expected terminal or other information, but I can't output error
> message such as "test.moon: 10: `ident' expected after `,'" if I only
> have failure position, How could I produce messages like this? maybe a
> function mark() to mark some terminal/nonterminal to makes they can be
> shown in message?
I used LPeg to parse Google Protocol Buffer definition files. The grammar 
has two wrapper function eV & eP (defined on lines 61-66). They are used in
place of V & P, when that pattern is expected.
The 'error' function (defined in  lines 68-74) is call in eV to create a
closure that is called when the expected pattern is not matched in the
grammar. This give good syntax error messages like what you are asking for.
This idea is not my own I got it from some other LPeg grammar/scanner (I think
it was one for C code).
Hope that helps.
Robert G. Jakabosky