2 package java_cup.runtime;
4 import java.util.Stack;
6 /** This class implements a skeleton table driven LR parser. In general,
7 * LR parsers are a form of bottom up shift-reduce parsers. Shift-reduce
8 * parsers act by shifting input onto a parse stack until the Symbols
9 * matching the right hand side of a production appear on the top of the
10 * stack. Once this occurs, a reduce is performed. This involves removing
11 * the Symbols corresponding to the right hand side of the production
12 * (the so called "handle") and replacing them with the non-terminal from
13 * the left hand side of the production. <p>
15 * To control the decision of whether to shift or reduce at any given point,
16 * the parser uses a state machine (the "viable prefix recognition machine"
17 * built by the parser generator). The current state of the machine is placed
18 * on top of the parse stack (stored as part of a Symbol object representing
19 * a terminal or non terminal). The parse action table is consulted
20 * (using the current state and the current lookahead Symbol as indexes) to
21 * determine whether to shift or to reduce. When the parser shifts, it
22 * changes to a new state by pushing a new Symbol (containing a new state)
23 * onto the stack. When the parser reduces, it pops the handle (right hand
24 * side of a production) off the stack. This leaves the parser in the state
25 * it was in before any of those Symbols were matched. Next the reduce-goto
26 * table is consulted (using the new state and current lookahead Symbol as
27 * indexes) to determine a new state to go to. The parser then shifts to
28 * this goto state by pushing the left hand side Symbol of the production
29 * (also containing the new state) onto the stack.<p>
31 * This class actually provides four LR parsers. The methods parse() and
32 * debug_parse() provide two versions of the main parser (the only difference
33 * being that debug_parse() emits debugging trace messages as it parses).
34 * In addition to these main parsers, the error recovery mechanism uses two
35 * more. One of these is used to simulate "parsing ahead" in the input
36 * without carrying out actions (to verify that a potential error recovery
37 * has worked), and the other is used to parse through buffered "parse ahead"
38 * input in order to execute all actions and re-synchronize the actual parser
41 * This is an abstract class which is normally filled out by a subclass
42 * generated by the JavaCup parser generator. In addition to supplying
43 * the actual parse tables, generated code also supplies methods which
44 * invoke various pieces of user supplied code, provide access to certain
45 * special Symbols (e.g., EOF and error), etc. Specifically, the following
46 * abstract methods are normally supplied by generated code:
48 * <dt> short[][] production_table()
49 * <dd> Provides a reference to the production table (indicating the index of
50 * the left hand side non terminal and the length of the right hand side
51 * for each production in the grammar).
52 * <dt> short[][] action_table()
53 * <dd> Provides a reference to the parse action table.
54 * <dt> short[][] reduce_table()
55 * <dd> Provides a reference to the reduce-goto table.
56 * <dt> int start_state()
57 * <dd> Indicates the index of the start state.
58 * <dt> int start_production()
59 * <dd> Indicates the index of the starting production.
61 * <dd> Indicates the index of the EOF Symbol.
62 * <dt> int error_sym()
63 * <dd> Indicates the index of the error Symbol.
64 * <dt> Symbol do_action()
65 * <dd> Executes a piece of user supplied action code. This always comes at
66 * the point of a reduce in the parse, so this code also allocates and
67 * fills in the left hand side non terminal Symbol object that is to be
68 * pushed onto the stack for the reduce.
69 * <dt> void init_actions()
70 * <dd> Code to initialize a special object that encapsulates user supplied
71 * actions (this object is used by do_action() to actually carry out the
75 * In addition to these routines that <i>must</i> be supplied by the
76 * generated subclass there are also a series of routines that <i>may</i>
77 * be supplied. These include:
80 * <dd> Used to get the next input Symbol from the scanner.
81 * <dt> Scanner getScanner()
82 * <dd> Used to provide a scanner for the default implementation of
84 * <dt> int error_sync_size()
85 * <dd> This determines how many Symbols past the point of an error
86 * must be parsed without error in order to consider a recovery to
87 * be valid. This defaults to 3. Values less than 2 are not
89 * <dt> void report_error(String message, Object info)
90 * <dd> This method is called to report an error. The default implementation
91 * simply prints a message to System.err and where the error occurred.
92 * This method is often replaced in order to provide a more sophisticated
93 * error reporting mechanism.
94 * <dt> void report_fatal_error(String message, Object info)
95 * <dd> This method is called when a fatal error that cannot be recovered from
96 * is encountered. In the default implementation, it calls
97 * report_error() to emit a message, then throws an exception.
98 * <dt> void syntax_error(Symbol cur_token)
99 * <dd> This method is called as soon as syntax error is detected (but
100 * before recovery is attempted). In the default implementation it
101 * invokes: report_error("Syntax error", null);
102 * <dt> void unrecovered_syntax_error(Symbol cur_token)
103 * <dd> This method is called if syntax error recovery fails. In the default
104 * implementation it invokes:<br>
105 * report_fatal_error("Couldn't repair and continue parse", null);
108 * @see java_cup.runtime.Symbol
109 * @see java_cup.runtime.Symbol
110 * @see java_cup.runtime.virtual_parse_stack
111 * @version last updated: 7/3/96
112 * @author Frank Flannery
115 public abstract class lr_parser {
117 /*-----------------------------------------------------------*/
118 /*--- Constructor(s) ----------------------------------------*/
119 /*-----------------------------------------------------------*/
121 /** Simple constructor. */
124 /* nothing to do here */
127 /** Constructor that sets the default scanner. [CSA/davidm] */
128 public lr_parser(Scanner s) {
129 this(); /* in case default constructor someday does something */
133 /*-----------------------------------------------------------*/
134 /*--- (Access to) Static (Class) Variables ------------------*/
135 /*-----------------------------------------------------------*/
137 /** The default number of Symbols after an error we much match to consider
140 protected final static int _error_sync_size = 3;
142 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
144 /** The number of Symbols after an error we much match to consider it
147 protected int error_sync_size() {return _error_sync_size; }
149 /*-----------------------------------------------------------*/
150 /*--- (Access to) Instance Variables ------------------------*/
151 /*-----------------------------------------------------------*/
153 /** Table of production information (supplied by generated subclass).
154 * This table contains one entry per production and is indexed by
155 * the negative-encoded values (reduce actions) in the action_table.
156 * Each entry has two parts, the index of the non-terminal on the
157 * left hand side of the production, and the number of Symbols
158 * on the right hand side.
160 public abstract short[][] production_table();
162 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
164 /** The action table (supplied by generated subclass). This table is
165 * indexed by state and terminal number indicating what action is to
166 * be taken when the parser is in the given state (i.e., the given state
167 * is on top of the stack) and the given terminal is next on the input.
168 * States are indexed using the first dimension, however, the entries for
169 * a given state are compacted and stored in adjacent index, value pairs
170 * which are searched for rather than accessed directly (see get_action()).
171 * The actions stored in the table will be either shifts, reduces, or
172 * errors. Shifts are encoded as positive values (one greater than the
173 * state shifted to). Reduces are encoded as negative values (one less
174 * than the production reduced by). Error entries are denoted by zero.
176 * @see java_cup.runtime.lr_parser#get_action
178 public abstract short[][] action_table();
180 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
182 /** The reduce-goto table (supplied by generated subclass). This
183 * table is indexed by state and non-terminal number and contains
184 * state numbers. States are indexed using the first dimension, however,
185 * the entries for a given state are compacted and stored in adjacent
186 * index, value pairs which are searched for rather than accessed
187 * directly (see get_reduce()). When a reduce occurs, the handle
188 * (corresponding to the RHS of the matched production) is popped off
189 * the stack. The new top of stack indicates a state. This table is
190 * then indexed by that state and the LHS of the reducing production to
191 * indicate where to "shift" to.
193 * @see java_cup.runtime.lr_parser#get_reduce
195 public abstract short[][] reduce_table();
197 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
199 /** The index of the start state (supplied by generated subclass). */
200 public abstract int start_state();
202 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
204 /** The index of the start production (supplied by generated subclass). */
205 public abstract int start_production();
207 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
209 /** The index of the end of file terminal Symbol (supplied by generated
212 public abstract int EOF_sym();
214 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
216 /** The index of the special error Symbol (supplied by generated subclass). */
217 public abstract int error_sym();
219 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
221 /** Internal flag to indicate when parser should quit. */
222 protected boolean _done_parsing = false;
224 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
226 /** This method is called to indicate that the parser should quit. This is
227 * normally called by an accept action, but can be used to cancel parsing
228 * early in other circumstances if desired.
230 public void done_parsing()
232 _done_parsing = true;
235 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
236 /* Global parse state shared by parse(), error recovery, and
237 * debugging routines */
238 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
240 /** Indication of the index for top of stack (for use by actions). */
243 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
245 /** The current lookahead Symbol. */
246 protected Symbol cur_token;
248 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
250 /** The parse stack itself. */
251 protected Stack stack = new Stack();
253 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
255 /** Direct reference to the production table. */
256 protected short[][] production_tab;
258 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
260 /** Direct reference to the action table. */
261 protected short[][] action_tab;
263 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
265 /** Direct reference to the reduce-goto table. */
266 protected short[][] reduce_tab;
268 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
270 /** This is the scanner object used by the default implementation
271 * of scan() to get Symbols. To avoid name conflicts with existing
272 * code, this field is private. [CSA/davidm] */
273 private Scanner _scanner;
276 * Simple accessor method to set the default scanner.
278 public void setScanner(Scanner s) { _scanner = s; }
281 * Simple accessor method to get the default scanner.
283 public Scanner getScanner() { return _scanner; }
285 /*-----------------------------------------------------------*/
286 /*--- General Methods ---------------------------------------*/
287 /*-----------------------------------------------------------*/
289 /** Perform a bit of user supplied action code (supplied by generated
290 * subclass). Actions are indexed by an internal action number assigned
291 * at parser generation time.
293 * @param act_num the internal index of the action to be performed.
294 * @param parser the parser object we are acting for.
295 * @param stack the parse stack of that object.
296 * @param top the index of the top element of the parse stack.
298 public abstract Symbol do_action(
303 throws java.lang.Exception;
305 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
307 /** User code for initialization inside the parser. Typically this
308 * initializes the scanner. This is called before the parser requests
309 * the first Symbol. Here this is just a placeholder for subclasses that
310 * might need this and we perform no action. This method is normally
311 * overridden by the generated code using this contents of the "init with"
312 * clause as its body.
314 public void user_init() throws java.lang.Exception { }
316 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
318 /** Initialize the action object. This is called before the parser does
319 * any parse actions. This is filled in by generated code to create
320 * an object that encapsulates all action code.
322 protected abstract void init_actions() throws java.lang.Exception;
324 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
326 /** Get the next Symbol from the input (supplied by generated subclass).
327 * Once end of file has been reached, all subsequent calls to scan
328 * should return an EOF Symbol (which is Symbol number 0). By default
329 * this method returns getScanner().next_token(); this implementation
330 * can be overriden by the generated parser using the code declared in
331 * the "scan with" clause. Do not recycle objects; every call to
332 * scan() should return a fresh object.
334 public Symbol scan() throws java.lang.Exception {
335 Symbol sym = getScanner().next_token();
336 return (sym!=null) ? sym : new Symbol(EOF_sym());
339 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
341 /** Report a fatal error. This method takes a message string and an
342 * additional object (to be used by specializations implemented in
343 * subclasses). Here in the base class a very simple implementation
344 * is provided which reports the error then throws an exception.
346 * @param message an error message.
347 * @param info an extra object reserved for use by specialized subclasses.
349 public void report_fatal_error(
352 throws java.lang.Exception
354 /* stop parsing (not really necessary since we throw an exception, but) */
357 /* use the normal error message reporting to put out the message */
358 report_error(message, info);
360 /* throw an exception */
361 throw new Exception("Can't recover from previous error(s)");
364 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
366 /** Report a non fatal error (or warning). This method takes a message
367 * string and an additional object (to be used by specializations
368 * implemented in subclasses). Here in the base class a very simple
369 * implementation is provided which simply prints the message to
372 * @param message an error message.
373 * @param info an extra object reserved for use by specialized subclasses.
375 public void report_error(String message, Object info)
377 System.err.print(message);
378 if (info instanceof Symbol)
379 if (((Symbol)info).left != -1)
380 System.err.println(" at character " + ((Symbol)info).left +
382 else System.err.println("");
383 else System.err.println("");
386 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
388 /** This method is called when a syntax error has been detected and recovery
389 * is about to be invoked. Here in the base class we just emit a
390 * "Syntax error" error message.
392 * @param cur_token the current lookahead Symbol.
394 public void syntax_error(Symbol cur_token)
396 report_error("Syntax error", cur_token);
399 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
401 /** This method is called if it is determined that syntax error recovery
402 * has been unsuccessful. Here in the base class we report a fatal error.
404 * @param cur_token the current lookahead Symbol.
406 public void unrecovered_syntax_error(Symbol cur_token)
407 throws java.lang.Exception
409 report_fatal_error("Couldn't repair and continue parse", cur_token);
412 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
414 /** Fetch an action from the action table. The table is broken up into
415 * rows, one per state (rows are indexed directly by state number).
416 * Within each row, a list of index, value pairs are given (as sequential
417 * entries in the table), and the list is terminated by a default entry
418 * (denoted with a Symbol index of -1). To find the proper entry in a row
419 * we do a linear or binary search (depending on the size of the row).
421 * @param state the state index of the action being accessed.
422 * @param sym the Symbol index of the action being accessed.
424 protected final short get_action(int state, int sym)
427 int first, last, probe;
428 short[] row = action_tab[state];
430 /* linear search if we are < 10 entries */
432 for (probe = 0; probe < row.length; probe++)
434 /* is this entry labeled with our Symbol or the default? */
436 if (tag == sym || tag == -1)
438 /* return the next entry */
442 /* otherwise binary search */
446 last = (row.length-1)/2 - 1; /* leave out trailing default entry */
447 while (first <= last)
449 probe = (first+last)/2;
450 if (sym == row[probe*2])
451 return row[probe*2+1];
452 else if (sym > row[probe*2])
458 /* not found, use the default at the end */
459 return row[row.length-1];
462 /* shouldn't happened, but if we run off the end we return the
463 default (error == 0) */
467 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
469 /** Fetch a state from the reduce-goto table. The table is broken up into
470 * rows, one per state (rows are indexed directly by state number).
471 * Within each row, a list of index, value pairs are given (as sequential
472 * entries in the table), and the list is terminated by a default entry
473 * (denoted with a Symbol index of -1). To find the proper entry in a row
474 * we do a linear search.
476 * @param state the state index of the entry being accessed.
477 * @param sym the Symbol index of the entry being accessed.
479 protected final short get_reduce(int state, int sym)
482 short[] row = reduce_tab[state];
484 /* if we have a null row we go with the default */
488 for (int probe = 0; probe < row.length; probe++)
490 /* is this entry labeled with our Symbol or the default? */
492 if (tag == sym || tag == -1)
494 /* return the next entry */
498 /* if we run off the end we return the default (error == -1) */
502 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
504 /** This method provides the main parsing routine. It returns only when
505 * done_parsing() has been called (typically because the parser has
506 * accepted, or a fatal error has been reported). See the header
507 * documentation for the class regarding how shift/reduce parsers operate
508 * and how the various tables are used.
510 public Symbol parse() throws java.lang.Exception
512 /* the current action code */
515 /* the Symbol/stack element returned by a reduce */
516 Symbol lhs_sym = null;
518 /* information about production being reduced with */
519 short handle_size, lhs_sym_num;
521 /* set up direct reference to tables to drive the parser */
523 production_tab = production_table();
524 action_tab = action_table();
525 reduce_tab = reduce_table();
527 /* initialize the action encapsulation object */
530 /* do user initialization */
533 /* get the first token */
536 /* push dummy Symbol with start state to get us underway */
537 stack.removeAllElements();
538 stack.push(new Symbol(0, start_state()));
541 /* continue until we are told to stop */
542 for (_done_parsing = false; !_done_parsing; )
544 /* Check current token for freshness. */
545 if (cur_token.used_by_parser)
546 throw new Error("Symbol recycling detected (fix your scanner).");
548 /* current state is always on the top of the stack */
550 /* look up action out of the current state with the current input */
551 act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
553 /* decode the action -- > 0 encodes shift */
556 /* shift to the encoded state by pushing it on the stack */
557 cur_token.parse_state = act-1;
558 cur_token.used_by_parser = true;
559 stack.push(cur_token);
562 /* advance to the next Symbol */
565 /* if its less than zero, then it encodes a reduce action */
568 /* perform the action for the reduce */
569 lhs_sym = do_action((-act)-1, this, stack, tos);
571 /* look up information about the production */
572 lhs_sym_num = production_tab[(-act)-1][0];
573 handle_size = production_tab[(-act)-1][1];
575 /* pop the handle off the stack */
576 for (int i = 0; i < handle_size; i++)
582 /* look up the state to go to from the one popped back to */
583 act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
585 /* shift to that state */
586 lhs_sym.parse_state = act;
587 lhs_sym.used_by_parser = true;
591 /* finally if the entry is zero, we have an error */
594 /* call user syntax error reporting routine */
595 syntax_error(cur_token);
597 /* try to error recover */
598 if (!error_recovery(false))
600 /* if that fails give up with a fatal syntax error */
601 unrecovered_syntax_error(cur_token);
603 /* just in case that wasn't fatal enough, end parse */
606 lhs_sym = (Symbol)stack.peek();
613 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
615 /** Write a debugging message to System.err for the debugging version
618 * @param mess the text of the debugging message.
620 public void debug_message(String mess)
622 System.err.println(mess);
625 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
627 /** Dump the parse stack for debugging purposes. */
628 public void dump_stack()
632 debug_message("# Stack dump requested, but stack is null");
636 debug_message("============ Parse Stack Dump ============");
639 for (int i=0; i<stack.size(); i++)
641 debug_message("Symbol: " + ((Symbol)stack.elementAt(i)).sym +
642 " State: " + ((Symbol)stack.elementAt(i)).parse_state);
644 debug_message("==========================================");
647 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
649 /** Do debug output for a reduce.
651 * @param prod_num the production we are reducing with.
652 * @param nt_num the index of the LHS non terminal.
653 * @param rhs_size the size of the RHS.
655 public void debug_reduce(int prod_num, int nt_num, int rhs_size)
657 debug_message("# Reduce with prod #" + prod_num + " [NT=" + nt_num +
658 ", " + "SZ=" + rhs_size + "]");
661 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
663 /** Do debug output for shift.
665 * @param shift_tkn the Symbol being shifted onto the stack.
667 public void debug_shift(Symbol shift_tkn)
669 debug_message("# Shift under term #" + shift_tkn.sym +
670 " to state #" + shift_tkn.parse_state);
673 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
675 /** Do debug output for stack state. [CSA]
677 public void debug_stack() {
678 StringBuffer sb=new StringBuffer("## STACK:");
679 for (int i=0; i<stack.size(); i++) {
680 Symbol s = (Symbol) stack.elementAt(i);
681 sb.append(" <state "+s.parse_state+", sym "+s.sym+">");
682 if ((i%3)==2 || (i==(stack.size()-1))) {
683 debug_message(sb.toString());
684 sb = new StringBuffer(" ");
689 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
691 /** Perform a parse with debugging output. This does exactly the
692 * same things as parse(), except that it calls debug_shift() and
693 * debug_reduce() when shift and reduce moves are taken by the parser
694 * and produces various other debugging messages.
696 public Symbol debug_parse()
697 throws java.lang.Exception
699 /* the current action code */
702 /* the Symbol/stack element returned by a reduce */
703 Symbol lhs_sym = null;
705 /* information about production being reduced with */
706 short handle_size, lhs_sym_num;
708 /* set up direct reference to tables to drive the parser */
709 production_tab = production_table();
710 action_tab = action_table();
711 reduce_tab = reduce_table();
713 debug_message("# Initializing parser");
715 /* initialize the action encapsulation object */
718 /* do user initialization */
721 /* the current Symbol */
724 debug_message("# Current Symbol is #" + cur_token.sym);
726 /* push dummy Symbol with start state to get us underway */
727 stack.removeAllElements();
728 stack.push(new Symbol(0, start_state()));
731 /* continue until we are told to stop */
732 for (_done_parsing = false; !_done_parsing; )
734 /* Check current token for freshness. */
735 if (cur_token.used_by_parser)
736 throw new Error("Symbol recycling detected (fix your scanner).");
738 /* current state is always on the top of the stack */
741 /* look up action out of the current state with the current input */
742 act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
744 /* decode the action -- > 0 encodes shift */
747 /* shift to the encoded state by pushing it on the stack */
748 cur_token.parse_state = act-1;
749 cur_token.used_by_parser = true;
750 debug_shift(cur_token);
751 stack.push(cur_token);
754 /* advance to the next Symbol */
756 debug_message("# Current token is " + cur_token);
758 /* if its less than zero, then it encodes a reduce action */
761 /* perform the action for the reduce */
762 lhs_sym = do_action((-act)-1, this, stack, tos);
764 /* look up information about the production */
765 lhs_sym_num = production_tab[(-act)-1][0];
766 handle_size = production_tab[(-act)-1][1];
768 debug_reduce((-act)-1, lhs_sym_num, handle_size);
770 /* pop the handle off the stack */
771 for (int i = 0; i < handle_size; i++)
777 /* look up the state to go to from the one popped back to */
778 act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
779 debug_message("# Reduce rule: top state " +
780 ((Symbol)stack.peek()).parse_state +
781 ", lhs sym " + lhs_sym_num + " -> state " + act);
783 /* shift to that state */
784 lhs_sym.parse_state = act;
785 lhs_sym.used_by_parser = true;
789 debug_message("# Goto state #" + act);
791 /* finally if the entry is zero, we have an error */
794 /* call user syntax error reporting routine */
795 syntax_error(cur_token);
797 /* try to error recover */
798 if (!error_recovery(true))
800 /* if that fails give up with a fatal syntax error */
801 unrecovered_syntax_error(cur_token);
803 /* just in case that wasn't fatal enough, end parse */
806 lhs_sym = (Symbol)stack.peek();
813 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
814 /* Error recovery code */
815 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
817 /** Attempt to recover from a syntax error. This returns false if recovery
818 * fails, true if it succeeds. Recovery happens in 4 steps. First we
819 * pop the parse stack down to a point at which we have a shift out
820 * of the top-most state on the error Symbol. This represents the
821 * initial error recovery configuration. If no such configuration is
822 * found, then we fail. Next a small number of "lookahead" or "parse
823 * ahead" Symbols are read into a buffer. The size of this buffer is
824 * determined by error_sync_size() and determines how many Symbols beyond
825 * the error must be matched to consider the recovery a success. Next,
826 * we begin to discard Symbols in attempt to get past the point of error
827 * to a point where we can continue parsing. After each Symbol, we attempt
828 * to "parse ahead" though the buffered lookahead Symbols. The "parse ahead"
829 * process simulates that actual parse, but does not modify the real
830 * parser's configuration, nor execute any actions. If we can parse all
831 * the stored Symbols without error, then the recovery is considered a
832 * success. Once a successful recovery point is determined, we do an
833 * actual parse over the stored input -- modifying the real parse
834 * configuration and executing all actions. Finally, we return the the
835 * normal parser to continue with the overall parse.
837 * @param debug should we produce debugging messages as we parse.
839 protected boolean error_recovery(boolean debug)
840 throws java.lang.Exception
842 if (debug) debug_message("# Attempting error recovery");
844 /* first pop the stack back into a state that can shift on error and
845 do that shift (if that fails, we fail) */
846 if (!find_recovery_config(debug))
848 if (debug) debug_message("# Error recovery fails");
852 /* read ahead to create lookahead we can parse multiple times */
855 /* repeatedly try to parse forward until we make it the required dist */
858 /* try to parse forward, if it makes it, bail out of loop */
859 if (debug) debug_message("# Trying to parse ahead");
860 if (try_parse_ahead(debug))
865 /* if we are now at EOF, we have failed */
866 if (lookahead[0].sym == EOF_sym())
868 if (debug) debug_message("# Error recovery fails at EOF");
872 /* otherwise, we consume another Symbol and try again */
873 // BUG FIX by Bruce Hutton
874 // Computer Science Department, University of Auckland,
875 // Auckland, New Zealand.
876 // It is the first token that is being consumed, not the one
877 // we were up to parsing
879 debug_message("# Consuming Symbol #" + lookahead[ 0 ].sym);
883 /* we have consumed to a point where we can parse forward */
884 if (debug) debug_message("# Parse-ahead ok, going back to normal parse");
886 /* do the real parse (including actions) across the lookahead */
887 parse_lookahead(debug);
889 /* we have success */
893 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
895 /** Determine if we can shift under the special error Symbol out of the
896 * state currently on the top of the (real) parse stack.
898 protected boolean shift_under_error()
900 /* is there a shift under error Symbol */
901 return get_action(((Symbol)stack.peek()).parse_state, error_sym()) > 0;
904 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
906 /** Put the (real) parse stack into error recovery configuration by
907 * popping the stack down to a state that can shift on the special
908 * error Symbol, then doing the shift. If no suitable state exists on
909 * the stack we return false
911 * @param debug should we produce debugging messages as we parse.
913 protected boolean find_recovery_config(boolean debug)
918 if (debug) debug_message("# Finding recovery state on stack");
920 /* Remember the right-position of the top symbol on the stack */
921 int right_pos = ((Symbol)stack.peek()).right;
922 int left_pos = ((Symbol)stack.peek()).left;
924 /* pop down until we can shift under error Symbol */
925 while (!shift_under_error())
929 debug_message("# Pop stack by one, state was # " +
930 ((Symbol)stack.peek()).parse_state);
931 left_pos = ((Symbol)stack.pop()).left;
934 /* if we have hit bottom, we fail */
937 if (debug) debug_message("# No recovery state found on stack");
942 /* state on top of the stack can shift under error, find the shift */
943 act = get_action(((Symbol)stack.peek()).parse_state, error_sym());
946 debug_message("# Recover state found (#" +
947 ((Symbol)stack.peek()).parse_state + ")");
948 debug_message("# Shifting on error to state #" + (act-1));
951 /* build and shift a special error Symbol */
952 error_token = new Symbol(error_sym(), left_pos, right_pos);
953 error_token.parse_state = act-1;
954 error_token.used_by_parser = true;
955 stack.push(error_token);
961 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
963 /** Lookahead Symbols used for attempting error recovery "parse aheads". */
964 protected Symbol lookahead[];
966 /** Position in lookahead input buffer used for "parse ahead". */
967 protected int lookahead_pos;
969 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
971 /** Read from input to establish our buffer of "parse ahead" lookahead
974 protected void read_lookahead() throws java.lang.Exception
976 /* create the lookahead array */
977 lookahead = new Symbol[error_sync_size()];
979 /* fill in the array */
980 for (int i = 0; i < error_sync_size(); i++)
982 lookahead[i] = cur_token;
986 /* start at the beginning */
990 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
992 /** Return the current lookahead in our error "parse ahead" buffer. */
993 protected Symbol cur_err_token() { return lookahead[lookahead_pos]; }
995 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
997 /** Advance to next "parse ahead" input Symbol. Return true if we have
998 * input to advance to, false otherwise.
1000 protected boolean advance_lookahead()
1002 /* advance the input location */
1005 /* return true if we didn't go off the end */
1006 return lookahead_pos < error_sync_size();
1009 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
1011 /** Reset the parse ahead input to one Symbol past where we started error
1012 * recovery (this consumes one new Symbol from the real input).
1014 protected void restart_lookahead() throws java.lang.Exception
1016 /* move all the existing input over */
1017 for (int i = 1; i < error_sync_size(); i++)
1018 lookahead[i-1] = lookahead[i];
1020 /* read a new Symbol into the last spot */
1021 // BUG Fix by Bruce Hutton
1022 // Computer Science Department, University of Auckland,
1023 // Auckland, New Zealand. [applied 5-sep-1999 by csa]
1024 // The following two lines were out of order!!
1025 lookahead[error_sync_size()-1] = cur_token;
1028 /* reset our internal position marker */
1032 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
1034 /** Do a simulated parse forward (a "parse ahead") from the current
1035 * stack configuration using stored lookahead input and a virtual parse
1036 * stack. Return true if we make it all the way through the stored
1037 * lookahead input without error. This basically simulates the action of
1038 * parse() using only our saved "parse ahead" input, and not executing any
1041 * @param debug should we produce debugging messages as we parse.
1043 protected boolean try_parse_ahead(boolean debug)
1044 throws java.lang.Exception
1047 short lhs, rhs_size;
1049 /* create a virtual stack from the real parse stack */
1050 virtual_parse_stack vstack = new virtual_parse_stack(stack);
1052 /* parse until we fail or get past the lookahead input */
1055 /* look up the action from the current state (on top of stack) */
1056 act = get_action(vstack.top(), cur_err_token().sym);
1058 /* if its an error, we fail */
1059 if (act == 0) return false;
1061 /* > 0 encodes a shift */
1064 /* push the new state on the stack */
1067 if (debug) debug_message("# Parse-ahead shifts Symbol #" +
1068 cur_err_token().sym + " into state #" + (act-1));
1070 /* advance simulated input, if we run off the end, we are done */
1071 if (!advance_lookahead()) return true;
1073 /* < 0 encodes a reduce */
1076 /* if this is a reduce with the start production we are done */
1077 if ((-act)-1 == start_production())
1079 if (debug) debug_message("# Parse-ahead accepts");
1083 /* get the lhs Symbol and the rhs size */
1084 lhs = production_tab[(-act)-1][0];
1085 rhs_size = production_tab[(-act)-1][1];
1087 /* pop handle off the stack */
1088 for (int i = 0; i < rhs_size; i++)
1092 debug_message("# Parse-ahead reduces: handle size = " +
1093 rhs_size + " lhs = #" + lhs + " from state #" + vstack.top());
1095 /* look up goto and push it onto the stack */
1096 vstack.push(get_reduce(vstack.top(), lhs));
1098 debug_message("# Goto state #" + vstack.top());
1103 /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
1105 /** Parse forward using stored lookahead Symbols. In this case we have
1106 * already verified that parsing will make it through the stored lookahead
1107 * Symbols and we are now getting back to the point at which we can hand
1108 * control back to the normal parser. Consequently, this version of the
1109 * parser performs all actions and modifies the real parse configuration.
1110 * This returns once we have consumed all the stored input or we accept.
1112 * @param debug should we produce debugging messages as we parse.
1114 protected void parse_lookahead(boolean debug)
1115 throws java.lang.Exception
1117 /* the current action code */
1120 /* the Symbol/stack element returned by a reduce */
1121 Symbol lhs_sym = null;
1123 /* information about production being reduced with */
1124 short handle_size, lhs_sym_num;
1126 /* restart the saved input at the beginning */
1131 debug_message("# Reparsing saved input with actions");
1132 debug_message("# Current Symbol is #" + cur_err_token().sym);
1133 debug_message("# Current state is #" +
1134 ((Symbol)stack.peek()).parse_state);
1137 /* continue until we accept or have read all lookahead input */
1138 while(!_done_parsing)
1140 /* current state is always on the top of the stack */
1142 /* look up action out of the current state with the current input */
1144 get_action(((Symbol)stack.peek()).parse_state, cur_err_token().sym);
1146 /* decode the action -- > 0 encodes shift */
1149 /* shift to the encoded state by pushing it on the stack */
1150 cur_err_token().parse_state = act-1;
1151 cur_err_token().used_by_parser = true;
1152 if (debug) debug_shift(cur_err_token());
1153 stack.push(cur_err_token());
1156 /* advance to the next Symbol, if there is none, we are done */
1157 if (!advance_lookahead())
1159 if (debug) debug_message("# Completed reparse");
1161 /* scan next Symbol so we can continue parse */
1162 // BUGFIX by Chris Harris <ckharris@ucsd.edu>:
1163 // correct a one-off error by commenting out
1165 /*cur_token = scan();*/
1167 /* go back to normal parser */
1172 debug_message("# Current Symbol is #" + cur_err_token().sym);
1174 /* if its less than zero, then it encodes a reduce action */
1177 /* perform the action for the reduce */
1178 lhs_sym = do_action((-act)-1, this, stack, tos);
1180 /* look up information about the production */
1181 lhs_sym_num = production_tab[(-act)-1][0];
1182 handle_size = production_tab[(-act)-1][1];
1184 if (debug) debug_reduce((-act)-1, lhs_sym_num, handle_size);
1186 /* pop the handle off the stack */
1187 for (int i = 0; i < handle_size; i++)
1193 /* look up the state to go to from the one popped back to */
1194 act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
1196 /* shift to that state */
1197 lhs_sym.parse_state = act;
1198 lhs_sym.used_by_parser = true;
1199 stack.push(lhs_sym);
1202 if (debug) debug_message("# Goto state #" + act);
1205 /* finally if the entry is zero, we have an error
1206 (shouldn't happen here, but...)*/
1209 report_fatal_error("Syntax error", lhs_sym);
1217 /*-----------------------------------------------------------*/
1219 /** Utility function: unpacks parse tables from strings */
1220 protected static short[][] unpackFromStrings(String[] sa)
1222 // Concatanate initialization strings.
1223 StringBuffer sb = new StringBuffer(sa[0]);
1224 for (int i=1; i<sa.length; i++)
1226 int n=0; // location in initialization string
1227 int size1 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
1228 short[][] result = new short[size1][];
1229 for (int i=0; i<size1; i++) {
1230 int size2 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
1231 result[i] = new short[size2];
1232 for (int j=0; j<size2; j++)
1233 result[i][j] = (short) (sb.charAt(n++)-2);