pyparsing and 'keywords'
ptmcg at austin.rr._bogus_.com
Tue Dec 14 19:39:19 CET 2004
"Berteun Damman" <berteun at gmail.com> wrote in message
news:1103043673.455705.113650 at f14g2000cwb.googlegroups.com...
> I'm having some problems with pyparsing, I could not find how to tell
> it to view certain words as keywords, i.e. not as a possible variable
> name (in an elegant way),
> for example, I have this little grammar:
> terminator = Literal(";")
> expr = Word(alphas)
> body = Forward();
> ifstat = "if" + body + "fi"
> stat = expr | ifstat
> body << OneOrMore(stat + terminator)
> program = body
> I.e. some program which contains statements separated by semicolons. A
> statement is either an if [....] fi statement or simply a word.
> If I try however to parse the String "if test; testagain; fi;", it does
> not work, because the fi is interpreted as an expr, not as the end of
> the if statement, and of course, adding another fi doesn't solve this
> How to fix this?
> Thank you,
The simplest way I can think of for this grammar off the top of my head is
to use a parse action to reject keywords.
keywords = [ "if", "fi", "else", "return" ]
if tokens in keywords:
raise ParseException(string,loc,"found keyword %s" % tokens)
expr.setParseAction( rejectKeywords )
I took a different tack in the idl parser that is included in the pyparsing
examples directory, but it is more extensive.
More information about the Python-list