lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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?
> 
> Thanks.

I used LPeg to parse Google Protocol Buffer definition files.  The grammar [1] 
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 [2] 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.

1. https://github.com/Neopallium/lua-pb/blob/master/pb/proto/grammar.lua
2. https://github.com/Neopallium/lua-pb/blob/master/pb/proto/scanner.lua

-- 
Robert G. Jakabosky