0001: package java_cup.runtime;
0002:
0003: import java.util.Stack;
0004:
0005: /** This class implements a skeleton table driven LR parser. In general,
0006: * LR parsers are a form of bottom up shift-reduce parsers. Shift-reduce
0007: * parsers act by shifting input onto a parse stack until the Symbols
0008: * matching the right hand side of a production appear on the top of the
0009: * stack. Once this occurs, a reduce is performed. This involves removing
0010: * the Symbols corresponding to the right hand side of the production
0011: * (the so called "handle") and replacing them with the non-terminal from
0012: * the left hand side of the production. <p>
0013: *
0014: * To control the decision of whether to shift or reduce at any given point,
0015: * the parser uses a state machine (the "viable prefix recognition machine"
0016: * built by the parser generator). The current state of the machine is placed
0017: * on top of the parse stack (stored as part of a Symbol object representing
0018: * a terminal or non terminal). The parse action table is consulted
0019: * (using the current state and the current lookahead Symbol as indexes) to
0020: * determine whether to shift or to reduce. When the parser shifts, it
0021: * changes to a new state by pushing a new Symbol (containing a new state)
0022: * onto the stack. When the parser reduces, it pops the handle (right hand
0023: * side of a production) off the stack. This leaves the parser in the state
0024: * it was in before any of those Symbols were matched. Next the reduce-goto
0025: * table is consulted (using the new state and current lookahead Symbol as
0026: * indexes) to determine a new state to go to. The parser then shifts to
0027: * this goto state by pushing the left hand side Symbol of the production
0028: * (also containing the new state) onto the stack.<p>
0029: *
0030: * This class actually provides four LR parsers. The methods parse() and
0031: * debug_parse() provide two versions of the main parser (the only difference
0032: * being that debug_parse() emits debugging trace messages as it parses).
0033: * In addition to these main parsers, the error recovery mechanism uses two
0034: * more. One of these is used to simulate "parsing ahead" in the input
0035: * without carrying out actions (to verify that a potential error recovery
0036: * has worked), and the other is used to parse through buffered "parse ahead"
0037: * input in order to execute all actions and re-synchronize the actual parser
0038: * configuration.<p>
0039: *
0040: * This is an abstract class which is normally filled out by a subclass
0041: * generated by the JavaCup parser generator. In addition to supplying
0042: * the actual parse tables, generated code also supplies methods which
0043: * invoke various pieces of user supplied code, provide access to certain
0044: * special Symbols (e.g., EOF and error), etc. Specifically, the following
0045: * abstract methods are normally supplied by generated code:
0046: * <dl compact>
0047: * <dt> short[][] production_table()
0048: * <dd> Provides a reference to the production table (indicating the index of
0049: * the left hand side non terminal and the length of the right hand side
0050: * for each production in the grammar).
0051: * <dt> short[][] action_table()
0052: * <dd> Provides a reference to the parse action table.
0053: * <dt> short[][] reduce_table()
0054: * <dd> Provides a reference to the reduce-goto table.
0055: * <dt> int start_state()
0056: * <dd> Indicates the index of the start state.
0057: * <dt> int start_production()
0058: * <dd> Indicates the index of the starting production.
0059: * <dt> int EOF_sym()
0060: * <dd> Indicates the index of the EOF Symbol.
0061: * <dt> int error_sym()
0062: * <dd> Indicates the index of the error Symbol.
0063: * <dt> Symbol do_action()
0064: * <dd> Executes a piece of user supplied action code. This always comes at
0065: * the point of a reduce in the parse, so this code also allocates and
0066: * fills in the left hand side non terminal Symbol object that is to be
0067: * pushed onto the stack for the reduce.
0068: * <dt> void init_actions()
0069: * <dd> Code to initialize a special object that encapsulates user supplied
0070: * actions (this object is used by do_action() to actually carry out the
0071: * actions).
0072: * </dl>
0073: *
0074: * In addition to these routines that <i>must</i> be supplied by the
0075: * generated subclass there are also a series of routines that <i>may</i>
0076: * be supplied. These include:
0077: * <dl>
0078: * <dt> Symbol scan()
0079: * <dd> Used to get the next input Symbol from the scanner.
0080: * <dt> Scanner getScanner()
0081: * <dd> Used to provide a scanner for the default implementation of
0082: * scan().
0083: * <dt> int error_sync_size()
0084: * <dd> This determines how many Symbols past the point of an error
0085: * must be parsed without error in order to consider a recovery to
0086: * be valid. This defaults to 3. Values less than 2 are not
0087: * recommended.
0088: * <dt> void report_error(String message, Object info)
0089: * <dd> This method is called to report an error. The default implementation
0090: * simply prints a message to System.err and where the error occurred.
0091: * This method is often replaced in order to provide a more sophisticated
0092: * error reporting mechanism.
0093: * <dt> void report_fatal_error(String message, Object info)
0094: * <dd> This method is called when a fatal error that cannot be recovered from
0095: * is encountered. In the default implementation, it calls
0096: * report_error() to emit a message, then throws an exception.
0097: * <dt> void syntax_error(Symbol cur_token)
0098: * <dd> This method is called as soon as syntax error is detected (but
0099: * before recovery is attempted). In the default implementation it
0100: * invokes: report_error("Syntax error", null);
0101: * <dt> void unrecovered_syntax_error(Symbol cur_token)
0102: * <dd> This method is called if syntax error recovery fails. In the default
0103: * implementation it invokes:<br>
0104: * report_fatal_error("Couldn't repair and continue parse", null);
0105: * </dl>
0106: *
0107: * @see java_cup.runtime.Symbol
0108: * @see java_cup.runtime.Symbol
0109: * @see java_cup.runtime.virtual_parse_stack
0110: * @version last updated: 7/3/96
0111: * @author Frank Flannery
0112: */
0113:
0114: public abstract class lr_parser {
0115:
0116: /*-----------------------------------------------------------*/
0117: /*--- Constructor(s) ----------------------------------------*/
0118: /*-----------------------------------------------------------*/
0119:
0120: /** Simple constructor. */
0121: public lr_parser() {
0122: /* nothing to do here */
0123: }
0124:
0125: /** Constructor that sets the default scanner. [CSA/davidm] */
0126: public lr_parser(Scanner s) {
0127: this (); /* in case default constructor someday does something */
0128: setScanner(s);
0129: }
0130:
0131: /*-----------------------------------------------------------*/
0132: /*--- (Access to) Static (Class) Variables ------------------*/
0133: /*-----------------------------------------------------------*/
0134:
0135: /** The default number of Symbols after an error we much match to consider
0136: * it recovered from.
0137: */
0138: protected final static int _error_sync_size = 3;
0139:
0140: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0141:
0142: /** The number of Symbols after an error we much match to consider it
0143: * recovered from.
0144: */
0145: protected int error_sync_size() {
0146: return _error_sync_size;
0147: }
0148:
0149: /*-----------------------------------------------------------*/
0150: /*--- (Access to) Instance Variables ------------------------*/
0151: /*-----------------------------------------------------------*/
0152:
0153: /** Table of production information (supplied by generated subclass).
0154: * This table contains one entry per production and is indexed by
0155: * the negative-encoded values (reduce actions) in the action_table.
0156: * Each entry has two parts, the index of the non-terminal on the
0157: * left hand side of the production, and the number of Symbols
0158: * on the right hand side.
0159: */
0160: public abstract short[][] production_table();
0161:
0162: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0163:
0164: /** The action table (supplied by generated subclass). This table is
0165: * indexed by state and terminal number indicating what action is to
0166: * be taken when the parser is in the given state (i.e., the given state
0167: * is on top of the stack) and the given terminal is next on the input.
0168: * States are indexed using the first dimension, however, the entries for
0169: * a given state are compacted and stored in adjacent index, value pairs
0170: * which are searched for rather than accessed directly (see get_action()).
0171: * The actions stored in the table will be either shifts, reduces, or
0172: * errors. Shifts are encoded as positive values (one greater than the
0173: * state shifted to). Reduces are encoded as negative values (one less
0174: * than the production reduced by). Error entries are denoted by zero.
0175: *
0176: * @see java_cup.runtime.lr_parser#get_action
0177: */
0178: public abstract short[][] action_table();
0179:
0180: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0181:
0182: /** The reduce-goto table (supplied by generated subclass). This
0183: * table is indexed by state and non-terminal number and contains
0184: * state numbers. States are indexed using the first dimension, however,
0185: * the entries for a given state are compacted and stored in adjacent
0186: * index, value pairs which are searched for rather than accessed
0187: * directly (see get_reduce()). When a reduce occurs, the handle
0188: * (corresponding to the RHS of the matched production) is popped off
0189: * the stack. The new top of stack indicates a state. This table is
0190: * then indexed by that state and the LHS of the reducing production to
0191: * indicate where to "shift" to.
0192: *
0193: * @see java_cup.runtime.lr_parser#get_reduce
0194: */
0195: public abstract short[][] reduce_table();
0196:
0197: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0198:
0199: /** The index of the start state (supplied by generated subclass). */
0200: public abstract int start_state();
0201:
0202: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0203:
0204: /** The index of the start production (supplied by generated subclass). */
0205: public abstract int start_production();
0206:
0207: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0208:
0209: /** The index of the end of file terminal Symbol (supplied by generated
0210: * subclass).
0211: */
0212: public abstract int EOF_sym();
0213:
0214: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0215:
0216: /** The index of the special error Symbol (supplied by generated subclass). */
0217: public abstract int error_sym();
0218:
0219: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0220:
0221: /** Internal flag to indicate when parser should quit. */
0222: protected boolean _done_parsing = false;
0223:
0224: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0225:
0226: /** This method is called to indicate that the parser should quit. This is
0227: * normally called by an accept action, but can be used to cancel parsing
0228: * early in other circumstances if desired.
0229: */
0230: public void done_parsing() {
0231: _done_parsing = true;
0232: }
0233:
0234: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0235: /* Global parse state shared by parse(), error recovery, and
0236: * debugging routines */
0237: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0238:
0239: /** Indication of the index for top of stack (for use by actions). */
0240: protected int tos;
0241:
0242: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0243:
0244: /** The current lookahead Symbol. */
0245: protected Symbol cur_token;
0246:
0247: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0248:
0249: /** The parse stack itself. */
0250: protected Stack stack = new Stack();
0251:
0252: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0253:
0254: /** Direct reference to the production table. */
0255: protected short[][] production_tab;
0256:
0257: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0258:
0259: /** Direct reference to the action table. */
0260: protected short[][] action_tab;
0261:
0262: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0263:
0264: /** Direct reference to the reduce-goto table. */
0265: protected short[][] reduce_tab;
0266:
0267: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0268:
0269: /** This is the scanner object used by the default implementation
0270: * of scan() to get Symbols. To avoid name conflicts with existing
0271: * code, this field is private. [CSA/davidm] */
0272: private Scanner _scanner;
0273:
0274: /**
0275: * Simple accessor method to set the default scanner.
0276: */
0277: public void setScanner(Scanner s) {
0278: _scanner = s;
0279: }
0280:
0281: /**
0282: * Simple accessor method to get the default scanner.
0283: */
0284: public Scanner getScanner() {
0285: return _scanner;
0286: }
0287:
0288: /*-----------------------------------------------------------*/
0289: /*--- General Methods ---------------------------------------*/
0290: /*-----------------------------------------------------------*/
0291:
0292: /** Perform a bit of user supplied action code (supplied by generated
0293: * subclass). Actions are indexed by an internal action number assigned
0294: * at parser generation time.
0295: *
0296: * @param act_num the internal index of the action to be performed.
0297: * @param parser the parser object we are acting for.
0298: * @param stack the parse stack of that object.
0299: * @param top the index of the top element of the parse stack.
0300: */
0301: public abstract Symbol do_action(int act_num, lr_parser parser,
0302: Stack stack, int top) throws java.lang.Exception;
0303:
0304: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0305:
0306: /** User code for initialization inside the parser. Typically this
0307: * initializes the scanner. This is called before the parser requests
0308: * the first Symbol. Here this is just a placeholder for subclasses that
0309: * might need this and we perform no action. This method is normally
0310: * overridden by the generated code using this contents of the "init with"
0311: * clause as its body.
0312: */
0313: public void user_init() throws java.lang.Exception {
0314: }
0315:
0316: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0317:
0318: /** Initialize the action object. This is called before the parser does
0319: * any parse actions. This is filled in by generated code to create
0320: * an object that encapsulates all action code.
0321: */
0322: protected abstract void init_actions() throws java.lang.Exception;
0323:
0324: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0325:
0326: /** Get the next Symbol from the input (supplied by generated subclass).
0327: * Once end of file has been reached, all subsequent calls to scan
0328: * should return an EOF Symbol (which is Symbol number 0). By default
0329: * this method returns getScanner().next_token(); this implementation
0330: * can be overriden by the generated parser using the code declared in
0331: * the "scan with" clause. Do not recycle objects; every call to
0332: * scan() should return a fresh object.
0333: */
0334: public Symbol scan() throws java.lang.Exception {
0335: return getScanner().next_token();
0336: }
0337:
0338: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0339:
0340: /** Report a fatal error. This method takes a message string and an
0341: * additional object (to be used by specializations implemented in
0342: * subclasses). Here in the base class a very simple implementation
0343: * is provided which reports the error then throws an exception.
0344: *
0345: * @param message an error message.
0346: * @param info an extra object reserved for use by specialized subclasses.
0347: */
0348: public void report_fatal_error(String message, Object info)
0349: throws java.lang.Exception {
0350: /* stop parsing (not really necessary since we throw an exception, but) */
0351: done_parsing();
0352:
0353: /* use the normal error message reporting to put out the message */
0354: report_error(message, info);
0355:
0356: /* throw an exception */
0357: throw new Exception("Can't recover from previous error(s)");
0358: }
0359:
0360: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0361:
0362: /** Report a non fatal error (or warning). This method takes a message
0363: * string and an additional object (to be used by specializations
0364: * implemented in subclasses). Here in the base class a very simple
0365: * implementation is provided which simply prints the message to
0366: * System.err.
0367: *
0368: * @param message an error message.
0369: * @param info an extra object reserved for use by specialized subclasses.
0370: */
0371: public void report_error(String message, Object info) {
0372: System.err.print(message);
0373: if (info instanceof Symbol)
0374: if (((Symbol) info).left != -1)
0375: System.err.println(" at character "
0376: + ((Symbol) info).left + " of input");
0377: else
0378: System.err.println("");
0379: else
0380: System.err.println("");
0381: }
0382:
0383: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0384:
0385: /** This method is called when a syntax error has been detected and recovery
0386: * is about to be invoked. Here in the base class we just emit a
0387: * "Syntax error" error message.
0388: *
0389: * @param cur_token the current lookahead Symbol.
0390: */
0391: public void syntax_error(Symbol cur_token) {
0392: report_error("Syntax error", cur_token);
0393: }
0394:
0395: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0396:
0397: /** This method is called if it is determined that syntax error recovery
0398: * has been unsuccessful. Here in the base class we report a fatal error.
0399: *
0400: * @param cur_token the current lookahead Symbol.
0401: */
0402: public void unrecovered_syntax_error(Symbol cur_token)
0403: throws java.lang.Exception {
0404: report_fatal_error("Couldn't repair and continue parse",
0405: cur_token);
0406: }
0407:
0408: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0409:
0410: /** Fetch an action from the action table. The table is broken up into
0411: * rows, one per state (rows are indexed directly by state number).
0412: * Within each row, a list of index, value pairs are given (as sequential
0413: * entries in the table), and the list is terminated by a default entry
0414: * (denoted with a Symbol index of -1). To find the proper entry in a row
0415: * we do a linear or binary search (depending on the size of the row).
0416: *
0417: * @param state the state index of the action being accessed.
0418: * @param sym the Symbol index of the action being accessed.
0419: */
0420: protected final short get_action(int state, int sym) {
0421: short tag;
0422: int first, last, probe;
0423: short[] row = action_tab[state];
0424:
0425: /* linear search if we are < 10 entries */
0426: if (row.length < 20)
0427: for (probe = 0; probe < row.length; probe++) {
0428: /* is this entry labeled with our Symbol or the default? */
0429: tag = row[probe++];
0430: if (tag == sym || tag == -1) {
0431: /* return the next entry */
0432: return row[probe];
0433: }
0434: }
0435: /* otherwise binary search */
0436: else {
0437: first = 0;
0438: last = (row.length - 1) / 2 - 1; /* leave out trailing default entry */
0439: while (first <= last) {
0440: probe = (first + last) / 2;
0441: if (sym == row[probe * 2])
0442: return row[probe * 2 + 1];
0443: else if (sym > row[probe * 2])
0444: first = probe + 1;
0445: else
0446: last = probe - 1;
0447: }
0448:
0449: /* not found, use the default at the end */
0450: return row[row.length - 1];
0451: }
0452:
0453: /* shouldn't happened, but if we run off the end we return the
0454: default (error == 0) */
0455: return 0;
0456: }
0457:
0458: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0459:
0460: /** Fetch a state from the reduce-goto table. The table is broken up into
0461: * rows, one per state (rows are indexed directly by state number).
0462: * Within each row, a list of index, value pairs are given (as sequential
0463: * entries in the table), and the list is terminated by a default entry
0464: * (denoted with a Symbol index of -1). To find the proper entry in a row
0465: * we do a linear search.
0466: *
0467: * @param state the state index of the entry being accessed.
0468: * @param sym the Symbol index of the entry being accessed.
0469: */
0470: protected final short get_reduce(int state, int sym) {
0471: short tag;
0472: short[] row = reduce_tab[state];
0473:
0474: /* if we have a null row we go with the default */
0475: if (row == null)
0476: return -1;
0477:
0478: for (int probe = 0; probe < row.length; probe++) {
0479: /* is this entry labeled with our Symbol or the default? */
0480: tag = row[probe++];
0481: if (tag == sym || tag == -1) {
0482: /* return the next entry */
0483: return row[probe];
0484: }
0485: }
0486: /* if we run off the end we return the default (error == -1) */
0487: return -1;
0488: }
0489:
0490: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0491:
0492: /** This method provides the main parsing routine. It returns only when
0493: * done_parsing() has been called (typically because the parser has
0494: * accepted, or a fatal error has been reported). See the header
0495: * documentation for the class regarding how shift/reduce parsers operate
0496: * and how the various tables are used.
0497: */
0498: public Symbol parse() throws java.lang.Exception {
0499: /* the current action code */
0500: int act;
0501:
0502: /* the Symbol/stack element returned by a reduce */
0503: Symbol lhs_sym = null;
0504:
0505: /* information about production being reduced with */
0506: short handle_size, lhs_sym_num;
0507:
0508: /* set up direct reference to tables to drive the parser */
0509:
0510: production_tab = production_table();
0511: action_tab = action_table();
0512: reduce_tab = reduce_table();
0513:
0514: /* initialize the action encapsulation object */
0515: init_actions();
0516:
0517: /* do user initialization */
0518: user_init();
0519:
0520: /* get the first token */
0521: cur_token = scan();
0522:
0523: /* push dummy Symbol with start state to get us underway */
0524: stack.removeAllElements();
0525: stack.push(new Symbol(0, start_state()));
0526: tos = 0;
0527:
0528: /* continue until we are told to stop */
0529: for (_done_parsing = false; !_done_parsing;) {
0530: /* Check current token for freshness. */
0531: if (cur_token.used_by_parser)
0532: throw new Error(
0533: "Symbol recycling detected (fix your scanner).");
0534:
0535: /* current state is always on the top of the stack */
0536:
0537: /* look up action out of the current state with the current input */
0538: act = get_action(((Symbol) stack.peek()).parse_state,
0539: cur_token.sym);
0540:
0541: /* decode the action -- > 0 encodes shift */
0542: if (act > 0) {
0543: /* shift to the encoded state by pushing it on the stack */
0544: cur_token.parse_state = act - 1;
0545: cur_token.used_by_parser = true;
0546: stack.push(cur_token);
0547: tos++;
0548:
0549: /* advance to the next Symbol */
0550: cur_token = scan();
0551: }
0552: /* if its less than zero, then it encodes a reduce action */
0553: else if (act < 0) {
0554: /* perform the action for the reduce */
0555: lhs_sym = do_action((-act) - 1, this , stack, tos);
0556:
0557: /* look up information about the production */
0558: lhs_sym_num = production_tab[(-act) - 1][0];
0559: handle_size = production_tab[(-act) - 1][1];
0560:
0561: /* pop the handle off the stack */
0562: for (int i = 0; i < handle_size; i++) {
0563: stack.pop();
0564: tos--;
0565: }
0566:
0567: /* look up the state to go to from the one popped back to */
0568: act = get_reduce(((Symbol) stack.peek()).parse_state,
0569: lhs_sym_num);
0570:
0571: /* shift to that state */
0572: lhs_sym.parse_state = act;
0573: lhs_sym.used_by_parser = true;
0574: stack.push(lhs_sym);
0575: tos++;
0576: }
0577: /* finally if the entry is zero, we have an error */
0578: else if (act == 0) {
0579: /* call user syntax error reporting routine */
0580: syntax_error(cur_token);
0581:
0582: /* try to error recover */
0583: if (!error_recovery(false)) {
0584: /* if that fails give up with a fatal syntax error */
0585: unrecovered_syntax_error(cur_token);
0586:
0587: /* just in case that wasn't fatal enough, end parse */
0588: done_parsing();
0589: } else {
0590: lhs_sym = (Symbol) stack.peek();
0591: }
0592: }
0593: }
0594: return lhs_sym;
0595: }
0596:
0597: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0598:
0599: /** Write a debugging message to System.err for the debugging version
0600: * of the parser.
0601: *
0602: * @param mess the text of the debugging message.
0603: */
0604: public void debug_message(String mess) {
0605: System.err.println(mess);
0606: }
0607:
0608: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0609:
0610: /** Dump the parse stack for debugging purposes. */
0611: public void dump_stack() {
0612: if (stack == null) {
0613: debug_message("# Stack dump requested, but stack is null");
0614: return;
0615: }
0616:
0617: debug_message("============ Parse Stack Dump ============");
0618:
0619: /* dump the stack */
0620: for (int i = 0; i < stack.size(); i++) {
0621: debug_message("Symbol: "
0622: + ((Symbol) stack.elementAt(i)).sym + " State: "
0623: + ((Symbol) stack.elementAt(i)).parse_state);
0624: }
0625: debug_message("==========================================");
0626: }
0627:
0628: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0629:
0630: /** Do debug output for a reduce.
0631: *
0632: * @param prod_num the production we are reducing with.
0633: * @param nt_num the index of the LHS non terminal.
0634: * @param rhs_size the size of the RHS.
0635: */
0636: public void debug_reduce(int prod_num, int nt_num, int rhs_size) {
0637: debug_message("# Reduce with prod #" + prod_num + " [NT="
0638: + nt_num + ", " + "SZ=" + rhs_size + "]");
0639: }
0640:
0641: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0642:
0643: /** Do debug output for shift.
0644: *
0645: * @param shift_tkn the Symbol being shifted onto the stack.
0646: */
0647: public void debug_shift(Symbol shift_tkn) {
0648: debug_message("# Shift under term #" + shift_tkn.sym
0649: + " to state #" + shift_tkn.parse_state);
0650: }
0651:
0652: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0653:
0654: /** Do debug output for stack state. [CSA]
0655: */
0656: public void debug_stack() {
0657: StringBuffer sb = new StringBuffer("## STACK:");
0658: for (int i = 0; i < stack.size(); i++) {
0659: Symbol s = (Symbol) stack.elementAt(i);
0660: sb.append(" <state " + s.parse_state + ", sym " + s.sym
0661: + ">");
0662: if ((i % 3) == 2 || (i == (stack.size() - 1))) {
0663: debug_message(sb.toString());
0664: sb = new StringBuffer(" ");
0665: }
0666: }
0667: }
0668:
0669: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0670:
0671: /** Perform a parse with debugging output. This does exactly the
0672: * same things as parse(), except that it calls debug_shift() and
0673: * debug_reduce() when shift and reduce moves are taken by the parser
0674: * and produces various other debugging messages.
0675: */
0676: public Symbol debug_parse() throws java.lang.Exception {
0677: /* the current action code */
0678: int act;
0679:
0680: /* the Symbol/stack element returned by a reduce */
0681: Symbol lhs_sym = null;
0682:
0683: /* information about production being reduced with */
0684: short handle_size, lhs_sym_num;
0685:
0686: /* set up direct reference to tables to drive the parser */
0687: production_tab = production_table();
0688: action_tab = action_table();
0689: reduce_tab = reduce_table();
0690:
0691: debug_message("# Initializing parser");
0692:
0693: /* initialize the action encapsulation object */
0694: init_actions();
0695:
0696: /* do user initialization */
0697: user_init();
0698:
0699: /* the current Symbol */
0700: cur_token = scan();
0701:
0702: debug_message("# Current Symbol is #" + cur_token.sym);
0703:
0704: /* push dummy Symbol with start state to get us underway */
0705: stack.removeAllElements();
0706: stack.push(new Symbol(0, start_state()));
0707: tos = 0;
0708:
0709: /* continue until we are told to stop */
0710: for (_done_parsing = false; !_done_parsing;) {
0711: /* Check current token for freshness. */
0712: if (cur_token.used_by_parser)
0713: throw new Error(
0714: "Symbol recycling detected (fix your scanner).");
0715:
0716: /* current state is always on the top of the stack */
0717: //debug_stack();
0718: /* look up action out of the current state with the current input */
0719: act = get_action(((Symbol) stack.peek()).parse_state,
0720: cur_token.sym);
0721:
0722: /* decode the action -- > 0 encodes shift */
0723: if (act > 0) {
0724: /* shift to the encoded state by pushing it on the stack */
0725: cur_token.parse_state = act - 1;
0726: cur_token.used_by_parser = true;
0727: debug_shift(cur_token);
0728: stack.push(cur_token);
0729: tos++;
0730:
0731: /* advance to the next Symbol */
0732: cur_token = scan();
0733: debug_message("# Current token is " + cur_token);
0734: }
0735: /* if its less than zero, then it encodes a reduce action */
0736: else if (act < 0) {
0737: /* perform the action for the reduce */
0738: lhs_sym = do_action((-act) - 1, this , stack, tos);
0739:
0740: /* look up information about the production */
0741: lhs_sym_num = production_tab[(-act) - 1][0];
0742: handle_size = production_tab[(-act) - 1][1];
0743:
0744: debug_reduce((-act) - 1, lhs_sym_num, handle_size);
0745:
0746: /* pop the handle off the stack */
0747: for (int i = 0; i < handle_size; i++) {
0748: stack.pop();
0749: tos--;
0750: }
0751:
0752: /* look up the state to go to from the one popped back to */
0753: act = get_reduce(((Symbol) stack.peek()).parse_state,
0754: lhs_sym_num);
0755: debug_message("# Reduce rule: top state "
0756: + ((Symbol) stack.peek()).parse_state
0757: + ", lhs sym " + lhs_sym_num + " -> state "
0758: + act);
0759:
0760: /* shift to that state */
0761: lhs_sym.parse_state = act;
0762: lhs_sym.used_by_parser = true;
0763: stack.push(lhs_sym);
0764: tos++;
0765:
0766: debug_message("# Goto state #" + act);
0767: }
0768: /* finally if the entry is zero, we have an error */
0769: else if (act == 0) {
0770: /* call user syntax error reporting routine */
0771: syntax_error(cur_token);
0772:
0773: /* try to error recover */
0774: if (!error_recovery(true)) {
0775: /* if that fails give up with a fatal syntax error */
0776: unrecovered_syntax_error(cur_token);
0777:
0778: /* just in case that wasn't fatal enough, end parse */
0779: done_parsing();
0780: } else {
0781: lhs_sym = (Symbol) stack.peek();
0782: }
0783: }
0784: }
0785: return lhs_sym;
0786: }
0787:
0788: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0789: /* Error recovery code */
0790: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0791:
0792: /** Attempt to recover from a syntax error. This returns false if recovery
0793: * fails, true if it succeeds. Recovery happens in 4 steps. First we
0794: * pop the parse stack down to a point at which we have a shift out
0795: * of the top-most state on the error Symbol. This represents the
0796: * initial error recovery configuration. If no such configuration is
0797: * found, then we fail. Next a small number of "lookahead" or "parse
0798: * ahead" Symbols are read into a buffer. The size of this buffer is
0799: * determined by error_sync_size() and determines how many Symbols beyond
0800: * the error must be matched to consider the recovery a success. Next,
0801: * we begin to discard Symbols in attempt to get past the point of error
0802: * to a point where we can continue parsing. After each Symbol, we attempt
0803: * to "parse ahead" though the buffered lookahead Symbols. The "parse ahead"
0804: * process simulates that actual parse, but does not modify the real
0805: * parser's configuration, nor execute any actions. If we can parse all
0806: * the stored Symbols without error, then the recovery is considered a
0807: * success. Once a successful recovery point is determined, we do an
0808: * actual parse over the stored input -- modifying the real parse
0809: * configuration and executing all actions. Finally, we return the the
0810: * normal parser to continue with the overall parse.
0811: *
0812: * @param debug should we produce debugging messages as we parse.
0813: */
0814: protected boolean error_recovery(boolean debug)
0815: throws java.lang.Exception {
0816: if (debug)
0817: debug_message("# Attempting error recovery");
0818:
0819: /* first pop the stack back into a state that can shift on error and
0820: do that shift (if that fails, we fail) */
0821: if (!find_recovery_config(debug)) {
0822: if (debug)
0823: debug_message("# Error recovery fails");
0824: return false;
0825: }
0826:
0827: /* read ahead to create lookahead we can parse multiple times */
0828: read_lookahead();
0829:
0830: /* repeatedly try to parse forward until we make it the required dist */
0831: for (;;) {
0832: /* try to parse forward, if it makes it, bail out of loop */
0833: if (debug)
0834: debug_message("# Trying to parse ahead");
0835: if (try_parse_ahead(debug)) {
0836: break;
0837: }
0838:
0839: /* if we are now at EOF, we have failed */
0840: if (lookahead[0].sym == EOF_sym()) {
0841: if (debug)
0842: debug_message("# Error recovery fails at EOF");
0843: return false;
0844: }
0845:
0846: /* otherwise, we consume another Symbol and try again */
0847: if (debug)
0848: debug_message("# Consuming Symbol #"
0849: + cur_err_token().sym);
0850: restart_lookahead();
0851: }
0852:
0853: /* we have consumed to a point where we can parse forward */
0854: if (debug)
0855: debug_message("# Parse-ahead ok, going back to normal parse");
0856:
0857: /* do the real parse (including actions) across the lookahead */
0858: parse_lookahead(debug);
0859:
0860: /* we have success */
0861: return true;
0862: }
0863:
0864: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0865:
0866: /** Determine if we can shift under the special error Symbol out of the
0867: * state currently on the top of the (real) parse stack.
0868: */
0869: protected boolean shift_under_error() {
0870: /* is there a shift under error Symbol */
0871: return get_action(((Symbol) stack.peek()).parse_state,
0872: error_sym()) > 0;
0873: }
0874:
0875: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0876:
0877: /** Put the (real) parse stack into error recovery configuration by
0878: * popping the stack down to a state that can shift on the special
0879: * error Symbol, then doing the shift. If no suitable state exists on
0880: * the stack we return false
0881: *
0882: * @param debug should we produce debugging messages as we parse.
0883: */
0884: protected boolean find_recovery_config(boolean debug) {
0885: Symbol error_token;
0886: int act;
0887:
0888: if (debug)
0889: debug_message("# Finding recovery state on stack");
0890:
0891: /* Remember the right-position of the top symbol on the stack */
0892: int right_pos = ((Symbol) stack.peek()).right;
0893: int left_pos = ((Symbol) stack.peek()).left;
0894:
0895: /* pop down until we can shift under error Symbol */
0896: while (!shift_under_error()) {
0897: /* pop the stack */
0898: if (debug)
0899: debug_message("# Pop stack by one, state was # "
0900: + ((Symbol) stack.peek()).parse_state);
0901: left_pos = ((Symbol) stack.pop()).left;
0902: tos--;
0903:
0904: /* if we have hit bottom, we fail */
0905: if (stack.empty()) {
0906: if (debug)
0907: debug_message("# No recovery state found on stack");
0908: return false;
0909: }
0910: }
0911:
0912: /* state on top of the stack can shift under error, find the shift */
0913: act = get_action(((Symbol) stack.peek()).parse_state,
0914: error_sym());
0915: if (debug) {
0916: debug_message("# Recover state found (#"
0917: + ((Symbol) stack.peek()).parse_state + ")");
0918: debug_message("# Shifting on error to state #" + (act - 1));
0919: }
0920:
0921: /* build and shift a special error Symbol */
0922: error_token = new Symbol(error_sym(), left_pos, right_pos);
0923: error_token.parse_state = act - 1;
0924: error_token.used_by_parser = true;
0925: stack.push(error_token);
0926: tos++;
0927:
0928: return true;
0929: }
0930:
0931: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0932:
0933: /** Lookahead Symbols used for attempting error recovery "parse aheads". */
0934: protected Symbol lookahead[];
0935:
0936: /** Position in lookahead input buffer used for "parse ahead". */
0937: protected int lookahead_pos;
0938:
0939: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0940:
0941: /** Read from input to establish our buffer of "parse ahead" lookahead
0942: * Symbols.
0943: */
0944: protected void read_lookahead() throws java.lang.Exception {
0945: /* create the lookahead array */
0946: lookahead = new Symbol[error_sync_size()];
0947:
0948: /* fill in the array */
0949: for (int i = 0; i < error_sync_size(); i++) {
0950: lookahead[i] = cur_token;
0951: cur_token = scan();
0952: }
0953:
0954: /* start at the beginning */
0955: lookahead_pos = 0;
0956: }
0957:
0958: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0959:
0960: /** Return the current lookahead in our error "parse ahead" buffer. */
0961: protected Symbol cur_err_token() {
0962: return lookahead[lookahead_pos];
0963: }
0964:
0965: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0966:
0967: /** Advance to next "parse ahead" input Symbol. Return true if we have
0968: * input to advance to, false otherwise.
0969: */
0970: protected boolean advance_lookahead() {
0971: /* advance the input location */
0972: lookahead_pos++;
0973:
0974: /* return true if we didn't go off the end */
0975: return lookahead_pos < error_sync_size();
0976: }
0977:
0978: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0979:
0980: /** Reset the parse ahead input to one Symbol past where we started error
0981: * recovery (this consumes one new Symbol from the real input).
0982: */
0983: protected void restart_lookahead() throws java.lang.Exception {
0984: /* move all the existing input over */
0985: for (int i = 1; i < error_sync_size(); i++)
0986: lookahead[i - 1] = lookahead[i];
0987:
0988: /* read a new Symbol into the last spot */
0989: cur_token = scan();
0990: lookahead[error_sync_size() - 1] = cur_token;
0991:
0992: /* reset our internal position marker */
0993: lookahead_pos = 0;
0994: }
0995:
0996: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
0997:
0998: /** Do a simulated parse forward (a "parse ahead") from the current
0999: * stack configuration using stored lookahead input and a virtual parse
1000: * stack. Return true if we make it all the way through the stored
1001: * lookahead input without error. This basically simulates the action of
1002: * parse() using only our saved "parse ahead" input, and not executing any
1003: * actions.
1004: *
1005: * @param debug should we produce debugging messages as we parse.
1006: */
1007: protected boolean try_parse_ahead(boolean debug)
1008: throws java.lang.Exception {
1009: int act;
1010: short lhs, rhs_size;
1011:
1012: /* create a virtual stack from the real parse stack */
1013: virtual_parse_stack vstack = new virtual_parse_stack(stack);
1014:
1015: /* parse until we fail or get past the lookahead input */
1016: for (;;) {
1017: /* look up the action from the current state (on top of stack) */
1018: act = get_action(vstack.top(), cur_err_token().sym);
1019:
1020: /* if its an error, we fail */
1021: if (act == 0)
1022: return false;
1023:
1024: /* > 0 encodes a shift */
1025: if (act > 0) {
1026: /* push the new state on the stack */
1027: vstack.push(act - 1);
1028:
1029: if (debug)
1030: debug_message("# Parse-ahead shifts Symbol #"
1031: + cur_err_token().sym + " into state #"
1032: + (act - 1));
1033:
1034: /* advance simulated input, if we run off the end, we are done */
1035: if (!advance_lookahead())
1036: return true;
1037: }
1038: /* < 0 encodes a reduce */
1039: else {
1040: /* if this is a reduce with the start production we are done */
1041: if ((-act) - 1 == start_production()) {
1042: if (debug)
1043: debug_message("# Parse-ahead accepts");
1044: return true;
1045: }
1046:
1047: /* get the lhs Symbol and the rhs size */
1048: lhs = production_tab[(-act) - 1][0];
1049: rhs_size = production_tab[(-act) - 1][1];
1050:
1051: /* pop handle off the stack */
1052: for (int i = 0; i < rhs_size; i++)
1053: vstack.pop();
1054:
1055: if (debug)
1056: debug_message("# Parse-ahead reduces: handle size = "
1057: + rhs_size
1058: + " lhs = #"
1059: + lhs
1060: + " from state #" + vstack.top());
1061:
1062: /* look up goto and push it onto the stack */
1063: vstack.push(get_reduce(vstack.top(), lhs));
1064: if (debug)
1065: debug_message("# Goto state #" + vstack.top());
1066: }
1067: }
1068: }
1069:
1070: /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
1071:
1072: /** Parse forward using stored lookahead Symbols. In this case we have
1073: * already verified that parsing will make it through the stored lookahead
1074: * Symbols and we are now getting back to the point at which we can hand
1075: * control back to the normal parser. Consequently, this version of the
1076: * parser performs all actions and modifies the real parse configuration.
1077: * This returns once we have consumed all the stored input or we accept.
1078: *
1079: * @param debug should we produce debugging messages as we parse.
1080: */
1081: protected void parse_lookahead(boolean debug)
1082: throws java.lang.Exception {
1083: /* the current action code */
1084: int act;
1085:
1086: /* the Symbol/stack element returned by a reduce */
1087: Symbol lhs_sym = null;
1088:
1089: /* information about production being reduced with */
1090: short handle_size, lhs_sym_num;
1091:
1092: /* restart the saved input at the beginning */
1093: lookahead_pos = 0;
1094:
1095: if (debug) {
1096: debug_message("# Reparsing saved input with actions");
1097: debug_message("# Current Symbol is #" + cur_err_token().sym);
1098: debug_message("# Current state is #"
1099: + ((Symbol) stack.peek()).parse_state);
1100: }
1101:
1102: /* continue until we accept or have read all lookahead input */
1103: while (!_done_parsing) {
1104: /* current state is always on the top of the stack */
1105:
1106: /* look up action out of the current state with the current input */
1107: act = get_action(((Symbol) stack.peek()).parse_state,
1108: cur_err_token().sym);
1109:
1110: /* decode the action -- > 0 encodes shift */
1111: if (act > 0) {
1112: /* shift to the encoded state by pushing it on the stack */
1113: cur_err_token().parse_state = act - 1;
1114: cur_err_token().used_by_parser = true;
1115: if (debug)
1116: debug_shift(cur_err_token());
1117: stack.push(cur_err_token());
1118: tos++;
1119:
1120: /* advance to the next Symbol, if there is none, we are done */
1121: if (!advance_lookahead()) {
1122: if (debug)
1123: debug_message("# Completed reparse");
1124:
1125: /* scan next Symbol so we can continue parse */
1126: // BUGFIX by Chris Harris <ckharris@ucsd.edu>:
1127: // correct a one-off error by commenting out
1128: // this next line.
1129: /*cur_token = scan();*/
1130:
1131: /* go back to normal parser */
1132: return;
1133: }
1134:
1135: if (debug)
1136: debug_message("# Current Symbol is #"
1137: + cur_err_token().sym);
1138: }
1139: /* if its less than zero, then it encodes a reduce action */
1140: else if (act < 0) {
1141: /* perform the action for the reduce */
1142: lhs_sym = do_action((-act) - 1, this , stack, tos);
1143:
1144: /* look up information about the production */
1145: lhs_sym_num = production_tab[(-act) - 1][0];
1146: handle_size = production_tab[(-act) - 1][1];
1147:
1148: if (debug)
1149: debug_reduce((-act) - 1, lhs_sym_num, handle_size);
1150:
1151: /* pop the handle off the stack */
1152: for (int i = 0; i < handle_size; i++) {
1153: stack.pop();
1154: tos--;
1155: }
1156:
1157: /* look up the state to go to from the one popped back to */
1158: act = get_reduce(((Symbol) stack.peek()).parse_state,
1159: lhs_sym_num);
1160:
1161: /* shift to that state */
1162: lhs_sym.parse_state = act;
1163: lhs_sym.used_by_parser = true;
1164: stack.push(lhs_sym);
1165: tos++;
1166:
1167: if (debug)
1168: debug_message("# Goto state #" + act);
1169:
1170: }
1171: /* finally if the entry is zero, we have an error
1172: (shouldn't happen here, but...)*/
1173: else if (act == 0) {
1174: report_fatal_error("Syntax error", lhs_sym);
1175: return;
1176: }
1177: }
1178:
1179: }
1180:
1181: /*-----------------------------------------------------------*/
1182:
1183: /** Utility function: unpacks parse tables from strings */
1184: protected static short[][] unpackFromStrings(String[] sa) {
1185: // Concatanate initialization strings.
1186: StringBuffer sb = new StringBuffer(sa[0]);
1187: for (int i = 1; i < sa.length; i++)
1188: sb.append(sa[i]);
1189: int n = 0; // location in initialization string
1190: int size1 = (((int) sb.charAt(n)) << 16)
1191: | ((int) sb.charAt(n + 1));
1192: n += 2;
1193: short[][] result = new short[size1][];
1194: for (int i = 0; i < size1; i++) {
1195: int size2 = (((int) sb.charAt(n)) << 16)
1196: | ((int) sb.charAt(n + 1));
1197: n += 2;
1198: result[i] = new short[size2];
1199: for (int j = 0; j < size2; j++)
1200: result[i][j] = (short) (sb.charAt(n++) - 2);
1201: }
1202: return result;
1203: }
1204: }
|