""> >

Chapter 4

4.1 Package content

TPG is a package which main function is to take a grammar and return a parser1. You only need to import TPG and use these four objects:

This function takes a grammar in a string and produces a parser in Python (also in a string). You can call exec to actually build it.
This exception is raised when the lexer fails.
This exception is raised when the parser fails.
This exception is raised by the grammar itself when some semantic properties fail.

The grammar must be in a string (see figure 4.1).

Figure 4.1: Grammar embeding example
    my_grammar = r"""  
    parser Foo:  
        START/x -> Bar/x .  
        Bar/x -> 'bar'/x .  

The tpg.compile function produces Python code from the grammar (see figure 4.2).

Figure 4.2: Parser compilation example
    exec(tpg.compile(my_grammar))    # Compiles my_grammar

Then you can use the new generated parser. The parser is now simply a Python class (see figure 4.3).

Figure 4.3: Parser usage example
    test = "bar"  
    my_parser = Foo()  
    x = my_parser(test)               # Uses the START symbol  
    print x  
    x = my_parser.parse('Bar', test)  # Uses the Bar symbol  
    print x

4.2 Command line usage

The tpg script is just a wrapper for the package. It reads a grammar in a file and write the generated code in a Python script. To produce a Python script from a grammar you can use tpg as follow:
    tpg [-v|-vv] grammar.g [-o]

tpg accepts some options on the command line:

turns tpg into a verbose mode (it displays parser names).
turns tpg into a more verbose mode (it displays parser names and simplified rules).
tells tpg to generate the parser in The default output file is if -o option is not provided and grammar.g is the name of the grammar.