/********************************************************************** CS 536 Java Cup Example: This is the Java Cup specification for the "parser" for the addition grammar. Note that this example does a combination of parsing and evaluating: a program consists of a list of expressions terminated by semicolons. Each expression is made up of integer literals and plus signs. The parser creates is an AST that is very flat: each expression is evaluated and it is the resulting integer value that is stored in the AST. So the AST has two levels: the root node and the root node's children each of which is an integer literal node (representing the list of evaluated expressions). **********************************************************************/ import java_cup.runtime.*; import java.util.*; parser code {: public void syntax_error(Symbol currToken) { if (currToken.value == null) { Errors.fatal(0,0, "Syntax error at end of file"); } else { Errors.fatal(((TokenVal)currToken.value).linenum, ((TokenVal)currToken.value).charnum, "Syntax error"); } System.exit(-1); } :}; /* Terminals (tokens returned by the scanner) */ terminal IntLitTokenVal INTLITERAL; terminal SEMICOLON; terminal PLUS; /* Nonterminals */ non terminal ProgramNode program; non terminal LinkedList expList; non terminal IntLitNode exp; /* Precedence and associativity declarations */ precedence left PLUS; start with program; /* Grammar with actions */ program ::= expList:eList {: RESULT = new ProgramNode(new ExpListNode(eList)); :} ; expList ::= exp:e SEMICOLON expList:eList {: eList.addFirst(e); RESULT = eList; :} | /* epsilon */ {: RESULT = new LinkedList(); :} ; exp ::= INTLITERAL:i {: RESULT = new IntLitNode(i.intVal); :} | exp:i1 PLUS exp:i2 {: RESULT = new IntLitNode(i1.getVal() + i2.getVal()); :} ;