Although this manual covers all aspects of the CUP system, it is relatively brief, and assumes you have at least a little bit of knowledge of LR parsing. A working knowledge of YACC is also very helpful in understanding how CUP specifications work. A number of compiler construction textbooks (such as [2,3]) cover this material, and discuss the YACC system (which is quite similar to this one) as a specific example.
Using CUP involves creating a simple specification based on the grammar for which a parser is needed, along with construction of a scanner capable of breaking characters up into meaningful tokens (such as keywords, numbers, and special symbols).
As a simple example, consider a system for evaluating simple arithmetic expressions over integers. This system would read expressions from standard input (each terminated with a semicolon), evaluate them, and print the result on standard output. A grammar for the input to such a system might look like:
expr_list ::= expr_list expr_part | expr_part expr_part ::= expr ';' expr ::= expr '+' expr | expr '-' expr | expr '*' expr | expr '/' expr | expr '%' expr | '(' expr ')' | '-' expr | numberTo specify a parser based on this grammar, our first step is to identify and name the set of terminal symbols that will appear on input, and the set of non-terminal symbols. In this case, the non-terminals are:
expr_list, expr_part and expr .For terminal names we might choose:
SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD, NUMBER, LPAREN, and RPARENThe experienced user will note a problem with the above grammar. It is ambiguous. An ambiguous grammar is a grammar which, given a certain input, can reduce the parts of the input in two different ways such as to give two different answers. Take the above grammar, for example. given the following input:
// CUP specification for a simple expression evaluator (no actions) import java_cup.runtime.*; /* Preliminaries to set up and use the scanner. */ init with {: scanner.init(); :}; scan with {: return scanner.next_token(); :}; /* Terminals (tokens returned by the scanner). */ terminal SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD; terminal UMINUS, LPAREN, RPAREN; terminal Integer NUMBER; /* Non terminals */ non terminal expr_list, expr_part; non terminal Integer expr, term, factor; /* Precedences */ precedence left PLUS, MINUS; precedence left TIMES, DIVIDE, MOD; precedence left UMINUS; /* The grammar */ expr_list ::= expr_list expr_part | expr_part; expr_part ::= expr SEMI; expr ::= expr PLUS expr | expr MINUS expr | expr TIMES expr | expr DIVIDE expr | expr MOD expr | MINUS expr %prec UMINUS | LPAREN expr RPAREN | NUMBER ;
To produce a parser from this specification we use the CUP generator. If this specification were stored in a file parser.cup, then (on a Unix system at least) we might invoke CUP using a command like:
java -jar java-cup-11b.jar parser.cupIn this case, the system will produce two Java source files containing parts of the generated parser: sym.java and parser.java. As you might expect, these two files contain declarations for the classes sym and parser. The sym class contains a series of constant declarations, one for each terminal symbol. This is typically used by the scanner to refer to symbols (e.g. with code such as "return new Symbol(sym.SEMI);" ). The parser class implements the parser itself.
The specification above, while constructing a full parser, does not perform any semantic actions &emdash; it will only indicate success or failure of a parse. To calculate and print values of each expression, we must embed Java code within the parser to carry out actions at various points. In CUP, actions are contained in code strings which are surrounded by delimiters of the form {: and :} (we can see examples of this in the init with and scan with clauses above). In general, the system records all characters within the delimiters, but does not try to check that it contains valid Java code.
A more complete CUP specification for our example system (with actions
embedded at various points in the grammar) is shown below:
// CUP specification for a simple expression evaluator (w/ actions) import java_cup.runtime.*; /* Preliminaries to set up and use the scanner. */ init with {: scanner.init(); :}; scan with {: return scanner.next_token(); :}; /* Terminals (tokens returned by the scanner). */ terminal SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD; terminal UMINUS, LPAREN, RPAREN; terminal Integer NUMBER; /* Non-terminals */ non terminal expr_list, expr_part; non terminal Integer expr; /* Precedences */ precedence left PLUS, MINUS; precedence left TIMES, DIVIDE, MOD; precedence left UMINUS; /* The grammar */ expr_list ::= expr_list expr_part | expr_part; expr_part ::= expr:e {: System.out.println("= " + e); :} SEMI ; expr ::= expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue() + e2.intValue()); :} | expr:e1 MINUS expr:e2 {: RESULT = new Integer(e1.intValue() - e2.intValue()); :} | expr:e1 TIMES expr:e2 {: RESULT = new Integer(e1.intValue() * e2.intValue()); :} | expr:e1 DIVIDE expr:e2 {: RESULT = new Integer(e1.intValue() / e2.intValue()); :} | expr:e1 MOD expr:e2 {: RESULT = new Integer(e1.intValue() % e2.intValue()); :} | NUMBER:n {: RESULT = n; :} | MINUS expr:e {: RESULT = new Integer(0 - e.intValue()); :} %prec UMINUS | LPAREN expr:e RPAREN {: RESULT = e; :} ;
expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue() + e2.intValue()); :}the first non-terminal expr has been labeled with e1, and the second with e2. The left hand side value of each production is always implicitly labeled as RESULT.
Each symbol appearing in a production is represented at runtime by an object of type Symbol on the parse stack. The labels refer to the instance variable value in those objects. In the expression expr:e1 PLUS expr:e2, e1 and e2 refer to objects of type Integer. These objects are in the value fields of the objects of type Symbol representing those non-terminals on the parse stack. RESULT is of type Integer as well, since the resulting non-terminal expr was declared as of type Integer. This object becomes the value instance variable of a new Symbol object.
For each label, two more variables accessible to the user are declared. A left and right value labels are passed to the code string, so that the user can find out where the left and right side of each terminal or non-terminal is in the input stream. The name of these variables is the label name, plus left or right. for example, given the right hand side of a production expr:e1 PLUS expr:e2 the user could not only access variables e1 and e2, but also e1left, e1right, e2left and e2right. these variables are of type int.
The final step in creating a working parser is to create a scanner (also
known as a lexical analyzer or simply a lexer). This routine is
responsible for reading individual characters, removing things things like
white space and comments, recognizing which terminal symbols from the
grammar each group of characters represents, then returning Symbol objects
representing these symbols to the parser.
The terminals will be retrieved with a call to the
scanner function. In the example, the parser will call
scanner.next_token(). The scanner should return objects of
type java_cup.runtime.Symbol. This type is very different than
older versions of CUP's java_cup.runtime.symbol. These Symbol
objects contains the instance variable value of type Object,
which should be
set by the lexer. This variable refers to the value of that symbol, and
the type of object in value should be of the same type as declared in
the terminal and non terminal declarations. In the
above example, if the lexer wished to pass a NUMBER token, it should
create a Symbol with the value instance variable
filled with an object of type Integer. Symbol
objects corresponding to terminals and non-terminals with no value
have a null value field.
The code contained in the init with clause of the specification
will be executed before any tokens are requested. Each token will be
requested using whatever code is found in the scan with clause.
Beyond this, the exact form the scanner takes is up to you; however
note that each call to the scanner function should return a new
instance of java_cup.runtime.Symbol
(or a subclass).
These symbol objects are annotated with parser information and pushed
onto a stack; reusing objects will result in the parser annotations
being scrambled. As of CUP 0.10j, Symbol
reuse should be
detected if it occurs; the parser will throw an Error
telling you to fix your scanner.
In the next section a more detailed and formal explanation of all parts of a CUP specification will be given. Section 3 describes options for running the CUP system. Section 4 discusses the details of how to customize a CUP parser, while section 5 discusses the scanner interface added in CUP 0.10j. Section 6 considers error recovery. Finally, Section 7 provides a conclusion.
package name;where name name is a Java package identifier, possibly in several parts separated by ".". In general, CUP employs Java lexical conventions. So for example, both styles of Java comments are supported, and identifiers are constructed beginning with a letter, dollar sign ($), or underscore (_), which can then be followed by zero or more letters, numbers, dollar signs, and underscores.
After an optional package declaration, there can be zero or more import declarations. As in a Java program these have the form:
import package_name.class_name;or
import package_name.*;The package declaration indicates what package the sym and parser classes that are generated by the system will be in. Any import declarations that appear in the specification will also appear in the source file for the parser class allowing various names from that package to be used directly in user supplied action code. After the package and imports, a specification can include a parser class name, as follows:
class name;If a class name is supplied, then that is the name that will be used for the generated parser code. As well, the generated symbols class will have the given name followed by "Sym".
If no class name is supplied, then the parser class is called "parser", and the symbols class is called "sym".
action code {: ... :};where {: ... :} is a code string whose contents will be placed directly within the action class class declaration.
After the action code declaration is an optional parser code declaration. This declaration allows methods and variable to be placed directly within the generated parser class. Although this is less common, it can be helpful when customizing the parser &emdash; it is possible for example, to include scanning methods inside the parser and/or override the default error reporting routines. This declaration is very similar to the action code declaration and takes the form:
parser code {: ... :};Again, code from the code string is placed directly into the generated parser class definition.
Next in the specification is the optional init declaration which has the form:
init with {: ... :};This declaration provides code that will be executed by the parser before it asks for the first token. Typically, this is used to initialize the scanner as well as various tables and other data structures that might be needed by semantic actions. In this case, the code given in the code string forms the body of a void method inside the parser class.
The final (optional) user code section of the specification indicates how the parser should ask for the next token from the scanner. This has the form:
scan with {: ... :};As with the init clause, the contents of the code string forms the body of a method in the generated parser. However, in this case the method returns an object of type java_cup.runtime.Symbol. Consequently the code found in the scan with clause should return such a value. See section 5 for information on the default behavior if the
scan with
section is omitted.As of CUP 0.10j the action code, parser code, init code, and scan with sections may appear in any order. They must, however, precede the symbol lists.
terminal classname name1, name2, ...; non terminal classname name1, name2, ...; terminal name1, name2, ...;and
non terminal name1, name2, ...;where classname can be a multiple part name separated with "."s. The classname specified represents the type of the value of that terminal or non-terminal. When accessing these values through labels, the users uses the type declared. the classname can be of any type. If no classname is given, then the terminal or non-terminal holds no value. a label referring to such a symbol with have a null value. As of CUP 0.10j, you may specify non-terminals the declaration "
nonterminal
" (note, no
space) as well as the original "non terminal
" spelling.Names of terminals and non-terminals cannot be CUP reserved words; these include "code", "action", "parser", "terminal", "non", "nonterminal", "init", "scan", "with", "start", "precedence", "left", "right", "nonassoc", "import", and "package".
precedence left terminal[, terminal...]; precedence right terminal[, terminal...]; precedence nonassoc terminal[, terminal...];The comma separated list indicates that those terminals should have the associativity specified at that precedence level and the precedence of that declaration. The order of precedence, from highest to lowest, is bottom to top. Hence, this declares that multiplication and division have higher precedence than addition and subtraction:
precedence left ADD, SUBTRACT; precedence left TIMES, DIVIDE;Precedence resolves shift reduce problems. For example, given the input to the above example parser 3 + 4 * 8, the parser doesn't know whether to reduce 3 + 4 or shift the '*' onto the stack. However, since '*' has a higher precedence than '+', it will be shifted and the multiplication will be performed before the addition.
CUP assigns each one of its terminals a precedence according to these declarations. Any terminals not in this declaration have lowest precedence. CUP also assigns each of its productions a precedence. That precedence is equal to the precedence of the last terminal in that production. If the production has no terminals, then it has lowest precedence. For example, expr ::= expr TIMES expr would have the same precedence as TIMES. When there is a shift/reduce conflict, the parser determines whether the terminal to be shifted has a higher precedence, or if the production to reduce by does. If the terminal has higher precedence, it it shifted, if the production has higher precedence, a reduce is performed. If they have equal precedence, associativity of the terminal determine what happens.
An associativity is assigned to each terminal used in the precedence/associativity declarations. The three associativities are left, right and nonassoc Associativities are also used to resolve shift/reduce conflicts, but only in the case of equal precedences. If the associativity of the terminal that can be shifted is left, then a reduce is performed. This means, if the input is a string of additions, like 3 + 4 + 5 + 6 + 7, the parser will always reduce them from left to right, in this case, starting with 3 + 4. If the associativity of the terminal is right, it is shifted onto the stack. hence, the reductions will take place from right to left. So, if PLUS were declared with associativity of right, the 6 + 7 would be reduced first in the above string. If a terminal is declared as nonassoc, then two consecutive occurrences of equal precedence non-associative terminals generates an error. This is useful for comparison operations. For example, if the input string is 6 == 7 == 8 == 9, the parser should generate an error. If '==' is declared as nonassoc then an error will be generated.
All terminals not used in the precedence/associativity declarations are treated as lowest precedence. If a shift/reduce error results, involving two such terminals, it cannot be resolved, as the above conflicts are, so it will be reported.
start with non-terminal;This indicates which non-terminal is the start or goal non-terminal for parsing. If a start non-terminal is not explicitly declared, then the non-terminal on the left hand side of the first production will be used. At the end of a successful parse, CUP returns an object of type java_cup.runtime.Symbol. This Symbol's value instance variable contains the final reduction result.
The grammar itself follows the optional start declaration. Each production in the grammar has a left hand side non-terminal followed by the symbol "::=", which is then followed by a series of zero or more actions, terminal, or non-terminal symbols, followed by an optional contextual precedence assignment, and terminated with a semicolon (;).
Each symbol on the right hand side can optionally be labeled with a name. Label names appear after the symbol name separated by a colon (:). Label names must be unique within the production, and can be used within action code to refer to the value of the symbol. Along with the label, two more variables are created, which are the label plus left and the label plus right. These are int values that contain the right and left locations of what the terminal or non-terminal covers in the input file. These values must be properly initialized in the terminals by the lexer. The left and right values then propagate to non-terminals to which productions reduce.
If there are several productions for the same non-terminal they may be declared together. In this case the productions start with the non-terminal and "::=". This is followed by multiple right hand sides each separated by a bar (|). The full set of productions is then terminated by a semicolon.
However, integers alone might not be good enough for locating symbols in
an input file. This is why CUP also supports more complex location information
in the form of Location
objects. These objects need to be created
by the scanner component. They become available
within the actions if the parser generator gets the right commandline parameter.
They are accessible via the handles ??xleft
and ??xright
,
with ??
being the label for the symbol.
Contextual precedence assignments follow all the symbols and actions of the right hand side of the production whose precedence it is assigning. Contextual precedence assignment allows a production to be assigned a precedence not based on the last terminal in it. A good example is shown in the above sample parser specification:
precedence left PLUS, MINUS; precedence left TIMES, DIVIDE, MOD; precedence left UMINUS; expr ::= MINUS expr:e {: RESULT = new Integer(0 - e.intValue()); :} %prec UMINUS
Here, there production is declared as having the precedence of UMINUS. Hence, the parser can give the MINUS sign two different precedences, depending on whether it is a unary minus or a subtraction operation.
java -jar java-cup-11b.jar options inputfileOnce running, CUP expects to find a specification file on standard input and produces two Java source files as output.
In addition to the specification file, CUP's behavior can also be changed
by passing various options to it. Legal options are documented in
Main.java
and include:
interface
rather than as a class
.
java_cup.runtime.Scanner
. By default, the
generated parser refers to this interface, which means you cannot
use these parsers with CUP runtimes older than 0.10j. If your
parser does not use the new scanner integration features, then you
may specify the -noscanner
option to suppress the
java_cup.runtime.Scanner
references and allow
compatibility with old runtimes. Not many people should have reason
to do this.
-version
flag will cause it
to print out the working version of CUP and halt. This allows
automated CUP version checking for Makefiles, install scripts and
other applications which may require it.
To use cup in an ANT script, You have to add the following task definition to Your build.xml file:
<taskdef name="cup" classname="java_cup.anttask.CUPTask" classpathref="cupclasspath" />
Now, You are ready to use Your new <cup/> task to generate own parsers from within ANT. Such a generation statement could look like:
<target name="cup"> <cup srcfile="path/to/cupfile/Parser.cup" destdir="path/to/javafiles" interface="true" /> </target>
You can specify all commandline flags from chapter
The parser class contains the actual generated parser. It is a subclass of java_cup.runtime.lr_parser which implements a general table driven framework for an LR parser. The generated parser class provides a series of tables for use by the general framework. Three tables are provided:
Beyond the parse tables, generated (or inherited) code provides a series of methods that can be used to customize the generated parser. Some of these methods are supplied by code found in part of the specification and can be customized directly in that fashion. The others are provided by the lr_parser base class and can be overridden with new versions (via the parser code declaration) to customize the system. Methods available for customization include:
getScanner().next_token()
.
In addition to the normal parser, the runtime system also provides a debugging version of the parser. This operates in exactly the same way as the normal parser, but prints debugging messages (by calling public void debug_message(String mess) whose default implementation prints a message to System.err).
Based on these routines, invocation of a CUP parser is typically done with code such as:
/* create a parsing object */ parser parser_obj = new parser(); /* open input files, etc. here */ Symbol parse_tree = null; try { if (do_debug_parse) parse_tree = parser_obj.debug_parse(); else parse_tree = parser_obj.parse(); } catch (Exception e) { /* do cleanup here - - possibly rethrow e */ } finally { /* do close out here */ }
In CUP 0.10j, scanner integration was improved according to suggestions made by David MacMahon. The changes make it easier to incorporate JLex and other automatically-generated scanners into CUP parsers.
To use the new code, your scanner should implement the
java_cup.runtime.Scanner
interface, defined as:
package java_cup.runtime; public interface Scanner { public Symbol next_token() throws java.lang.Exception; }
In addition to the methods described in section
4, the java_cup.runtime.lr_parser
class has two new
accessor methods, setScanner()
and getScanner()
.
The default implementation of scan()
is:
public Symbol scan() throws java.lang.Exception { return getScanner().next_token(); }
The generated parser also contains a constructor which takes a
Scanner
and calls setScanner()
with it. In
most cases, then, the init with
and scan
with
directives may be omitted. You can simply create the
parser with a reference to the desired scanner:
/* create a parsing object */ parser parser_obj = new parser(new my_scanner());or set the scanner after the parser is created:
/* create a parsing object */ parser parser_obj = new parser(); /* set the default scanner */ parser_obj.setScanner(new my_scanner());
Note that because the parser uses look-ahead, resetting the scanner in
the middle of a parse is not recommended. If you attempt to use the
default implementation of scan()
without first calling
setScanner()
, a NullPointerException
will be
thrown.
As an example of scanner integration, the following three lines in the lexer-generator input are all that is required to use a JLex scanner with CUP:
%implements java_cup.runtime.Scanner %function next_token %type java_cup.runtime.SymbolIt is anticipated that the JLex directive
%cup
will
abbreviate the above three directive in the next version of JLex.
Invoking the parser with the JLex scanner is then simply:
parser parser_obj = new parser( new Yylex( some_InputStream_or_Reader));
Note that you still have to handle EOF correctly; the JLex code to do so is something like:
%eofval{ return sym.EOF; %eofval}where
sym
is the name of the symbol class for your
generated parser.The simple_calc example in the CUP distribution illustrates the use of the scanner integration features with a hand-coded scanner.
Since CUP v11a we offer the possibility of advanced symbol handling in CUP.
Therefore, You can implement Your own SymbolFactory, derived from
java_cup.runtime.SymbolFactory
, and have CUP manage Your own type of
symbols. We've done that for You already in the pre-defined
java_cup.runtime.ComplexSymbolFactory
, which provides support for
detailed location information in the symbol class. Just have a look at CUP's own
Lexer.jflex
, which is already using the new feature.
All You have to do is providing Your CUP-generated parser with the new SymbolFactory which can be done like this:
SymbolFactory symbolFactory = new ComplexSymbolFactory(); MyParser parser = new MyParser(new Lexer(inputfile,symbolFactory),symbolFactory);
The ComplexSymbolFactory
is used straight-forward: In Your
lexer, instead of directly creating Symbol
-Objects, You call
the factory's creation methods, called newSymbol(...)
.
Most of the times, You will want to use just the ComplexSymbolFactory
.
You can do that, by adding convenience methods into Your parser's body, like the following one
for symobls with an attached String-value:
public Symbol symbol(String plainname, int terminalcode, String lexem){ return symbolFactory.newSymbol(plainname, terminalcode, new Location(yyline+1, yycolumn +1), new Location(yyline+1,yycolumn+yylength()), lexem); }
The Location
-Objects provide a convenient way to manage detailed
position informations for Your symbols. In order to use them in Your action specifications,
don't forget to set the -locations
-commandline-parameter when running CUP!
This generates into the frame of each production no plain integer values (referred to via ??left,??right
,
with ?? being Your symbol name) any more, but Your beloved Location objects (??xleft,??xright
, again
with ?? Your symbol's name). You can then access all its information like this:
expr ::= expr:e1 PLUS expr:e2 {: RESULT = BinExpr.createAdd(e1,e2); :} | NUMBER:n {: RESULT = Expr.createConst(nxleft,n,nxright); :}
In the example, we create an expression tree from our input language. Here,
we store the location information for the subexpressions in the AST.
This can be seen in the action for the NUMBER
, where we access
nxleft
and nxright
. Note, that in this example we
only store the locations of leaves directly. In a convenient implementation
of the AST, we would expect a recursive function, that computes the locations for each
intermediary node in the tree.
CUP offers an additional layer between scanner and parser, in order to cache the actual sequence of terminal symbols, provided by the scanner for potential later use. This comes in handy, if e.g. a pretty printer or syntax highlighter is applied.
Given that the Lexer
class implements CUP's Scanner
interface, we can buffer its output with the ScannerBuffer
and access
the tokenstream with getBuffered()
, once the parsing is finished:
Scanner scanner = new Lexer(); ScannerBuffer buffer = new ScannerBuffer(lexer); Parser p = new Parser(buffer,new ComplexSymbolFactory); p.parse(); System.out.println(buffer.getBuffered());
The error symbol only comes into play if a syntax error is detected. If a syntax error is detected then the parser tries to replace some portion of the input token stream with error and then continue parsing. For example, we might have productions such as:
stmt ::= expr SEMI | while_stmt SEMI | if_stmt SEMI | ... | error SEMI ;This indicates that if none of the normal productions for stmt can be matched by the input, then a syntax error should be declared, and recovery should be made by skipping erroneous tokens (equivalent to matching and replacing them with error) up to a point at which the parse can be continued with a semicolon (and additional context that legally follows a statement). An error is considered to be recovered from if and only if a sufficient number of tokens past the error symbol can be successfully parsed. (The number of tokens required is determined by the error_sync_size() method of the parser and defaults to 3).
Specifically, the parser first looks for the closest state to the top of the parse stack that has an outgoing transition under error. This generally corresponds to working from productions that represent more detailed constructs (such as a specific kind of statement) up to productions that represent more general or enclosing constructs (such as the general production for all statements or a production representing a whole section of declarations) until we get to a place where an error recovery production has been provided for. Once the parser is placed into a configuration that has an immediate error recovery (by popping the stack to the first such state), the parser begins skipping tokens to find a point at which the parse can be continued. After discarding each token, the parser attempts to parse ahead in the input (without executing any embedded semantic actions). If the parser can successfully parse past the required number of tokens, then the input is backed up to the point of recovery and the parse is resumed normally (executing all actions). If the parse cannot be continued far enough, then another token is discarded and the parser again tries to parse ahead. If the end of input is reached without making a successful recovery (or there was no suitable error recovery state found on the parse stack to begin with) then error recovery fails.
In case of parsing errors, CUP offers support in delivering meaningful
user feedback. Consider that the specified parser is to be applied in a
fancy IDE which registers parsing errors and makes propositions, on how
to fix these errors. In these cases, an implementation for the action code
of an error symbol could consist in telling the IDE about the exact
location of the unmatched input, as well as the list of viable symbols, with
which the parser can advance a step in the current state, reaching an
accepting state. These symbols are coded as integers, and can be decoded to
their string representations via calls to symbol_name_from_id()
.
Such an action can look like:
stmt ::= expr SEMI | while_stmt SEMI | if_stmt SEMI | ... | error:e {: Listexpected = expected_token_ids(); myIDE.registerParseError(exleft,exright,expected); :} SEMI ;
This document covers version 0.11b of the system. Check the CUP home page: http://www2.in.tum.de/projects/cuptum/ for the latest release information, instructions for downloading the system, and additional news about CUP. Bug reports and other comments for the developers should be sent to the CUP maintainer, M. Petter, at petterATcs.tum.edu
Before this, it was maintained by C. Scott Ananian, at cananian@alumni.princeton.edu
CUP was originally written by Scott Hudson, in August of 1995.
It was extended to support precedence by Frank Flannery, in July of 1996.
On-going improvements have been done by C. Scott Ananian, the CUP maintainer, from December of 1997 to the present.
java_cup_spec ::= package_spec import_list class_name code_parts symbol_list precedence_list start_spec production_list package_spec ::= PACKAGE multipart_id SEMI | empty import_list ::= import_list import_spec | empty import_spec ::= IMPORT import_id SEMI class_name ::= CLASS ID SEMI | empty code_part ::= action_code_part | parser_code_part | init_code | scan_code code_parts ::= code_parts code_part | empty action_code_part ::= ACTION CODE CODE_STRING opt_semi parser_code_part ::= PARSER CODE CODE_STRING opt_semi init_code ::= INIT WITH CODE_STRING opt_semi scan_code ::= SCAN WITH CODE_STRING opt_semi symbol_list ::= symbol_list symbol | symbol symbol ::= TERMINAL type_id declares_term | NON TERMINAL type_id declares_non_term | NONTERMINAL type_id declares_non_term | TERMINAL declares_term | NON TERMINAL declares_non_term | NONTERMIANL declared_non_term term_name_list ::= term_name_list COMMA new_term_id | new_term_id non_term_name_list ::= non_term_name_list COMMA new_non_term_id | new_non_term_id declares_term ::= term_name_list SEMI declares_non_term ::= non_term_name_list SEMI precedence_list ::= precedence_l | empty precedence_l ::= precedence_l preced + preced; preced ::= PRECEDENCE LEFT terminal_list SEMI | PRECEDENCE RIGHT terminal_list SEMI | PRECEDENCE NONASSOC terminal_list SEMI terminal_list ::= terminal_list COMMA terminal_id | terminal_id start_spec ::= START WITH nt_id SEMI | empty production_list ::= production_list production | production production ::= nt_id COLON_COLON_EQUALS rhs_list SEMI rhs_list ::= rhs_list BAR rhs | rhs rhs ::= prod_part_list PERCENT_PREC term_id | prod_part_list prod_part_list ::= prod_part_list prod_part | empty prod_part ::= symbol_id opt_label | CODE_STRING opt_label ::= COLON label_id | empty multipart_id ::= multipart_id DOT ID | ID import_id ::= multipart_id DOT STAR | multipart_id type_id ::= multipart_id terminal_id ::= term_id term_id ::= symbol_id new_term_id ::= ID new_non_term_id ::= ID nt_id ::= ID symbol_id ::= ID label_id ::= ID opt_semi ::= SEMI | empty
// Simple Example Scanner Class import java_cup.runtime.*; import sym; public class scanner { /* single lookahead character */ protected static int next_char; // since cup v11 we use SymbolFactories rather than Symbols private SymbolFactory sf = new DefaultSymbolFactory(); /* advance input by one character */ protected static void advance() throws java.io.IOException { next_char = System.in.read(); } /* initialize the scanner */ public static void init() throws java.io.IOException { advance(); } /* recognize and return the next complete token */ public static Symbol next_token() throws java.io.IOException { for (;;) switch (next_char) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* parse a decimal integer */ int i_val = 0; do { i_val = i_val * 10 + (next_char - '0'); advance(); } while (next_char >= '0' && next_char <= '9'); return sf.newSymbol("NUMBER",sym.NUMBER, new Integer(i_val)); case ';': advance(); return sf.newSymbol("SEMI",sym.SEMI); case '+': advance(); return sf.newSymbol("PLUS",sym.PLUS); case '-': advance(); return sf.newSymbol("MINUS",sym.MINUS); case '*': advance(); return sf.newSymbol("TIMES",sym.TIMES); case '/': advance(); return sf.newSymbol("DIVIDE",sym.DIVIDE); case '%': advance(); return sf.newSymbol("MOD",sym.MOD); case '(': advance(); return sf.newSymbol("LPAREN",sym.LPAREN); case ')': advance(); return sf.newSymbol("RPAREN",sym.RPAREN); case -1: return return sf.newSymbol("EOF",sym.EOF); default: /* in this simple scanner we just ignore everything else */ advance(); break; } } };
For more information, refer to the manual on scanners.
terminal classname terminal [, terminal ...];still works. The classname, however indicates the type of the value of the terminal or non-terminal, and does not indicate the type of object placed on the parse stack. A declaration, such as:
terminal terminal [, terminal ...];indicates the terminals in the list hold no value.
For more information, refer to the manual on declarations.
For more information, refer to the manual on labels.
For more information, refer to the manual on RESULT.
For more information, refer to the manual on positions.
precedence {left| right | nonassoc} terminal[, terminal ...]; ...The terminals are assigned a precedence, where terminals on the same line have equal precedences, and the precedence declarations farther down the list of precedence declarations have higher precedence. left, right and nonassoc specify the associativity of these terminals. left associativity corresponds to a reduce on conflict, right to a shift on conflict, and nonassoc to an error on conflict. Hence, ambiguous grammars may now be used.
For more information, refer to the manual on precedence.
lhs ::= {right hand side list of terminals, non-terminals and actions} %prec {terminal};this production would then have a precedence equal to the terminal specified after the %prec. Hence, shift/reduce conflicts can be contextually resolved. Note that the %prec terminal part comes after all actions strings. It does not come before the last action string.
For more information, refer to the manual on contextual precedence. These changes implemented by:
This is because the parsing tables (and parsing engine) are in one object (belonging to class parser or whatever name is specified by the -parser directive), and the semantic actions are in another object (of class CUP$actions).
However, there is a way to do it, though it's a bit inelegant. The action object has a private final field named parser that points to the parsing object. Thus, methods and instance variables of the parser can be accessed within semantic actions as:
parser.report_error(message,info); x = parser.mydata;
Perhaps this will not be necessary in a future release, and that such methods and variables as report_error and mydata will be available directly from the semantic actions; we will achieve this by combining the "parser" object and the "actions" object together.
For a list of any other currently known bugs in CUP, see http://www.cs.princeton.edu/~appel/modern/java/CUP/bugs.html.
java_cup.runtime.Scanner
interface.