OOPEG: An Object-Oriented Parser Generator Based on Parsing Expression Grammars
Jacob Korsgaard, Jørgen Ulrik · 2010
Syntax Tree expr = {add} [left]:expr [right]:expr | {sub} [left]:expr [right]:expr | {mul} [left]:expr [right]:expr | {div} [left]:expr [right]:expr | {number} number; In the CST to AST annotations we can either create and return a new node, or we can return a node of the same AST type created deeper in the hierarchy. In this example the factor and value productions are eliminated using these annotations, resulting in a more concise AST. We can also generate lists of nodes in the AST, listing 3.12 shows how this can be done for the arguments passed to a function call. Listing 3.12: Example of list creation with SableCC CST to AST transformations. /* This example assumes expr to be defined as in the previous example */ Productions func {-> func} = {function} [name]:identifier left_paren [args]:arg_list right_paren {-> New func.function(name,[args.expr])}; arg_list {-> expr*} = {single} [arg]:expr {-> [arg.expr]} | {multiple} [arg]:expr comma [rest]:arg_list{-> [arg.expr, rest.expr]}; Abstract Syntax Tree func = {function} [name]:identifier [args]:expr*;Syntax Tree func = {function} [name]:identifier [args]:expr*; One thing worth noticing is that the AST grammar can not refer to rules defined in the CST grammar. This means that every node you want in the AST has to be defined in the AST grammar. This can potentially lead to having many rules defined both in the CST grammar and the AST grammar, which can make the grammar harder to maintain. More information about SableCC can be found in [9].