Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: 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     /* Add code to propagate RESULT assignments that occur in
388      * action code embedded in a production (ie, non-rightmost
389      * action code). 24-Mar-1998 CSA
390      */
391     for (int i=0; i<prod.rhs_length(); i++) {
392       // only interested in non-terminal symbols.
393       if (!(prod.rhs(i) instanceof symbol_part)) continue;
394       symbol s = ((symbol_part)prod.rhs(i)).the_symbol();
395       if (!(s instanceof non_terminal)) continue;
396       // skip this non-terminal unless it corresponds to
397       // an embedded action production.
398       if (((non_terminal)s).is_embedded_action == false) continue;
399       // OK, it fits.  Make a conditional assignment to RESULT.
400       int index = prod.rhs_length() - i - 1; // last rhs is on top.
401       out.println("              " + "// propagate RESULT from " +
402       s.name());
403       out.println("              " + "if ( " +
404         "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt("
405               + emit.pre("top") + "-" + index + ")).value != null )");
406       out.println("                " + "RESULT = " +
407         "(" + prod.lhs().the_symbol().stack_type() + ") " +
408         "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt("
409               + emit.pre("top") + "-" + index + ")).value;");
410     }
411 
412         /* if there is an action string, emit it */
413           if (prod.action() != null && prod.action().code_string() != null &&
414               !prod.action().equals(""))
415             out.println(prod.action().code_string());
416 
417     /* here we have the left and right values being propagated.  
418     must make this a command line option.
419        frankf 6/18/96 */
420 
421          /* Create the code that assigns the left and right values of
422             the new Symbol that the production is reducing to */
423     if (emit.lr_values()) {      
424       int loffset;
425       String leftstring, rightstring;
426       int roffset = 0;
427       rightstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + 
428         emit.pre("top") + "-" + roffset + ")).right";    
429       if (prod.rhs_length() == 0) 
430         leftstring = rightstring;
431       else {
432         loffset = prod.rhs_length() - 1;
433         leftstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + 
434     emit.pre("top") + "-" + loffset + ")).left";    
435       }
436       out.println("              " + pre("result") + " = new java_cup.runtime.Symbol(" + 
437       prod.lhs().the_symbol().index() + "/*" +
438       prod.lhs().the_symbol().name() + "*/" + 
439       ", " + leftstring + ", " + rightstring + ", RESULT);");
440     } else {
441       out.println("              " + pre("result") + " = new java_cup.runtime.Symbol(" + 
442       prod.lhs().the_symbol().index() + "/*" +
443       prod.lhs().the_symbol().name() + "*/" + 
444       ", RESULT);");
445     }
446     
447     /* end of their block */
448     out.println("            }");
449 
450     /* if this was the start production, do action for accept */
451     if (prod == start_prod)
452       {
453         out.println("          /* ACCEPT */");
454         out.println("          " + pre("parser") + ".done_parsing();");
455       }
456 
457     /* code to return lhs symbol */
458     out.println("          return " + pre("result") + ";");
459     out.println();
460   }
461 
462       /* end of switch */
463       out.println("          /* . . . . . .*/");
464       out.println("          default:");
465       out.println("            throw new Exception(");
466       out.println("               \"Invalid action number found in " +
467           "internal parse table\");");
468       out.println();
469       out.println("        }");
470 
471       /* end of method */
472       out.println("    }");
473 
474       /* end of class */
475       out.println("}");
476       out.println();
477 
478       action_code_time = System.currentTimeMillis() - start_time;
479     }
480 
481   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
482 
483   /** Emit the production table. 
484    * @param out stream to produce output on.
485    */
486   protected static void emit_production_table(PrintWriter out)
487     {
488       production all_prods[];
489       production prod;
490 
491       long start_time = System.currentTimeMillis();
492 
493       /* collect up the productions in order */
494       all_prods = new production[production.number()];
495       for (Enumeration p = production.all(); p.hasMoreElements(); )
496   {
497     prod = (production)p.nextElement();
498     all_prods[prod.index()] = prod;
499   }
500 
501       // make short[][]
502       short[][] prod_table = new short[production.number()][2];
503       for (int i = 0; i<production.number(); i++)
504   {
505     prod = all_prods[i];
506     // { lhs symbol , rhs size }
507     prod_table[i][0] = (short) prod.lhs().the_symbol().index();
508     prod_table[i][1] = (short) prod.rhs_length();
509   }
510       /* do the top of the table */
511       out.println();
512       out.println("  /** Production table. */");
513       out.println("  protected static final short _production_table[][] = ");
514       out.print  ("    unpackFromStrings(");
515       do_table_as_string(out, prod_table);
516       out.println(");");
517 
518       /* do the public accessor method */
519       out.println();
520       out.println("  /** Access to production table. */");
521       out.println("  public short[][] production_table() " + 
522              "{return _production_table;}");
523 
524       production_table_time = System.currentTimeMillis() - start_time;
525     }
526 
527   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
528 
529   /** Emit the action table. 
530    * @param out             stream to produce output on.
531    * @param act_tab         the internal representation of the action table.
532    * @param compact_reduces do we use the most frequent reduce as default?
533    */
534   protected static void do_action_table(
535     PrintWriter        out, 
536     parse_action_table act_tab,
537     boolean            compact_reduces)
538     throws internal_error
539     {
540       parse_action_row row;
541       parse_action     act;
542       int              red;
543 
544       long start_time = System.currentTimeMillis();
545 
546       /* collect values for the action table */
547       short[][] action_table = new short[act_tab.num_states()][];
548       /* do each state (row) of the action table */
549       for (int i = 0; i < act_tab.num_states(); i++)
550   {
551     /* get the row */
552     row = act_tab.under_state[i];
553 
554     /* determine the default for the row */
555     if (compact_reduces)
556       row.compute_default();
557     else
558       row.default_reduce = -1;
559 
560     /* make temporary table for the row. */
561     short[] temp_table = new short[2*row.size()];
562     int nentries = 0;
563 
564     /* do each column */
565     for (int j = 0; j < row.size(); j++)
566       {
567         /* extract the action from the table */
568         act = row.under_term[j];
569 
570         /* skip error entries these are all defaulted out */
571         if (act.kind() != parse_action.ERROR)
572     {
573       /* first put in the symbol index, then the actual entry */
574 
575       /* shifts get positive entries of state number + 1 */
576       if (act.kind() == parse_action.SHIFT)
577         {
578           /* make entry */
579           temp_table[nentries++] = (short) j;
580           temp_table[nentries++] = (short)
581       (((shift_action)act).shift_to().index() + 1);
582         }
583 
584       /* reduce actions get negated entries of production# + 1 */
585       else if (act.kind() == parse_action.REDUCE)
586         {
587           /* if its the default entry let it get defaulted out */
588           red = ((reduce_action)act).reduce_with().index();
589           if (red != row.default_reduce) {
590       /* make entry */
591       temp_table[nentries++] = (short) j;
592       temp_table[nentries++] = (short) (-(red+1));
593           }
594         } else if (act.kind() == parse_action.NONASSOC)
595           {
596       /* do nothing, since we just want a syntax error */
597           }
598       /* shouldn't be anything else */
599       else
600         throw new internal_error("Unrecognized action code " + 
601                act.kind() + " found in parse table");
602     }
603       }
604 
605     /* now we know how big to make the row */
606     action_table[i] = new short[nentries + 2];
607     System.arraycopy(temp_table, 0, action_table[i], 0, nentries);
608 
609     /* finish off the row with a default entry */
610     action_table[i][nentries++] = -1;
611     if (row.default_reduce != -1)
612       action_table[i][nentries++] = (short) (-(row.default_reduce+1));
613     else
614       action_table[i][nentries++] = 0;
615   }
616 
617       /* finish off the init of the table */
618       out.println();
619       out.println("  /** Parse-action table. */");
620       out.println("  protected static final short[][] _action_table = "); 
621       out.print  ("    unpackFromStrings(");
622       do_table_as_string(out, action_table);
623       out.println(");");
624 
625       /* do the public accessor method */
626       out.println();
627       out.println("  /** Access to parse-action table. */");
628       out.println("  public short[][] action_table() {return _action_table;}");
629 
630       action_table_time = System.currentTimeMillis() - start_time;
631     }
632 
633   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
634 
635   /** Emit the reduce-goto table. 
636    * @param out     stream to produce output on.
637    * @param red_tab the internal representation of the reduce-goto table.
638    */
639   protected static void do_reduce_table(
640     PrintWriter out, 
641     parse_reduce_table red_tab)
642     {
643       lalr_state       goto_st;
644       parse_action     act;
645 
646       long start_time = System.currentTimeMillis();
647 
648       /* collect values for reduce-goto table */
649       short[][] reduce_goto_table = new short[red_tab.num_states()][];
650       /* do each row of the reduce-goto table */
651       for (int i=0; i<red_tab.num_states(); i++)
652   {
653     /* make temporary table for the row. */
654     short[] temp_table = new short[2*red_tab.under_state[i].size()];
655     int nentries = 0;
656     /* do each entry in the row */
657     for (int j=0; j<red_tab.under_state[i].size(); j++)
658       {
659         /* get the entry */
660         goto_st = red_tab.under_state[i].under_non_term[j];
661 
662         /* if we have none, skip it */
663         if (goto_st != null)
664     {
665       /* make entries for the index and the value */
666       temp_table[nentries++] = (short) j;
667       temp_table[nentries++] = (short) goto_st.index();
668     }
669       }
670     /* now we know how big to make the row. */
671     reduce_goto_table[i] = new short[nentries+2];
672     System.arraycopy(temp_table, 0, reduce_goto_table[i], 0, nentries);
673 
674     /* end row with default value */
675     reduce_goto_table[i][nentries++] = -1;
676     reduce_goto_table[i][nentries++] = -1;
677   }
678 
679       /* emit the table. */
680       out.println();
681       out.println("  /** <code>reduce_goto</code> table. */");
682       out.println("  protected static final short[][] _reduce_table = "); 
683       out.print  ("    unpackFromStrings(");
684       do_table_as_string(out, reduce_goto_table);
685       out.println(");");
686 
687       /* do the public accessor method */
688       out.println();
689       out.println("  /** Access to <code>reduce_goto</code> table. */");
690       out.println("  public short[][] reduce_table() {return _reduce_table;}");
691       out.println();
692 
693       goto_table_time = System.currentTimeMillis() - start_time;
694     }
695 
696   // print a string array encoding the given short[][] array.
697   protected static void do_table_as_string(PrintWriter out, short[][] sa) {
698     out.println("new String[] {");
699     out.print("    \"");
700     int nchar=0, nbytes=0;
701     nbytes+=do_escaped(out, (char)(sa.length>>16));
702     nchar  =do_newline(out, nchar, nbytes);
703     nbytes+=do_escaped(out, (char)(sa.length&0xFFFF));
704     nchar  =do_newline(out, nchar, nbytes);
705     for (int i=0; i<sa.length; i++) {
706   nbytes+=do_escaped(out, (char)(sa[i].length>>16));
707   nchar  =do_newline(out, nchar, nbytes);
708   nbytes+=do_escaped(out, (char)(sa[i].length&0xFFFF));
709   nchar  =do_newline(out, nchar, nbytes);
710   for (int j=0; j<sa[i].length; j++) {
711     // contents of string are (value+2) to allow for common -1, 0 cases
712     // (UTF-8 encoding is most efficient for 0<c<0x80)
713     nbytes+=do_escaped(out, (char)(2+sa[i][j]));
714     nchar  =do_newline(out, nchar, nbytes);
715   }
716     }
717     out.print("\" }");
718   }
719   // split string if it is very long; start new line occasionally for neatness
720   protected static int do_newline(PrintWriter out, int nchar, int nbytes) {
721     if (nbytes > 65500)  { out.println("\", "); out.print("    \""); }
722     else if (nchar > 11) { out.println("\" +"); out.print("    \""); }
723     else return nchar+1;
724     return 0;
725   }
726   // output an escape sequence for the given character code.
727   protected static int do_escaped(PrintWriter out, char c) {
728     StringBuffer escape = new StringBuffer();
729     if (c <= 0xFF) {
730       escape.append(Integer.toOctalString(c));
731       while(escape.length() < 3) escape.insert(0, '0');
732     } else {
733       escape.append(Integer.toHexString(c));
734       while(escape.length() < 4) escape.insert(0, '0');
735       escape.insert(0, 'u');
736     }
737     escape.insert(0, '\\');
738     out.print(escape.toString());
739 
740     // return number of bytes this takes up in UTF-8 encoding.
741     if (c == 0) return 2;
742     if (c >= 0x01 && c <= 0x7F) return 1;
743     if (c >= 0x80 && c <= 0x7FF) return 2;
744     return 3;
745   }
746 
747   /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
748 
749   /** Emit the parser subclass with embedded tables. 
750    * @param out             stream to produce output on.
751    * @param action_table    internal representation of the action table.
752    * @param reduce_table    internal representation of the reduce-goto table.
753    * @param start_st        start state of the parse machine.
754    * @param start_prod      start production of the grammar.
755    * @param compact_reduces do we use most frequent reduce as default?
756    * @param suppress_scanner should scanner be suppressed for compatibility?
757    */
758   public static void parser(
759     PrintWriter        out, 
760     parse_action_table action_table,
761     parse_reduce_table reduce_table,
762     int                start_st,
763     production         start_prod,
764     boolean            compact_reduces,
765     boolean            suppress_scanner)
766     throws internal_error
767     {
768       long start_time = System.currentTimeMillis();
769 
770       /* top of file */
771       out.println();
772       out.println("//----------------------------------------------------"); 
773       out.println("// The following code was generated by " + 
774               version.title_str);
775       out.println("// " + new Date());
776       out.println("//----------------------------------------------------"); 
777       out.println();
778       emit_package(out);
779 
780       /* user supplied imports */
781       for (int i = 0; i < import_list.size(); i++)
782   out.println("import " + import_list.elementAt(i) + ";");
783 
784       /* class header */
785       out.println();
786       out.println("/** "+version.title_str+" generated parser.");
787       out.println("  * @version " + new Date());
788       out.println("  */");
789       out.println("public class " + parser_class_name + 
790       " extends java_cup.runtime.lr_parser {");
791 
792       /* constructors [CSA/davidm, 24-jul-99] */
793       out.println();
794       out.println("  /** Default constructor. */");
795       out.println("  public " + parser_class_name + "() {super();}");
796       if (!suppress_scanner) {
797     out.println();
798     out.println("  /** Constructor which sets the default scanner. */");
799     out.println("  public " + parser_class_name + 
800           "(java_cup.runtime.Scanner s) {super(s);}");
801       }
802 
803       /* emit the various tables */
804       emit_production_table(out);
805       do_action_table(out, action_table, compact_reduces);
806       do_reduce_table(out, reduce_table);
807 
808       /* instance of the action encapsulation class */
809       out.println("  /** Instance of action encapsulation class. */");
810       out.println("  protected " + pre("actions") + " action_obj;");
811       out.println();
812 
813       /* action object initializer */
814       out.println("  /** Action encapsulation object initializer. */");
815       out.println("  protected void init_actions()");
816       out.println("    {");
817       out.println("      action_obj = new " + pre("actions") + "(this);");
818       out.println("    }");
819       out.println();
820 
821       /* access to action code */
822       out.println("  /** Invoke a user supplied parse action. */");
823       out.println("  public java_cup.runtime.Symbol do_action(");
824       out.println("    int                        act_num,");
825       out.println("    java_cup.runtime.lr_parser parser,");
826       out.println("    java.util.Stack            stack,");
827       out.println("    int                        top)");
828       out.println("    throws java.lang.Exception");
829       out.println("  {");
830       out.println("    /* call code in generated class */");
831       out.println("    return action_obj." + pre("do_action(") +
832                   "act_num, parser, stack, top);");
833       out.println("  }");
834       out.println("");
835 
836 
837       /* method to tell the parser about the start state */
838       out.println("  /** Indicates start state. */");
839       out.println("  public int start_state() {return " + start_st + ";}");
840 
841       /* method to indicate start production */
842       out.println("  /** Indicates start production. */");
843       out.println("  public int start_production() {return " + 
844          start_production.index() + ";}");
845       out.println();
846 
847       /* methods to indicate EOF and error symbol indexes */
848       out.println("  /** <code>EOF</code> Symbol index. */");
849       out.println("  public int EOF_sym() {return " + terminal.EOF.index() + 
850             ";}");
851       out.println();
852       out.println("  /** <code>error</code> Symbol index. */");
853       out.println("  public int error_sym() {return " + terminal.error.index() +
854             ";}");
855       out.println();
856 
857       /* user supplied code for user_init() */
858       if (init_code != null)
859   {
860           out.println();
861     out.println("  /** User initialization code. */");
862     out.println("  public void user_init() throws java.lang.Exception");
863     out.println("    {");
864     out.println(init_code);
865     out.println("    }");
866   }
867 
868       /* user supplied code for scan */
869       if (scan_code != null)
870   {
871           out.println();
872     out.println("  /** Scan to get the next Symbol. */");
873     out.println("  public java_cup.runtime.Symbol scan()");
874     out.println("    throws java.lang.Exception");
875     out.println("    {");
876     out.println(scan_code);
877     out.println("    }");
878   }
879 
880       /* user supplied code */
881       if (parser_code != null)
882   {
883     out.println();
884           out.println(parser_code);
885   }
886 
887       /* end of class */
888       out.println("}");
889 
890       /* put out the action code class */
891       emit_action_code(out, start_prod);
892 
893       parser_time = System.currentTimeMillis() - start_time;
894     }
895 
896     /*-----------------------------------------------------------*/
897 }