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