HANDBOOK / GENTLE PRIMER / At a Glance /

# Translating Concrete Syntax into Abstract Syntax

We now show how concrete syntax can be translated into abstract syntax. This can be done in exactly the same way as with the calculator. We use the expression grammar where each nonterminal gets an output parameter that specifies the corresponding abstract syntax.

    'root' expression(-> X) print(X)

    'nonterm' expression(-> Expr)

       'rule' expression(-> X): expr2(-> X)
       'rule' expression(-> plus(X,Y)): expression(-> X) "+" expr2(-> Y)
       'rule' expression(-> minus(X,Y)): expression(-> X) "-" expr2(-> Y)

    'nonterm' expr2(-> Expr)

       'rule' expr2(-> X): expr3(-> X)
       'rule' expr2(-> mult(X,Y)): expr2(-> X) "*" expr3(-> Y)
       'rule' expr2(-> div(X,Y)): expr2(-> X) "/" expr3(-> Y)

    'nonterm' expr3(-> Expr)

       'rule' expr3(-> num(X)): Number(-> X)
       'rule' expr3(-> neg(X)): "-" expr3(-> X)
       'rule' expr3(-> X): "+" expr3(-> X)
       'rule' expr3(-> X): "(" expression(-> X) ")"

    'token' Number(-> INT)

Consider the rule

    'rule' expression(-> plus(X, Y)): expression(-> X) "+" expr(-> Y)

that corresponds to the rule

    'rule' expression(-> X + Y): expression(-> X) "+" expr(-> Y)

of the calculator.

If `X` is the abstract syntax of the `expression` appearing on the right hand side and `Y` is the abstract syntax of the `expr2` phrase then `plus(X,Y)` is the abstract syntax of the whole phrase.

For example, if `X` has the value `num(10)` and `Y` has the value `mult(num(20),num(20))`, then `plus(num(10)), mult(num(20), num(30))` is defined as the abstract syntax of the whole phrase parsed by the rule.

    'root' expression(-> X) print(X)

causes the abstract syntax to be printed.