Changed iterator behavior...It only iterates over the items in the set
[repair.git] / Repair / RepairCompiler / java_cup / emit.java
1 package java_cup;
2
3 import java.io.PrintWriter;
4 import java.util.Stack;
5 import java.util.Enumeration;
6 import java.util.Date;
7
8 /** 
9  * This class handles emitting generated code for the resulting parser.
10  * The various parse tables must be constructed, etc. before calling any 
11  * routines in this class.<p>  
12  *
13  * Three classes are produced by this code:
14  *   <dl>
15  *   <dt> symbol constant class
16  *   <dd>   this contains constant declarations for each terminal (and 
17  *          optionally each non-terminal).
18  *   <dt> action class
19  *   <dd>   this non-public class contains code to invoke all the user actions 
20  *          that were embedded in the parser specification.
21  *   <dt> parser class
22  *   <dd>   the specialized parser class consisting primarily of some user 
23  *          supplied general and initialization code, and the parse tables.
24  *   </dl><p>
25  *
26  *  Three parse tables are created as part of the parser class:
27  *    <dl>
28  *    <dt> production table
29  *    <dd>   lists the LHS non terminal number, and the length of the RHS of 
30  *           each production.
31  *    <dt> action table
32  *    <dd>   for each state of the parse machine, gives the action to be taken
33  *           (shift, reduce, or error) under each lookahead symbol.<br>
34  *    <dt> reduce-goto table
35  *    <dd>   when a reduce on a given production is taken, the parse stack is 
36  *           popped back a number of elements corresponding to the RHS of the 
37  *           production.  This reveals a prior state, which we transition out 
38  *           of under the LHS non terminal symbol for the production (as if we
39  *           had seen the LHS symbol rather than all the symbols matching the 
40  *           RHS).  This table is indexed by non terminal numbers and indicates 
41  *           how to make these transitions. 
42  *    </dl><p>
43  * 
44  * In addition to the method interface, this class maintains a series of 
45  * public global variables and flags indicating how misc. parts of the code 
46  * and other output is to be produced, and counting things such as number of 
47  * conflicts detected (see the source code and public variables below for
48  * more details).<p> 
49  *
50  * This class is "static" (contains only static data and methods).<p> 
51  *
52  * @see java_cup.main
53  * @version last update: 11/25/95
54  * @author Scott Hudson
55  */
56
57 /* Major externally callable routines here include:
58      symbols               - emit the symbol constant class 
59      parser                - emit the parser class
60
61    In addition the following major internal routines are provided:
62      emit_package          - emit a package declaration
63      emit_action_code      - emit the class containing the user's actions 
64      emit_production_table - emit declaration and init for the production table
65      do_action_table       - emit declaration and init for the action table
66      do_reduce_table       - emit declaration and init for the reduce-goto table
67
68    Finally, this class uses a number of public instance variables to communicate
69    optional parameters and flags used to control how code is generated,
70    as well as to report counts of various things (such as number of conflicts
71    detected).  These include:
72
73    prefix                  - a prefix string used to prefix names that would 
74                              otherwise "pollute" someone else's name space.
75    package_name            - name of the package emitted code is placed in 
76                              (or null for an unnamed package.
77    symbol_const_class_name - name of the class containing symbol constants.
78    parser_class_name       - name of the class for the resulting parser.
79    action_code             - user supplied declarations and other code to be 
80                              placed in action class.
81    parser_code             - user supplied declarations and other code to be 
82                              placed in parser class.
83    init_code               - user supplied code to be executed as the parser 
84                              is being initialized.
85    scan_code               - user supplied code to get the next Symbol.
86    start_production        - the start production for the grammar.
87    import_list             - list of imports for use with action class.
88    num_conflicts           - number of conflicts detected. 
89    nowarn                  - true if we are not to issue warning messages.
90    not_reduced             - count of number of productions that never reduce.
91    unused_term             - count of unused terminal symbols.
92    unused_non_term         - count of unused non terminal symbols.
93    *_time                  - a series of symbols indicating how long various
94                              sub-parts of code generation took (used to produce
95                              optional time reports in main).
96 */
97
98 public class emit {
99
100   /*-----------------------------------------------------------*/
101   /*--- Constructor(s) ----------------------------------------*/
102   /*-----------------------------------------------------------*/
103
104   /** Only constructor is private so no instances can be created. */
105   private emit() { }
106
107   /*-----------------------------------------------------------*/
108   /*--- Static (Class) Variables ------------------------------*/
109   /*-----------------------------------------------------------*/
110
111   /** The prefix placed on names that pollute someone else's name space. */
112   public static String prefix = "CUP$";
113
114   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
115
116   /** Package that the resulting code goes into (null is used for unnamed). */
117   public static String package_name = null;
118
119   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
120
121   /** Name of the generated class for symbol constants. */
122   public static String symbol_const_class_name = "sym";
123
124   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
125
126   /** Name of the generated parser class. */
127   public static String parser_class_name = "parser";
128
129   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
130
131   /** User declarations for direct inclusion in user action class. */
132   public static String action_code = null;
133
134   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
135
136   /** User declarations for direct inclusion in parser class. */
137   public static String parser_code = null;
138
139   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
140
141   /** User code for user_init() which is called during parser initialization. */
142   public static String init_code = null;
143
144   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
145
146   /** User code for scan() which is called to get the next Symbol. */
147   public static String scan_code = null;
148
149   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
150
151   /** The start production of the grammar. */
152   public static production start_production = null;
153
154   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
155
156   /** List of imports (Strings containing class names) to go with actions. */
157   public static Stack import_list = new Stack();
158
159   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
160
161   /** Number of conflict found while building tables. */
162   public static int num_conflicts = 0;
163
164   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
165
166   /** Do we skip warnings? */
167   public static boolean nowarn = false;
168
169   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
170
171   /** Count of the number on non-reduced productions found. */
172   public static int not_reduced = 0;
173
174   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
175
176   /** Count of unused terminals. */
177   public static int unused_term = 0;
178
179   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
180
181   /** Count of unused non terminals. */
182   public static int unused_non_term = 0;
183
184   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
185
186   /* Timing values used to produce timing report in main.*/
187
188   /** Time to produce symbol constant class. */
189   public static long symbols_time          = 0;
190
191   /** Time to produce parser class. */
192   public static long parser_time           = 0;
193
194   /** Time to produce action code class. */
195   public static long action_code_time      = 0;
196
197   /** Time to produce the production table. */
198   public static long production_table_time = 0;
199
200   /** Time to produce the action table. */
201   public static long action_table_time     = 0;
202
203   /** Time to produce the reduce-goto table. */
204   public static long goto_table_time       = 0;
205
206   /* frankf 6/18/96 */
207   protected static boolean _lr_values;
208
209   /** whether or not to emit code for left and right values */
210   public static boolean lr_values() {return _lr_values;}
211   protected static void set_lr_values(boolean b) { _lr_values = b;}
212
213   /*-----------------------------------------------------------*/
214   /*--- General Methods ---------------------------------------*/
215   /*-----------------------------------------------------------*/
216
217   /** Build a string with the standard prefix. 
218    * @param str string to prefix.
219    */
220   protected static String pre(String str) {
221     return prefix + parser_class_name + "$" + str;
222   }
223
224   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
225
226   /** Emit a package spec if the user wants one. 
227    * @param out stream to produce output on.
228    */
229   protected static void emit_package(PrintWriter out)
230     {
231       /* generate a package spec if we have a name for one */
232       if (package_name != null) {
233         out.println("package " + package_name + ";"); out.println();
234       }
235     }
236
237   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
238
239   /** Emit code for the symbol constant class, optionally including non terms,
240    *  if they have been requested.  
241    * @param out            stream to produce output on.
242    * @param emit_non_terms do we emit constants for non terminals?
243    * @param sym_interface  should we emit an interface, rather than a class?
244    */
245   public static void symbols(PrintWriter out, 
246                              boolean emit_non_terms, boolean sym_interface)
247     {
248       terminal term;
249       non_terminal nt;
250       String class_or_interface = (sym_interface)?"interface":"class";
251
252       long start_time = System.currentTimeMillis();
253
254       /* top of file */
255       out.println();
256       out.println("//----------------------------------------------------"); 
257       out.println("// The following code was generated by " + 
258                                                            version.title_str);
259       out.println("// " + new Date());
260       out.println("//----------------------------------------------------"); 
261       out.println();
262       emit_package(out);
263
264       /* class header */
265       out.println("/** CUP generated " + class_or_interface + 
266                   " containing symbol constants. */");
267       out.println("public " + class_or_interface + " " + 
268                   symbol_const_class_name + " {");
269
270       out.println("  /* terminals */");
271
272       /* walk over the terminals */              /* later might sort these */
273       for (Enumeration e = terminal.all(); e.hasMoreElements(); )
274         {
275           term = (terminal)e.nextElement();
276
277           /* output a constant decl for the terminal */
278           out.println("  public static final int " + term.name() + " = " + 
279                       term.index() + ";");
280         }
281
282       /* do the non terminals if they want them (parser doesn't need them) */
283       if (emit_non_terms)
284         {
285           out.println();
286           out.println("  /* non terminals */");
287
288           /* walk over the non terminals */       /* later might sort these */
289           for (Enumeration e = non_terminal.all(); e.hasMoreElements(); )
290             {
291               nt = (non_terminal)e.nextElement();
292     
293               /* output a constant decl for the terminal */
294               out.println("  static final int " + nt.name() + " = " + 
295                           nt.index() + ";");
296             }
297         }
298
299       /* end of class */
300       out.println("}");
301       out.println();
302
303       symbols_time = System.currentTimeMillis() - start_time;
304     }
305
306   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
307
308   /** Emit code for the non-public class holding the actual action code. 
309    * @param out        stream to produce output on.
310    * @param start_prod the start production of the grammar.
311    */
312   protected static void emit_action_code(PrintWriter out, production start_prod)
313     throws internal_error
314     {
315       production prod;
316
317       long start_time = System.currentTimeMillis();
318
319       /* class header */
320       out.println();
321       out.println(
322        "/** Cup generated class to encapsulate user supplied action code.*/"
323       );  
324       out.println("class " +  pre("actions") + " {");
325
326       /* user supplied code */
327       if (action_code != null)
328         {
329           out.println();
330           out.println(action_code);
331         }
332
333       /* field for parser object */
334       out.println("  private final "+parser_class_name+" parser;");
335
336       /* constructor */
337       out.println();
338       out.println("  /** Constructor */");
339       out.println("  " + pre("actions") + "("+parser_class_name+" parser) {");
340       out.println("    this.parser = parser;");
341       out.println("  }");
342
343       /* action method head */
344       out.println();
345       out.println("  /** Method with the actual generated action code. */");
346       out.println("  public final java_cup.runtime.Symbol " + 
347                      pre("do_action") + "(");
348       out.println("    int                        " + pre("act_num,"));
349       out.println("    java_cup.runtime.lr_parser " + pre("parser,"));
350       out.println("    java.util.Stack            " + pre("stack,"));
351       out.println("    int                        " + pre("top)"));
352       out.println("    throws java.lang.Exception");
353       out.println("    {");
354
355       /* declaration of result symbol */
356       /* New declaration!! now return Symbol
357          6/13/96 frankf */
358       out.println("      /* Symbol object for return from actions */");
359       out.println("      java_cup.runtime.Symbol " + pre("result") + ";");
360       out.println();
361
362       /* switch top */
363       out.println("      /* select the action based on the action number */");
364       out.println("      switch (" + pre("act_num") + ")");
365       out.println("        {");
366
367       /* emit action code for each production as a separate case */
368       for (Enumeration p = production.all(); p.hasMoreElements(); )
369         {
370           prod = (production)p.nextElement();
371
372           /* case label */
373           out.println("          /*. . . . . . . . . . . . . . . . . . . .*/");
374           out.println("          case " + prod.index() + ": // " + 
375                                           prod.to_simple_string());
376
377           /* give them their own block to work in */
378           out.println("            {");
379
380           /* create the result symbol */
381           /*make the variable RESULT which will point to the new Symbol (see below)
382             and be changed by action code
383             6/13/96 frankf */
384           out.println("              " +  prod.lhs().the_symbol().stack_type() +
385                       " RESULT = null;");
386           
387           /* create the PRODSTRING variable, useful for debugging */
388           out.println("              String PRODSTRING = \"" + prod.to_simple_string() + "\";");
389
390           /* Add code to propagate RESULT assignments that occur in
391            * action code embedded in a production (ie, non-rightmost
392            * action code). 24-Mar-1998 CSA
393            */
394           for (int i=0; i<prod.rhs_length(); i++) {
395             // only interested in non-terminal symbols.
396             if (!(prod.rhs(i) instanceof symbol_part)) continue;
397             symbol s = ((symbol_part)prod.rhs(i)).the_symbol();
398             if (!(s instanceof non_terminal)) continue;
399             // skip this non-terminal unless it corresponds to
400             // an embedded action production.
401             if (((non_terminal)s).is_embedded_action == false) continue;
402             // OK, it fits.  Make a conditional assignment to RESULT.
403             int index = prod.rhs_length() - i - 1; // last rhs is on top.
404             out.println("              " + "// propagate RESULT from " +
405                         s.name());
406             out.println("              " + "if ( " +
407               "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt("
408               + emit.pre("top") + "-" + index + ")).value != null )");
409             out.println("                " + "RESULT = " +
410               "(" + prod.lhs().the_symbol().stack_type() + ") " +
411               "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt("
412               + emit.pre("top") + "-" + index + ")).value;");
413           }
414
415         /* if there is an action string, emit it */
416           if (prod.action() != null && prod.action().code_string() != null &&
417               !prod.action().equals(""))
418             out.println(prod.action().code_string());
419
420           /* here we have the left and right values being propagated.  
421                 must make this a command line option.
422              frankf 6/18/96 */
423
424          /* Create the code that assigns the left and right values of
425             the new Symbol that the production is reducing to */
426           if (emit.lr_values()) {           
427             int loffset;
428             String leftstring, rightstring;
429             int roffset = 0;
430             rightstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + 
431               emit.pre("top") + "-" + roffset + ")).right";       
432             if (prod.rhs_length() == 0) 
433               leftstring = rightstring;
434             else {
435               loffset = prod.rhs_length() - 1;
436               leftstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + 
437                 emit.pre("top") + "-" + loffset + ")).left";      
438             }
439             out.println("              " + pre("result") + " = new java_cup.runtime.Symbol(" + 
440                         prod.lhs().the_symbol().index() + "/*" +
441                         prod.lhs().the_symbol().name() + "*/" + 
442                         ", " + leftstring + ", " + rightstring + ", RESULT);");
443           } else {
444             out.println("              " + pre("result") + " = new java_cup.runtime.Symbol(" + 
445                         prod.lhs().the_symbol().index() + "/*" +
446                         prod.lhs().the_symbol().name() + "*/" + 
447                         ", RESULT);");
448           }
449           
450           /* end of their block */
451           out.println("            }");
452
453           /* if this was the start production, do action for accept */
454           if (prod == start_prod)
455             {
456               out.println("          /* ACCEPT */");
457               out.println("          " + pre("parser") + ".done_parsing();");
458             }
459
460           /* code to return lhs symbol */
461           out.println("          return " + pre("result") + ";");
462           out.println();
463         }
464
465       /* end of switch */
466       out.println("          /* . . . . . .*/");
467       out.println("          default:");
468       out.println("            throw new Exception(");
469       out.println("               \"Invalid action number found in " +
470                                   "internal parse table\");");
471       out.println();
472       out.println("        }");
473
474       /* end of method */
475       out.println("    }");
476
477       /* end of class */
478       out.println("}");
479       out.println();
480
481       action_code_time = System.currentTimeMillis() - start_time;
482     }
483
484   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
485
486   /** Emit the production table. 
487    * @param out stream to produce output on.
488    */
489   protected static void emit_production_table(PrintWriter out)
490     {
491       production all_prods[];
492       production prod;
493
494       long start_time = System.currentTimeMillis();
495
496       /* collect up the productions in order */
497       all_prods = new production[production.number()];
498       for (Enumeration p = production.all(); p.hasMoreElements(); )
499         {
500           prod = (production)p.nextElement();
501           all_prods[prod.index()] = prod;
502         }
503
504       // make short[][]
505       short[][] prod_table = new short[production.number()][2];
506       for (int i = 0; i<production.number(); i++)
507         {
508           prod = all_prods[i];
509           // { lhs symbol , rhs size }
510           prod_table[i][0] = (short) prod.lhs().the_symbol().index();
511           prod_table[i][1] = (short) prod.rhs_length();
512         }
513       /* do the top of the table */
514       out.println();
515       out.println("  /** Production table. */");
516       out.println("  protected static final short _production_table[][] = ");
517       out.print  ("    unpackFromStrings(");
518       do_table_as_string(out, prod_table);
519       out.println(");");
520
521       /* do the public accessor method */
522       out.println();
523       out.println("  /** Access to production table. */");
524       out.println("  public short[][] production_table() " + 
525                                                  "{return _production_table;}");
526
527       production_table_time = System.currentTimeMillis() - start_time;
528     }
529
530   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
531
532   /** Emit the action table. 
533    * @param out             stream to produce output on.
534    * @param act_tab         the internal representation of the action table.
535    * @param compact_reduces do we use the most frequent reduce as default?
536    */
537   protected static void do_action_table(
538     PrintWriter        out, 
539     parse_action_table act_tab,
540     boolean            compact_reduces)
541     throws internal_error
542     {
543       parse_action_row row;
544       parse_action     act;
545       int              red;
546
547       long start_time = System.currentTimeMillis();
548
549       /* collect values for the action table */
550       short[][] action_table = new short[act_tab.num_states()][];
551       /* do each state (row) of the action table */
552       for (int i = 0; i < act_tab.num_states(); i++)
553         {
554           /* get the row */
555           row = act_tab.under_state[i];
556
557           /* determine the default for the row */
558           if (compact_reduces)
559             row.compute_default();
560           else
561             row.default_reduce = -1;
562
563           /* make temporary table for the row. */
564           short[] temp_table = new short[2*row.size()];
565           int nentries = 0;
566
567           /* do each column */
568           for (int j = 0; j < row.size(); j++)
569             {
570               /* extract the action from the table */
571               act = row.under_term[j];
572
573               /* skip error entries these are all defaulted out */
574               if (act.kind() != parse_action.ERROR)
575                 {
576                   /* first put in the symbol index, then the actual entry */
577
578                   /* shifts get positive entries of state number + 1 */
579                   if (act.kind() == parse_action.SHIFT)
580                     {
581                       /* make entry */
582                       temp_table[nentries++] = (short) j;
583                       temp_table[nentries++] = (short)
584                         (((shift_action)act).shift_to().index() + 1);
585                     }
586
587                   /* reduce actions get negated entries of production# + 1 */
588                   else if (act.kind() == parse_action.REDUCE)
589                     {
590                       /* if its the default entry let it get defaulted out */
591                       red = ((reduce_action)act).reduce_with().index();
592                       if (red != row.default_reduce) {
593                         /* make entry */
594                         temp_table[nentries++] = (short) j;
595                         temp_table[nentries++] = (short) (-(red+1));
596                       }
597                     } else if (act.kind() == parse_action.NONASSOC)
598                       {
599                         /* do nothing, since we just want a syntax error */
600                       }
601                   /* shouldn't be anything else */
602                   else
603                     throw new internal_error("Unrecognized action code " + 
604                                              act.kind() + " found in parse table");
605                 }
606             }
607
608           /* now we know how big to make the row */
609           action_table[i] = new short[nentries + 2];
610           System.arraycopy(temp_table, 0, action_table[i], 0, nentries);
611
612           /* finish off the row with a default entry */
613           action_table[i][nentries++] = -1;
614           if (row.default_reduce != -1)
615             action_table[i][nentries++] = (short) (-(row.default_reduce+1));
616           else
617             action_table[i][nentries++] = 0;
618         }
619
620       /* finish off the init of the table */
621       out.println();
622       out.println("  /** Parse-action table. */");
623       out.println("  protected static final short[][] _action_table = "); 
624       out.print  ("    unpackFromStrings(");
625       do_table_as_string(out, action_table);
626       out.println(");");
627
628       /* do the public accessor method */
629       out.println();
630       out.println("  /** Access to parse-action table. */");
631       out.println("  public short[][] action_table() {return _action_table;}");
632
633       action_table_time = System.currentTimeMillis() - start_time;
634     }
635
636   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
637
638   /** Emit the reduce-goto table. 
639    * @param out     stream to produce output on.
640    * @param red_tab the internal representation of the reduce-goto table.
641    */
642   protected static void do_reduce_table(
643     PrintWriter out, 
644     parse_reduce_table red_tab)
645     {
646       lalr_state       goto_st;
647       parse_action     act;
648
649       long start_time = System.currentTimeMillis();
650
651       /* collect values for reduce-goto table */
652       short[][] reduce_goto_table = new short[red_tab.num_states()][];
653       /* do each row of the reduce-goto table */
654       for (int i=0; i<red_tab.num_states(); i++)
655         {
656           /* make temporary table for the row. */
657           short[] temp_table = new short[2*red_tab.under_state[i].size()];
658           int nentries = 0;
659           /* do each entry in the row */
660           for (int j=0; j<red_tab.under_state[i].size(); j++)
661             {
662               /* get the entry */
663               goto_st = red_tab.under_state[i].under_non_term[j];
664
665               /* if we have none, skip it */
666               if (goto_st != null)
667                 {
668                   /* make entries for the index and the value */
669                   temp_table[nentries++] = (short) j;
670                   temp_table[nentries++] = (short) goto_st.index();
671                 }
672             }
673           /* now we know how big to make the row. */
674           reduce_goto_table[i] = new short[nentries+2];
675           System.arraycopy(temp_table, 0, reduce_goto_table[i], 0, nentries);
676
677           /* end row with default value */
678           reduce_goto_table[i][nentries++] = -1;
679           reduce_goto_table[i][nentries++] = -1;
680         }
681
682       /* emit the table. */
683       out.println();
684       out.println("  /** <code>reduce_goto</code> table. */");
685       out.println("  protected static final short[][] _reduce_table = "); 
686       out.print  ("    unpackFromStrings(");
687       do_table_as_string(out, reduce_goto_table);
688       out.println(");");
689
690       /* do the public accessor method */
691       out.println();
692       out.println("  /** Access to <code>reduce_goto</code> table. */");
693       out.println("  public short[][] reduce_table() {return _reduce_table;}");
694       out.println();
695
696       goto_table_time = System.currentTimeMillis() - start_time;
697     }
698
699   // print a string array encoding the given short[][] array.
700   protected static void do_table_as_string(PrintWriter out, short[][] sa) {
701     out.println("new String[] {");
702     out.print("    \"");
703     int nchar=0, nbytes=0;
704     nbytes+=do_escaped(out, (char)(sa.length>>16));
705     nchar  =do_newline(out, nchar, nbytes);
706     nbytes+=do_escaped(out, (char)(sa.length&0xFFFF));
707     nchar  =do_newline(out, nchar, nbytes);
708     for (int i=0; i<sa.length; i++) {
709         nbytes+=do_escaped(out, (char)(sa[i].length>>16));
710         nchar  =do_newline(out, nchar, nbytes);
711         nbytes+=do_escaped(out, (char)(sa[i].length&0xFFFF));
712         nchar  =do_newline(out, nchar, nbytes);
713         for (int j=0; j<sa[i].length; j++) {
714           // contents of string are (value+2) to allow for common -1, 0 cases
715           // (UTF-8 encoding is most efficient for 0<c<0x80)
716           nbytes+=do_escaped(out, (char)(2+sa[i][j]));
717           nchar  =do_newline(out, nchar, nbytes);
718         }
719     }
720     out.print("\" }");
721   }
722   // split string if it is very long; start new line occasionally for neatness
723   protected static int do_newline(PrintWriter out, int nchar, int nbytes) {
724     if (nbytes > 65500)  { out.println("\", "); out.print("    \""); }
725     else if (nchar > 11) { out.println("\" +"); out.print("    \""); }
726     else return nchar+1;
727     return 0;
728   }
729   // output an escape sequence for the given character code.
730   protected static int do_escaped(PrintWriter out, char c) {
731     StringBuffer escape = new StringBuffer();
732     if (c <= 0xFF) {
733       escape.append(Integer.toOctalString(c));
734       while(escape.length() < 3) escape.insert(0, '0');
735     } else {
736       escape.append(Integer.toHexString(c));
737       while(escape.length() < 4) escape.insert(0, '0');
738       escape.insert(0, 'u');
739     }
740     escape.insert(0, '\\');
741     out.print(escape.toString());
742
743     // return number of bytes this takes up in UTF-8 encoding.
744     if (c == 0) return 2;
745     if (c >= 0x01 && c <= 0x7F) return 1;
746     if (c >= 0x80 && c <= 0x7FF) return 2;
747     return 3;
748   }
749
750   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
751
752   /** Emit the parser subclass with embedded tables. 
753    * @param out             stream to produce output on.
754    * @param action_table    internal representation of the action table.
755    * @param reduce_table    internal representation of the reduce-goto table.
756    * @param start_st        start state of the parse machine.
757    * @param start_prod      start production of the grammar.
758    * @param compact_reduces do we use most frequent reduce as default?
759    * @param suppress_scanner should scanner be suppressed for compatibility?
760    */
761   public static void parser(
762     PrintWriter        out, 
763     parse_action_table action_table,
764     parse_reduce_table reduce_table,
765     int                start_st,
766     production         start_prod,
767     boolean            compact_reduces,
768     boolean            suppress_scanner)
769     throws internal_error
770     {
771       long start_time = System.currentTimeMillis();
772
773       /* top of file */
774       out.println();
775       out.println("//----------------------------------------------------"); 
776       out.println("// The following code was generated by " + 
777                                                         version.title_str);
778       out.println("// " + new Date());
779       out.println("//----------------------------------------------------"); 
780       out.println();
781       emit_package(out);
782
783       /* user supplied imports */
784       for (int i = 0; i < import_list.size(); i++)
785         out.println("import " + import_list.elementAt(i) + ";");
786
787       /* class header */
788       out.println();
789       out.println("/** "+version.title_str+" generated parser.");
790       out.println("  * @version " + new Date());
791       out.println("  */");
792       out.println("public class " + parser_class_name + 
793                   " extends java_cup.runtime.lr_parser {");
794
795       /* constructors [CSA/davidm, 24-jul-99] */
796       out.println();
797       out.println("  /** Default constructor. */");
798       out.println("  public " + parser_class_name + "() {super();}");
799       if (!suppress_scanner) {
800           out.println();
801           out.println("  /** Constructor which sets the default scanner. */");
802           out.println("  public " + parser_class_name + 
803                       "(java_cup.runtime.Scanner s) {super(s);}");
804       }
805
806       /* emit the various tables */
807       emit_production_table(out);
808       do_action_table(out, action_table, compact_reduces);
809       do_reduce_table(out, reduce_table);
810
811       /* instance of the action encapsulation class */
812       out.println("  /** Instance of action encapsulation class. */");
813       out.println("  protected " + pre("actions") + " action_obj;");
814       out.println();
815
816       /* action object initializer */
817       out.println("  /** Action encapsulation object initializer. */");
818       out.println("  protected void init_actions()");
819       out.println("    {");
820       out.println("      action_obj = new " + pre("actions") + "(this);");
821       out.println("    }");
822       out.println();
823
824       /* access to action code */
825       out.println("  /** Invoke a user supplied parse action. */");
826       out.println("  public java_cup.runtime.Symbol do_action(");
827       out.println("    int                        act_num,");
828       out.println("    java_cup.runtime.lr_parser parser,");
829       out.println("    java.util.Stack            stack,");
830       out.println("    int                        top)");
831       out.println("    throws java.lang.Exception");
832       out.println("  {");
833       out.println("    /* call code in generated class */");
834       out.println("    return action_obj." + pre("do_action(") +
835                   "act_num, parser, stack, top);");
836       out.println("  }");
837       out.println("");
838
839
840       /* method to tell the parser about the start state */
841       out.println("  /** Indicates start state. */");
842       out.println("  public int start_state() {return " + start_st + ";}");
843
844       /* method to indicate start production */
845       out.println("  /** Indicates start production. */");
846       out.println("  public int start_production() {return " + 
847                      start_production.index() + ";}");
848       out.println();
849
850       /* methods to indicate EOF and error symbol indexes */
851       out.println("  /** <code>EOF</code> Symbol index. */");
852       out.println("  public int EOF_sym() {return " + terminal.EOF.index() + 
853                                           ";}");
854       out.println();
855       out.println("  /** <code>error</code> Symbol index. */");
856       out.println("  public int error_sym() {return " + terminal.error.index() +
857                                           ";}");
858       out.println();
859
860       /* user supplied code for user_init() */
861       if (init_code != null)
862         {
863           out.println();
864           out.println("  /** User initialization code. */");
865           out.println("  public void user_init() throws java.lang.Exception");
866           out.println("    {");
867           out.println(init_code);
868           out.println("    }");
869         }
870
871       /* user supplied code for scan */
872       if (scan_code != null)
873         {
874           out.println();
875           out.println("  /** Scan to get the next Symbol. */");
876           out.println("  public java_cup.runtime.Symbol scan()");
877           out.println("    throws java.lang.Exception");
878           out.println("    {");
879           out.println(scan_code);
880           out.println("    }");
881         }
882
883       /* user supplied code */
884       if (parser_code != null)
885         {
886           out.println();
887           out.println(parser_code);
888         }
889
890       /* end of class */
891       out.println("}");
892
893       /* put out the action code class */
894       emit_action_code(out, start_prod);
895
896       parser_time = System.currentTimeMillis() - start_time;
897     }
898
899     /*-----------------------------------------------------------*/
900 }