pyparsing and 'keywords'

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Dec 14 13:39:19 EST 2004


"Berteun Damman" <berteun at gmail.com> wrote in message
news:1103043673.455705.113650 at f14g2000cwb.googlegroups.com...
> Hello,
>
> 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
> either.
>
> How to fix this?
>
> Thank you,
>
> Berteun
>
Berteun -

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" ]
def rejectKeywords(string,loc,tokens):
    if tokens[0] in keywords:
        raise ParseException(string,loc,"found keyword %s" % tokens[0])
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.

-- Paul





More information about the Python-list mailing list