Chapter 7
Parser

7.1 Declaration

A parser is declared as a tpg.Parser class. The doc string of the class contains the definition of the tokens and rules.

7.2 Grammar rules

Rule declarations have two parts. The left side declares the symbol associated to the rule, its attributes and its return value. The right side describes the decomposition of the rule. Both parts of the declaration are separated with an arrow () and the declaration ends with a ;.

The symbol defined by the rule as well as the symbols that appear in the rule can have attributes and return values. The attribute list - if any - is given as an object list enclosed in left and right angles. The return value - if any - is extracted by the infix / operator. See figure 7.1 for example.




Figure 7.1: Rule declaration
    SYMBOL <att1, att2, att3> / return_expression_of_SYMBOL ->  
 
        A <x, y> / ret_value_of_A  
 
        B <y, z> / ret_value_of_B  
 
        ;



7.3 Parsing terminal symbols

Each time a terminal symbol is encountered in a rule, the parser compares it to the current token in the token list. If it is different the parser backtracks.

7.4 Parsing non terminal symbols

7.4.1 Starting the parser

You can start the parser from the axiom or from any other non terminal symbol. When the parser can not parse the whole token list a tpg.SyntacticError is raised. The value returned by the parser is the return value of the parsed symbol.

From the axiom

The axiom is a special non terminal symbol named START. Parsers are callable objects. When an instance of a parser is called, the START rule is parsed. The first argument of the call is the string to parse. The other arguments of the call are given to the START symbol.

This allows to simply write x=calc("1+1") to parse and compute an expression if calc is an instance of an expression parser.

From another non terminal symbol

It’s also possible to start parsing from any other non terminal symbol. TPG parsers have a method named parse. The first argument is the name of the symbol to start from. The second argument is the string to parse. The other arguments are given to the specified symbol.

For example to start parsing a Term you can write:

    f=calc.parse(’Term’, "2*3")

7.4.2 In a rule

To parse a non terminal symbol in a rule, TPG call the rule corresponding to the symbol.

7.5 Sequences

Sequences in grammar rules describe in which order symbols should appear in the input string. For example the sequence A B recognizes an A followed by a B. Sequences can be empty.

For example to say that a sum is a term plus another term you can write:

    Sum -> Term ’+’ Term ;

7.6 Alternatives

Alternatives in grammar rules describe several possible decompositions of a symbol. The infix pipe operator () is used to separate alternatives. A   B recognizes either an A or a B. If both A and B can be matched only the first match is considered. So the order of alternatives is very important. If an alternative has an empty choice, it must be the last. Empty choices in other positions will be reported as syntax errors.

For example to say that an atom is an integer or an expression in paranthesis you can write:

    Atom -> integer | ’\(’ Expr ’\)’ ;

7.7 Repetitions

Repetitions in grammar rules describe how many times an expression should be matched.

A?
recognizes zero or one A.
A*
recognizes zero or more A.
A+
recognizes one or more A.
A{m,n}
recognizes at least m and at most n A.

Repetitions are greedy. Repetitions are translated into Python loops. Thus whatever the length of the repetitions, the Python stack will not overflow.

7.8 Precedence and grouping

The figure 7.2 lists the different structures in increasing precedence order. To override the default precedence you can group expressions with parenthesis.



Figure 7.2: Precedence in TPG expressions


Structure Example




Alternative A   B


Sequence A B


Repetitions A?, A*, A+


Symbol and groupingA and (  )



7.9 Actions

Grammar rules can contain actions as Python code. Python code is copied verbatim into the generated code.

7.9.1 Abstract syntax trees

An abstract syntax tree (AST) is an abstract representation of the structure of the input. A node of an AST is a Python object (there is no constraint about its class). AST nodes are completely defined by the user.

The figure 7.3 shows a node symbolizing a couple.




Figure 7.3: AST example
 
class Couple:  
    def __init__(self, a, b):  
        self.a = a  
        self.b = b  
 
class Foo(tpg.Parser):  
    r"""  
    COUPLE -> ’(’ ITEM/a ’,’ ITEM/b ’)’ $ c = Couple(a,b) $ ;  
 
    COUPLE/$Couple(a,b)$ -> ’(’ ITEM/a ’,’ ITEM/b ’)’ ;  
    """



Creating an AST

AST are created in Python code delimited either by $...$ or by {{...}} (see figure 7.9.1).

Updating an AST

When parsing lists for example it is useful to save all the items of the list. In that case one can use a list and its append method (see figure 7.4).




Figure 7.4: AST update example
 
class ListParser(tpg.Parser):  
    r"""  
    LIST/l ->  
        ’(’  
                            $ l = List<>  
            ITEM/a          $ l.append(a)  
            ( ’,’ ITEM/a    $ l.append(a)  
            )*  
        ’)’  
        ;  
    """



7.9.2 Text extraction

TPG can extract a portion of the input string. The idea is to put marks while parsing and then extract the text between the two marks. This extracts the whole text between the marks, including the tokens defined as separators.

7.9.3 Object

TPG 3 doesn’t handle Python object as TPG 2. Only identifiers, integers and strings are known. Other objects must be written in Python code delimited either by $...$ or by {{...}}.

Argument lists and tuples

Argument list is a comma separated list of objects. Remember that arguments are enclosed in left and right angles.

    <object1, object2, object3>

Argument lists and tuples have the same syntax except from the possibility to have default arguments, argument lists and argument dictionnaries as arguments as in Python.

    RULE<arg1, arg2=18, arg3=None, *other_args, **keywords> -> ;

Python code object

A Python code object is a piece of Python code in double curly brackets or in dollar signs. Python code used in an object expression must have only one line.

    $ dict([ (x,x**2) for x in range(100) ]) $ # Python embeded in TPG

Text extraction

Text extraction is done by the extract method. Marks can be put in the input string by the mark method or the prefix operator.

    @beginning      # equivalent to $ beginning = self.mark()  
    ...  
    @end            # equivalent to $ end = self.mark()  
    ...  
    $ my_string = self.extract(beginning, end)

Getting the line and row number of a token

The line and row methods return the line and row number of the current token. If the first parameter is a mark (see 7.9.2) the method returns the line number of the token following the mark.

Backtracking

The user can force the parser to backtrack in rule actions. The module has a WrongToken exception for that purpose (see figure 7.5).




Figure 7.5: Backtracking with WrongToken example
    # NATURAL matches integers greater than 0  
    NATURAL/n ->  
        number/n  
        $ if n<1: raise tpg.WrongToken $  
        ;



Parsers have another useful method named check (see figure 7.6). This method checks a condition. If this condition is false then WrongToken if called in order to backtrack.




Figure 7.6: Backtracking with the check method example
    # NATURAL matches integers greater than 0  
    NATURAL/n ->  
        number/n  
        $ self.check(n>=1) $  
        ;



A shortcut for the check method is the check keyword followed by the condition to check (see figure 7.7).




Figure 7.7: Backtracking with the check keyword example
    # NATURAL matches integers greater than 0  
    NATURAL/n ->  
        number/n  
        check $ n>=1 $  
        ;



Error reporting

The user can force the parser to stop and raise an exception. The parser classes have a error method for that purpose (see figure 7.8). This method raises a SemanticError.




Figure 7.8: Error reporting the error method example
    # FRACT parses fractions  
    FRACT/<n,d> ->  
        number/n ’/’ number/d  
        $ if d==0: self.error("Division by zero") $  
        ;



A shortcut for the error method is the error keyword followed by the object to give to the SemanticError exception (see figure 7.9).




Figure 7.9: Error reporting the error keyword example
    # FRACT parses fractions  
    FRACT/<n,d> ->  
        number/n ’/’ number/d  
        ( check d | error "Division by zero" )  
        ;