From 5c1177e58895b23617e622debabc126d3c1d2f84 Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Wed, 8 Apr 2026 19:51:40 +0700 Subject: [PATCH 01/12] Avoid 64KB clinit limit for large grammars via init methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Grammars with many keywords (e.g. JSqlParser with 500+ SQL keywords) generate TokenManager classes where the combined static array initializers exceed the JVM's 64 KB bytecode limit per method. All static final field initializers compile into a single method, causing ClassFormatError at class load time. Move array initialization out of into dedicated _init() methods. For very large arrays, split across multiple chunk methods so no single method exceeds the bytecode limit. For 2D arrays (jjnextStateSet, jjcompositeState), flatten into contiguous 1D arrays with offset/length accessors, eliminating both the problem and the per-row object header overhead. New file: JavaArrayHelper.java Reusable utility for emitting chunked int[], String[] and flattened int[][] array initializers via _init() methods. Modified: TokenManagerCodeGenerator.java Six arrays now emitted via JavaArrayHelper: - stringLiterals (int[]) — collect then emit via emitIntArray - jjstrLiteralImages (String[]) — collect then emit via emitStringArray - jjmatchKinds (int[]) — collect then emit via emitIntArray - jjnewLexState (int[]) — emit via emitIntArray - jjnextStateSet (int[][]) — flatten to 1D via emitFlatIntArray2D - jjcompositeState (int[][]) — flatten to 1D via emitFlatIntArray2D Modified: TokenManagerDriver.template Two lines changed to use generated _row() accessors for the flattened 2D arrays (jjcompositeState_row, jjnextStateSet_row). Backward compatible: generated parser is functionally identical. Tested with JSqlParser (500+ keywords, 500+ productions). --- .../java/org/javacc/java/JavaArrayHelper.java | 299 +++++ .../java/TokenManagerCodeGenerator.java | 1084 ++++++++--------- .../java/TokenManagerDriver.template | 4 +- 3 files changed, 798 insertions(+), 589 deletions(-) create mode 100644 src/main/java/org/javacc/java/JavaArrayHelper.java diff --git a/src/main/java/org/javacc/java/JavaArrayHelper.java b/src/main/java/org/javacc/java/JavaArrayHelper.java new file mode 100644 index 0000000..ff93a8e --- /dev/null +++ b/src/main/java/org/javacc/java/JavaArrayHelper.java @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2025, JavaCC contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the names of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.javacc.java; + +import java.util.List; + +/** + * Utility for emitting large Java static array declarations that would otherwise + * exceed the JVM's 64 KB bytecode limit on the {@code } method. + * + *

Instead of generating inline array initializers that all compile into + * {@code }, this helper generates dedicated {@code _init()} methods. + * For very large arrays the init body is further split across multiple chunk + * methods so that no single method exceeds the bytecode limit. + * + *

For 2D arrays ({@code int[][]}), this helper can flatten them into a + * contiguous 1D representation with offset/length arrays, eliminating both + * the {@code } problem and the per-row object header overhead. + */ +final class JavaArrayHelper { + + /** + * Maximum number of elements emitted per init chunk method. + * Each {@code r[i]=val;} compiles to roughly 8 bytes of bytecode, so 4000 + * elements is about 32 KB, well within the 64 KB limit. + */ + private static final int CHUNK_SIZE = 4000; + + /** Elements per line in the generated source for readability. */ + private static final int ELEMENTS_PER_LINE = 16; + + private JavaArrayHelper() {} + + // ---------------------------------------------------------------- + // int[] + // ---------------------------------------------------------------- + + /** + * Emits a {@code static final int[]} field backed by init method(s). + * + * @param jcb the code builder + * @param indent leading whitespace (e.g. {@code " "} for a class member) + * @param vis visibility keyword ({@code "private"}, {@code "public"}, etc.) + * @param name field name + * @param data the array data + */ + static void emitIntArray( + final JavaCodeBuilder jcb, final String indent, + final String vis, final String name, final int[] data) { + + jcb.println(indent + vis + " static final int[] " + name + " = " + name + "_init();"); + jcb.println(); + + if (data.length <= CHUNK_SIZE) { + jcb.println(indent + "private static int[] " + name + "_init() {"); + jcb.print(indent + " return new int[] {"); + appendIntElements(jcb, indent + " ", data, 0, data.length); + jcb.println(indent + " };"); + jcb.println(indent + "}"); + } else { + final int chunks = (data.length + CHUNK_SIZE - 1) / CHUNK_SIZE; + jcb.println(indent + "private static int[] " + name + "_init() {"); + jcb.println(indent + " final int[] r = new int[" + data.length + "];"); + for (int c = 0; c < chunks; c++) { + jcb.println(indent + " " + name + "_init_" + c + "(r);"); + } + jcb.println(indent + " return r;"); + jcb.println(indent + "}"); + jcb.println(); + for (int c = 0; c < chunks; c++) { + final int start = c * CHUNK_SIZE; + final int end = Math.min(start + CHUNK_SIZE, data.length); + jcb.println(indent + "private static void " + name + "_init_" + c + "(final int[] r) {"); + for (int i = start; i < end; i++) { + if ((i - start) % ELEMENTS_PER_LINE == 0) { + if (i > start) { + jcb.println(); + } + jcb.print(indent + " "); + } + jcb.print("r[" + i + "]=" + data[i] + "; "); + } + jcb.println(); + jcb.println(indent + "}"); + if (c < chunks - 1) { + jcb.println(); + } + } + } + jcb.println(); + } + + // ---------------------------------------------------------------- + // String[] + // ---------------------------------------------------------------- + + /** + * Emits a {@code static final String[]} field backed by init method(s). + * + * @param data array of already-quoted string values (e.g. {@code "\"hello\""}); + * {@code null} entries are emitted as the Java literal {@code null} + */ + static void emitStringArray( + final JavaCodeBuilder jcb, final String indent, + final String vis, final String name, final String[] data) { + + jcb.println(indent + vis + " static final String[] " + name + " = " + name + "_init();"); + jcb.println(); + + if (data.length <= CHUNK_SIZE) { + jcb.println(indent + "private static String[] " + name + "_init() {"); + jcb.println(indent + " return new String[] {"); + for (int i = 0; i < data.length; i++) { + jcb.print(indent + " " + (data[i] == null ? "null" : data[i])); + if (i < data.length - 1) { + jcb.println(","); + } else { + jcb.println(); + } + } + jcb.println(indent + " };"); + jcb.println(indent + "}"); + } else { + final int chunks = (data.length + CHUNK_SIZE - 1) / CHUNK_SIZE; + jcb.println(indent + "private static String[] " + name + "_init() {"); + jcb.println(indent + " final String[] r = new String[" + data.length + "];"); + for (int c = 0; c < chunks; c++) { + jcb.println(indent + " " + name + "_init_" + c + "(r);"); + } + jcb.println(indent + " return r;"); + jcb.println(indent + "}"); + jcb.println(); + for (int c = 0; c < chunks; c++) { + final int start = c * CHUNK_SIZE; + final int end = Math.min(start + CHUNK_SIZE, data.length); + jcb.println(indent + "private static void " + name + "_init_" + c + "(final String[] r) {"); + for (int i = start; i < end; i++) { + jcb.println(indent + " r[" + i + "] = " + + (data[i] == null ? "null" : data[i]) + ";"); + } + jcb.println(indent + "}"); + if (c < chunks - 1) { + jcb.println(); + } + } + } + jcb.println(); + } + + // ---------------------------------------------------------------- + // int[][] → flattened 1D representation + // ---------------------------------------------------------------- + + /** + * Result of flattening a 2D {@code int[][]} array into a contiguous 1D representation. + */ + static final class FlatIntArray2D { + + final int[] data; + final int[] offsets; + final int[] lengths; + final int rows; + + FlatIntArray2D(final int[] data, final int[] offsets, final int[] lengths, final int rows) { + this.data = data; + this.offsets = offsets; + this.lengths = lengths; + this.rows = rows; + } + } + + /** + * Flattens a list of {@code int[]} rows into a contiguous representation. + * Null or empty rows get {@code length == 0} and a valid offset. + * + * @param rows list of rows; null entries are treated as empty + * @return the flat representation + */ + static FlatIntArray2D flatten(final List rows) { + int totalSize = 0; + for (final int[] row : rows) { + if (row != null) { + totalSize += row.length; + } + } + // Ensure at least 1 element so data array is never zero-length + final int[] data = new int[Math.max(totalSize, 1)]; + final int[] offsets = new int[rows.size()]; + final int[] lengths = new int[rows.size()]; + int pos = 0; + for (int i = 0; i < rows.size(); i++) { + offsets[i] = pos; + final int[] row = rows.get(i); + if (row != null && row.length > 0) { + lengths[i] = row.length; + System.arraycopy(row, 0, data, pos, row.length); + pos += row.length; + } + } + return new FlatIntArray2D(data, offsets, lengths, rows.size()); + } + + /** + * Emits a flattened 2D array as three 1D arrays ({@code _data}, {@code _offsets}, + * {@code _lengths}) plus accessor methods. + * + *

Generated accessors: + *

    + *
  • {@code int NAME(int row, int col)} — element access
  • + *
  • {@code int NAME_length(int row)} — row length
  • + *
  • {@code int[] NAME_row(int row)} — copy of row (for for-each loops)
  • + *
+ * + * @param jcb the code builder + * @param indent leading whitespace + * @param vis visibility for the underlying arrays + * @param name base name (e.g. {@code "jjnextStateSet"}) + * @param flat the flattened data from {@link #flatten} + */ + static void emitFlatIntArray2D( + final JavaCodeBuilder jcb, final String indent, + final String vis, final String name, final FlatIntArray2D flat) { + + emitIntArray(jcb, indent, vis, name + "_data", flat.data); + emitIntArray(jcb, indent, vis, name + "_offsets", flat.offsets); + emitIntArray(jcb, indent, vis, name + "_lengths", flat.lengths); + + // Accessor: element by row+col + jcb.println(indent + "private static int " + name + "(final int row, final int col) {"); + jcb.println(indent + " return " + name + "_data[" + name + "_offsets[row] + col];"); + jcb.println(indent + "}"); + jcb.println(); + + // Accessor: row length + jcb.println(indent + "private static int " + name + "_length(final int row) {"); + jcb.println(indent + " return " + name + "_lengths[row];"); + jcb.println(indent + "}"); + jcb.println(); + + // Accessor: get row as array (for for-each compatibility in template) + jcb.println(indent + "private static int[] " + name + "_row(final int row) {"); + jcb.println(indent + " final int off = " + name + "_offsets[row];"); + jcb.println(indent + " final int len = " + name + "_lengths[row];"); + jcb.println(indent + " final int[] r = new int[len];"); + jcb.println(indent + " System.arraycopy(" + name + "_data, off, r, 0, len);"); + jcb.println(indent + " return r;"); + jcb.println(indent + "}"); + jcb.println(); + } + + // ---------------------------------------------------------------- + // Private helpers + // ---------------------------------------------------------------- + + private static void appendIntElements( + final JavaCodeBuilder jcb, final String indent, + final int[] data, final int from, final int to) { + jcb.println(); + for (int i = from; i < to; i++) { + if ((i - from) % ELEMENTS_PER_LINE == 0) { + if (i > from) { + jcb.println(); + } + jcb.print(indent); + } + jcb.print(data[i]); + if (i < to - 1) { + jcb.print(", "); + } + } + jcb.println(); + } +} diff --git a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java index fc34774..b788c7a 100644 --- a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java +++ b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java @@ -38,7 +38,6 @@ import java.util.Map; import org.javacc.parser.CodeGeneratorSettings; import org.javacc.parser.Context; -import org.javacc.parser.JavaCCGlobals; import org.javacc.parser.JavaCCParserConstants; import org.javacc.parser.Options; import org.javacc.parser.Token; @@ -49,619 +48,530 @@ /** Class that implements a table driven code generator for the token manager in Java. */ class TokenManagerCodeGenerator implements org.javacc.parser.TokenManagerCodeGenerator { - private static final String tokenManagerTemplate = "/templates/java/TokenManagerDriver.template"; - - private final Context context; - private JavaCodeBuilder jcb; - private static final String EOL = System.getProperty("line.separator"); - - TokenManagerCodeGenerator(final Context context) { - this.context = context; - } - - @Override - public void generateCode( - final CodeGeneratorSettings settings, final TokenizerData tokenizerData) { - - settings.putAll(Options.getOptions()); - - settings.put("maxOrdinal", tokenizerData.allMatches.size()); - settings.put("maxLexStates", tokenizerData.lexStateNames.length); - settings.put("nfaSize", tokenizerData.nfa.size()); - settings.put("charsVectorSize", ((Character.MAX_VALUE >> 6) + 1)); - settings.put("stateSetSize", tokenizerData.nfa.size()); - settings.put("parserName", tokenizerData.parserName); - settings.put("maxLongs", (tokenizerData.allMatches.size() / 64) + 1); - settings.put("parserName", tokenizerData.parserName); - settings.put("charStreamName", Options.getCharStreamName()); - settings.put("defaultLexState", tokenizerData.lexStateNames[tokenizerData.defaultLexState]); - settings.put("decls", tokenizerData.decls); - settings.put("generatedStates", tokenizerData.nfa.size()); - settings.put("initMatch", tokenizerData.initialMatchForLexState); - - final String tmSuperClass = (String) settings.get(Options.UO__TOKEN_MANAGER_SUPER_CLASS); - settings.put( - "tmSuperClass", - ((tmSuperClass == null) || tmSuperClass.equals("")) ? "" : "extends " + tmSuperClass); - settings.put("noDfa", Options.getNoDfa()); - - try { - - final File file = - new File(Options.getOutputDirectory(), tokenizerData.parserName + "TokenManager.java"); - jcb = JavaCodeBuilder.of(context, settings).setFile(file); - jcb.setPackageName(JavaUtil.parsePackage(context)); - - if (context.globals().cu_to_insertion_point_1.size() != 0) { - List tokens = null; - final Object firstToken = context.globals().cu_to_insertion_point_1.get(0); - jcb.printTokenSetup((Token) firstToken); - for (final Token t : context.globals().cu_to_insertion_point_1) { - if (t.kind == JavaCCParserConstants.IMPORT) { - tokens = new ArrayList<>(); - } else if ((tokens != null) && (t.kind == JavaCCParserConstants.SEMICOLON)) { - jcb.println("import", String.join("", tokens), ";"); - tokens = null; - } else if (tokens != null) { - tokens.add(CodeBuilder.toString(t)); - } - } - jcb.println(); - } + private static final String tokenManagerTemplate = "/templates/java/TokenManagerDriver.template"; - jcb.println("/* Beginning of code from " + tokenManagerTemplate + " */"); - jcb.println(); - jcb.printTemplate(tokenManagerTemplate); - jcb.println(); - jcb.println("/* End of code from " + tokenManagerTemplate + " */"); - jcb.println(); + private final Context context; + private JavaCodeBuilder jcb; + private static final String EOL = System.getProperty("line.separator"); - jcb.println(" /* Match info. */"); - jcb.println(); - dumpMatchInfo(jcb, tokenizerData); + TokenManagerCodeGenerator(final Context context) { + this.context = context; + } - if (!Options.getNoDfa()) { - jcb.println(" /* DFA tables. */"); - jcb.println(); - dumpDfaTables(jcb, tokenizerData); - } - - jcb.println(" /* NFA tables. */"); - jcb.println(); - dumpNfaTables(jcb, tokenizerData); - - jcb.println(" static {"); - if (!Options.getNoDfa()) { - jcb.println(" InitStartAndSize();"); - } - jcb.println(" initJjChars();"); - jcb.println(" }"); - jcb.println(); - jcb.println("}"); - - } catch (final IOException ioe) { - ioe.printStackTrace(); - assert (false); + @Override + public void generateCode(final CodeGeneratorSettings settings, final TokenizerData tokenizerData) { + settings.putAll(Options.getOptions()); + + settings.put("maxOrdinal", tokenizerData.allMatches.size()); + settings.put("maxLexStates", tokenizerData.lexStateNames.length); + settings.put("nfaSize", tokenizerData.nfa.size()); + settings.put("charsVectorSize", ((Character.MAX_VALUE >> 6) + 1)); + settings.put("stateSetSize", tokenizerData.nfa.size()); + settings.put("parserName", tokenizerData.parserName); + settings.put("maxLongs", (tokenizerData.allMatches.size() / 64) + 1); + settings.put("parserName", tokenizerData.parserName); + settings.put("charStreamName", Options.getCharStreamName()); + settings.put("defaultLexState", tokenizerData.lexStateNames[tokenizerData.defaultLexState]); + settings.put("decls", tokenizerData.decls); + settings.put("generatedStates", tokenizerData.nfa.size()); + settings.put("initMatch", tokenizerData.initialMatchForLexState); + + final String tmSuperClass = (String) settings.get(Options.UO__TOKEN_MANAGER_SUPER_CLASS); + settings.put( + "tmSuperClass", + ((tmSuperClass == null) || tmSuperClass.equals("")) ? "" : "extends " + tmSuperClass + ); + settings.put("noDfa", Options.getNoDfa()); + + try { + final File file = new File(Options.getOutputDirectory(), tokenizerData.parserName + "TokenManager.java"); + jcb = JavaCodeBuilder.of(context, settings).setFile(file); + jcb.setPackageName(JavaUtil.parsePackage(context)); + + if (context.globals().cu_to_insertion_point_1.size() != 0) { + List tokens = null; + final Object firstToken = context.globals().cu_to_insertion_point_1.get(0); + jcb.printTokenSetup((Token) firstToken); + for (final Token t : context.globals().cu_to_insertion_point_1) { + if (t.kind == JavaCCParserConstants.IMPORT) { + tokens = new ArrayList<>(); + } else if ((tokens != null) && (t.kind == JavaCCParserConstants.SEMICOLON)) { + jcb.println("import", String.join("", tokens), ";"); + tokens = null; + } else if (tokens != null) { + tokens.add(CodeBuilder.toString(t)); + } + } + jcb.println(); + } + + jcb.println("/* Beginning of code from " + tokenManagerTemplate + " */"); + jcb.println(); + jcb.printTemplate(tokenManagerTemplate); + jcb.println(); + jcb.println("/* End of code from " + tokenManagerTemplate + " */"); + jcb.println(); + + jcb.println(" /* Match info. */"); + jcb.println(); + dumpMatchInfo(jcb, tokenizerData); + + if (!Options.getNoDfa()) { + jcb.println(" /* DFA tables. */"); + jcb.println(); + dumpDfaTables(jcb, tokenizerData); + } + + jcb.println(" /* NFA tables. */"); + jcb.println(); + dumpNfaTables(jcb, tokenizerData); + + jcb.println(" static {"); + if (!Options.getNoDfa()) { + jcb.println(" InitStartAndSize();"); + } + jcb.println(" initJjChars();"); + jcb.println(" }"); + jcb.println(); + jcb.println("}"); + } catch (final IOException ioe) { + ioe.printStackTrace(); + assert (false); + } } - } - @Override - public void finish(final CodeGeneratorSettings settings, final TokenizerData tokenizerData) { + @Override + public void finish(final CodeGeneratorSettings settings, final TokenizerData tokenizerData) { + if (!Options.getBuildTokenManager()) { + return; + } - if (!Options.getBuildTokenManager()) { - return; + try { + jcb.close(); + } catch (final IOException ioe) { + ioe.printStackTrace(); + } } - try { - jcb.close(); - } catch (final IOException ioe) { - ioe.printStackTrace(); - } - } - - private static void dumpDfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { - - /* stringLiterals. */ - jcb.println(" // pairs of comment line & data line; format of comment line: // k, s"); - jcb.println( - " // k: key of map of lists of literals starting by char 'c', indexed by ((LexicalState << 16 | (int) c)"); - jcb.println(" // s: each string of the literals list for key k"); - jcb.println( - " // data line: len, ign_case (t/f=1/0), charAt(0..len-1), UCcharAt(0..len) if ic=true, kind, nfaStartState"); - jcb.println(" private static final int[] stringLiterals = {"); - int i = 0; - final Map startAndSize = new HashMap<>(); - for (final int key : tokenizerData.literalSequence.keySet()) { - final int[] arr = new int[2]; - final List l = tokenizerData.literalSequence.get(key); - final List kinds = tokenizerData.literalKinds.get(key); - arr[0] = i; - arr[1] = l.size(); - int j = 0; - if (i > 0) { - jcb.println(","); - } - for (final String s : l) { - if (j > 0) { - jcb.println(", "); - } - final int kind = kinds.get(j); - final boolean ignoreCase = tokenizerData.ignoreCaseKinds.contains(kind); - jcb.println(" // " + key + ", \"" + JavaCCGlobals.add_escapes(s) + "\""); - jcb.print(" "); - jcb.print(s.length()); - jcb.print(", "); - jcb.print(ignoreCase ? 1 : 0); - for (int k = 0; k < s.length(); k++) { - jcb.print(", "); - jcb.print((int) s.charAt(k)); - i++; + private static void dumpDfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { + /* stringLiterals — collect into int[], emit via init method to avoid overflow. */ + final List slData = new ArrayList<>(); + final Map startAndSize = new HashMap<>(); + for (final int key : tokenizerData.literalSequence.keySet()) { + final int[] arr = new int[2]; + final List l = tokenizerData.literalSequence.get(key); + final List kinds = tokenizerData.literalKinds.get(key); + arr[0] = slData.size(); + arr[1] = l.size(); + int j = 0; + for (final String s : l) { + final int kind = kinds.get(j); + final boolean ignoreCase = tokenizerData.ignoreCaseKinds.contains(kind); + slData.add(s.length()); + slData.add(ignoreCase ? 1 : 0); + for (int k = 0; k < s.length(); k++) { + slData.add((int) s.charAt(k)); + } + if (ignoreCase) { + for (int k = 0; k < s.length(); k++) { + slData.add((int) s.toUpperCase().charAt(k)); + } + } + slData.add(kind); + slData.add(tokenizerData.kindToNfaStartState.get(kind)); + j++; + } + startAndSize.put(key, arr); } - if (ignoreCase) { - for (int k = 0; k < s.length(); k++) { - jcb.print(", "); - jcb.print((int) s.toUpperCase().charAt(k)); - i++; - } + final int[] stringLiteralsArr = new int[slData.size()]; + for (int idx = 0; idx < slData.size(); idx++) { + stringLiteralsArr[idx] = slData.get(idx); } - jcb.print(", " + kind); - jcb.print(", " + tokenizerData.kindToNfaStartState.get(kind)); - i += 4; - j++; - } - startAndSize.put(key, arr); - } - jcb.println(); - jcb.println(" };"); - jcb.println(); - - /* startAndSize. */ - jcb.println(" private static final java.util.Map startAndSize ="); - jcb.println(" new java.util.HashMap();"); - jcb.println(); - - /* InitStartAndSize. */ - jcb.println(" // format of \"startAndSize.put(k, new int[] {ix, sz})\":"); - jcb.println( - " // k: key of map of lists of literals starting by char 'c', indexed by ((LexicalState << 16 | (int) c)"); - jcb.println(" // ix: index (list's start in stringLiterals)"); - jcb.println(" // sz: list's size"); - jcb.println(" private static void InitStartAndSize() {"); - for (final int key : tokenizerData.literalSequence.keySet()) { - final int[] arr = startAndSize.get(key); - jcb.println(" startAndSize.put(" + key + ", new int[] {" + arr[0] + ", " + arr[1] + "});"); - } - jcb.println(" }"); - jcb.println(); - } - - private static void dumpNfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { - - /* canMatchAnyChar. */ - jcb.print(" private static final int[] canMatchAnyChar = {"); - int v = 0; - for (int i = 0; i < tokenizerData.wildcardKind.size(); i++) { - if (v++ > 0) { - jcb.print(", "); - } else { + JavaArrayHelper.emitIntArray(jcb, " ", "private", "stringLiterals", stringLiteralsArr); + + /* startAndSize. */ + jcb.println(" private static final java.util.Map startAndSize ="); + jcb.println(" new java.util.HashMap();"); jcb.println(); - jcb.print(" "); - } - jcb.print(tokenizerData.wildcardKind.get(i)); - } - if (!tokenizerData.wildcardKind.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - - /* jjInitStates. */ - jcb.print(" private static final int[] jjInitStates = {"); - v = 0; - for (final int i : tokenizerData.initialStates.keySet()) { - if (v++ > 0) { - jcb.print(", "); - } else { + + /* InitStartAndSize. */ + jcb.println(" // format of \"startAndSize.put(k, new int[] {ix, sz})\":"); + jcb.println( + " // k: key of map of lists of literals starting by char 'c', indexed by ((LexicalState << 16 | (int) c)" + ); + jcb.println(" // ix: index (list's start in stringLiterals)"); + jcb.println(" // sz: list's size"); + jcb.println(" private static void InitStartAndSize() {"); + for (final int key : tokenizerData.literalSequence.keySet()) { + final int[] arr = startAndSize.get(key); + jcb.println(" startAndSize.put(" + key + ", new int[] {" + arr[0] + ", " + arr[1] + "});"); + } + jcb.println(" }"); jcb.println(); - jcb.print(" "); - } - jcb.print(tokenizerData.initialStates.get(i)); } - if (!tokenizerData.initialStates.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - - /* jjInitialMatchForLexState. */ - jcb.print(" private static final int[] jjInitialMatchForLexState = {"); - v = 0; - for (int i = 0; i < tokenizerData.lexStateNames.length; i++) { - if (v++ > 0) { - jcb.print(", "); - } else { + + private static void dumpNfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { + /* canMatchAnyChar. */ + jcb.print(" private static final int[] canMatchAnyChar = {"); + int v = 0; + for (int i = 0; i < tokenizerData.wildcardKind.size(); i++) { + if (v++ > 0) { + jcb.print(", "); + } else { + jcb.println(); + jcb.print(" "); + } + jcb.print(tokenizerData.wildcardKind.get(i)); + } + if (!tokenizerData.wildcardKind.isEmpty()) { + jcb.println(); + jcb.println(" };"); + } else { + jcb.println("};"); + } jcb.println(); - jcb.print(" "); - } - jcb.print(tokenizerData.initialMatchForLexState[i]); - } - jcb.println("};"); - jcb.println(); - - // We do the following for Java so that the generated code is reasonable - // size and can be compiled. May not be needed for other languages. - - /* EMPTY_CHAR_DATA. */ - jcb.println(" private static final long[] EMPTY_CHAR_DATA = new long[] {};"); - jcb.println(); - - /* CharDataConsts. */ - jcb.println(" private static final class CharDataConsts {"); - jcb.println(); - - /* jjCharData into a buffer. */ - final Map nfa = tokenizerData.nfa; - final Map charDataVars = new HashMap(); - final Map charDataCdbs = new HashMap(); - - final StringBuilder sb = new StringBuilder(64 + 18 * nfa.size()); - sb.append(" private static final long[][] jjCharData = {"); - final String charDataVarPrefix = "CHAR_DATA"; - final StringBuilder charDataBuilder = new StringBuilder(64); - for (int i = 0; i < nfa.size(); i++) { - if (i > 0) { - sb.append(',').append(EOL); - } else { - sb.append(EOL); - } - charDataBuilder.setLength(0); - // We have a lot of similar states. So factor them so we don't get "Code too large" errors. - final TokenizerData.NfaState tmp = nfa.get(i); - if (tmp == null) { - // sb.append(" EMPTY_CHAR_DATA").append(EOL); - sb.append(" /* ").append(i).append(" */ EMPTY_CHAR_DATA").append(EOL); - } else { - charDataBuilder.append("new long[] {"); - final BitSet bits = new BitSet(); - for (final char c : tmp.characters) { - bits.set(c); + + /* jjInitStates. */ + jcb.print(" private static final int[] jjInitStates = {"); + v = 0; + for (final int i : tokenizerData.initialStates.keySet()) { + if (v++ > 0) { + jcb.print(", "); + } else { + jcb.println(); + jcb.print(" "); + } + jcb.print(tokenizerData.initialStates.get(i)); } - final long[] longs = bits.toLongArray(); - for (int k = 0; k < longs.length; k++) { - int rep = 1; - while (((k + rep) < longs.length) && (longs[k + rep] == longs[k])) { - rep++; - } - if (k > 0) { - charDataBuilder.append(", "); - } - charDataBuilder.append(rep).append(", "); - charDataBuilder.append(Long.toString(longs[k])).append("L"); - k += rep - 1; + if (!tokenizerData.initialStates.isEmpty()) { + jcb.println(); + jcb.println(" };"); + } else { + jcb.println("};"); } - charDataBuilder.append("}"); - final String cdb = charDataBuilder.toString(); - String var = charDataVars.get(cdb); - if (var == null) { - var = charDataVarPrefix + (charDataVars.size() + 1); - charDataVars.put(cdb, var); - charDataCdbs.put(var, cdb); + jcb.println(); + + /* jjInitialMatchForLexState. */ + jcb.print(" private static final int[] jjInitialMatchForLexState = {"); + v = 0; + for (int i = 0; i < tokenizerData.lexStateNames.length; i++) { + if (v++ > 0) { + jcb.print(", "); + } else { + jcb.println(); + jcb.print(" "); + } + jcb.print(tokenizerData.initialMatchForLexState[i]); } - // sb.append(" " + var); - sb.append(" /* ").append(i).append(" */ ").append(var); - } - } - if (!nfa.isEmpty()) { - sb.append(EOL).append(" };").append(EOL); - } else { - sb.append(" };").append(EOL); - } + jcb.println("};"); + jcb.println(); - // in order, for easier comparison with C# & C++ - for (int k = 1; k <= charDataCdbs.size(); k++) { - final String key = charDataVarPrefix + Integer.toString(k); - jcb.println(" private static final long[] " + key + " = " + charDataCdbs.get(key) + ";"); - } - jcb.println(); - - // now print jjCharData buffer - jcb.println(sb); - - /* end class CharDataConsts. */ - jcb.println(" }"); - jcb.println(); - - /* EMPTY_STATE_SET. */ - jcb.println(" private static final int[] EMPTY_STATE_SET = new int[] {};"); - jcb.println(); - - /* jjcompositeState. */ - jcb.print(" private static final int[][] jjcompositeState = {"); - for (int i = 0; i < nfa.size(); i++) { - final TokenizerData.NfaState tmp = nfa.get(i); - if (i > 0) { - jcb.println(","); - } else { + // We do the following for Java so that the generated code is reasonable + // size and can be compiled. May not be needed for other languages. + + /* EMPTY_CHAR_DATA. */ + jcb.println(" private static final long[] EMPTY_CHAR_DATA = new long[] {};"); + jcb.println(); + + /* CharDataConsts. */ + jcb.println(" private static final class CharDataConsts {"); jcb.println(); - } - if (tmp == null || tmp.compositeStates.isEmpty()) { - // jcb.print(" EMPTY_STATE_SET"); - jcb.print(" /* " + i + " */ EMPTY_STATE_SET"); - } else { - // jcb.print(" new int[] { "); - jcb.print(" /* " + i + " */ new int[] { "); - int k = 0; - for (final int st : tmp.compositeStates) { - if (k++ > 0) { - jcb.print(", "); - } - jcb.print(st); + + /* jjCharData into a buffer. */ + final Map nfa = tokenizerData.nfa; + final Map charDataVars = new HashMap(); + final Map charDataCdbs = new HashMap(); + + final StringBuilder sb = new StringBuilder(64 + 18 * nfa.size()); + sb.append(" private static final long[][] jjCharData = {"); + final String charDataVarPrefix = "CHAR_DATA"; + final StringBuilder charDataBuilder = new StringBuilder(64); + for (int i = 0; i < nfa.size(); i++) { + if (i > 0) { + sb.append(',').append(EOL); + } else { + sb.append(EOL); + } + charDataBuilder.setLength(0); + // We have a lot of similar states. So factor them so we don't get "Code too large" errors. + final TokenizerData.NfaState tmp = nfa.get(i); + if (tmp == null) { + // sb.append(" EMPTY_CHAR_DATA").append(EOL); + sb.append(" /* ").append(i).append(" */ EMPTY_CHAR_DATA").append(EOL); + } else { + charDataBuilder.append("new long[] {"); + final BitSet bits = new BitSet(); + for (final char c : tmp.characters) { + bits.set(c); + } + final long[] longs = bits.toLongArray(); + for (int k = 0; k < longs.length; k++) { + int rep = 1; + while (((k + rep) < longs.length) && (longs[k + rep] == longs[k])) { + rep++; + } + if (k > 0) { + charDataBuilder.append(", "); + } + charDataBuilder.append(rep).append(", "); + charDataBuilder.append(Long.toString(longs[k])).append("L"); + k += rep - 1; + } + charDataBuilder.append("}"); + final String cdb = charDataBuilder.toString(); + String var = charDataVars.get(cdb); + if (var == null) { + var = charDataVarPrefix + (charDataVars.size() + 1); + charDataVars.put(cdb, var); + charDataCdbs.put(var, cdb); + } + // sb.append(" " + var); + sb.append(" /* ").append(i).append(" */ ").append(var); + } + } + if (!nfa.isEmpty()) { + sb.append(EOL).append(" };").append(EOL); + } else { + sb.append(" };").append(EOL); + } + + // in order, for easier comparison with C# & C++ + for (int k = 1; k <= charDataCdbs.size(); k++) { + final String key = charDataVarPrefix + Integer.toString(k); + jcb.println(" private static final long[] " + key + " = " + charDataCdbs.get(key) + ";"); } - jcb.print(" }"); - } - } - if (!nfa.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - - /* jjmatchKinds. */ - jcb.print(" private static final int[] jjmatchKinds = {"); - for (int i = 0; i < nfa.size(); i++) { - final TokenizerData.NfaState tmp = nfa.get(i); - if (i > 0) { - jcb.println(","); - } else { jcb.println(); - } - // jcb.print(" "); - jcb.print(" /* " + i + " */ "); - // TODO(sreeni) : Fix this mess. - jcb.print(tmp == null ? Integer.MAX_VALUE : tmp.kind); - } - if (!nfa.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - - /* jjnextStateSet. */ - jcb.print(" private static final int[][] jjnextStateSet = {"); - for (int i = 0; i < nfa.size(); i++) { - final TokenizerData.NfaState tmp = nfa.get(i); - if (i > 0) { - jcb.println(","); - } else { + + // now print jjCharData buffer + jcb.println(sb); + + /* end class CharDataConsts. */ + jcb.println(" }"); jcb.println(); - } - if (tmp == null || tmp.nextStates.isEmpty()) { - // jcb.print(" EMPTY_STATE_SET"); - jcb.print(" /* " + i + " */ EMPTY_STATE_SET"); - } else { - int k = 0; - // jcb.print(" new int[] { "); - jcb.print(" /* " + i + " */ new int[] { "); - for (final int s : tmp.nextStates) { - if (k++ > 0) { - jcb.print(", "); - } - jcb.print(s); - } - jcb.print(" }"); - } - } - if (!nfa.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - } - - private static void dumpMatchInfo(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { - final Map allMatches = tokenizerData.allMatches; - - // A bit ugly. - - final BitSet toSkip = new BitSet(allMatches.size()); - final BitSet toSpecial = new BitSet(allMatches.size()); - final BitSet toMore = new BitSet(allMatches.size()); - final BitSet toToken = new BitSet(allMatches.size()); - final int[] newStates = new int[allMatches.size()]; - toSkip.set(allMatches.size() + 1, true); - toToken.set(allMatches.size() + 1, true); - toMore.set(allMatches.size() + 1, true); - toSpecial.set(allMatches.size() + 1, true); - - /* jjstrLiteralImages. */ - jcb.println(" public static final String[] jjstrLiteralImages = {"); - int k = 0; - for (int i = 0; i < allMatches.size(); i++) { - final TokenizerData.MatchInfo matchInfo = allMatches.get(i); - switch (matchInfo.matchType) { - case SKIP: - toSkip.set(i); - break; - case SPECIAL_TOKEN: - toSpecial.set(i); - break; - case MORE: - toMore.set(i); - break; - case TOKEN: - toToken.set(i); - break; - } - newStates[i] = matchInfo.newLexState; - final String image = matchInfo.image; - if (k++ > 0) { - jcb.println(","); - } - if (image != null) { - jcb.print(" \""); - for (int j = 0; j < image.length(); j++) { - final int cj = image.charAt(j); - switch (cj) { - case '\b': - jcb.print("\\b"); - continue; - case '\t': - jcb.print("\\t"); - continue; - case '\n': - jcb.print("\\n"); - continue; - case '\f': - jcb.print("\\f"); - continue; - case '\r': - jcb.print("\\r"); - continue; - case '\"': - jcb.print("\\\""); - continue; - case '\'': - jcb.print("\\\'"); - continue; - case '\\': - jcb.print("\\\\"); - continue; - default: - if (cj <= 0xff) { - if (cj < 0x20 || (cj > 0x7e)) { - jcb.print("0x" + Integer.toHexString(cj)); - } else { - jcb.print(image.charAt(j)); + + /* jjcompositeState and jjnextStateSet are now flattened; EMPTY_STATE_SET no longer needed. */ + + /* jjcompositeState — flatten int[][] to 1D for clinit safety and cache efficiency. */ + final List compositeRows = new ArrayList<>(nfa.size()); + for (int i = 0; i < nfa.size(); i++) { + final TokenizerData.NfaState tmp = nfa.get(i); + if (tmp == null || tmp.compositeStates.isEmpty()) { + compositeRows.add(null); + } else { + final int[] row = new int[tmp.compositeStates.size()]; + int k = 0; + for (final int st : tmp.compositeStates) { + row[k++] = st; } - } else { - String hexVal = Integer.toHexString(image.charAt(j)); - if (hexVal.length() == 3) { - hexVal = "0" + hexVal; + compositeRows.add(row); + } + } + final JavaArrayHelper.FlatIntArray2D flatComposite = JavaArrayHelper.flatten(compositeRows); + JavaArrayHelper.emitFlatIntArray2D(jcb, " ", "private", "jjcompositeState", flatComposite); + + /* jjmatchKinds — emit via init method. */ + final int[] matchKindsArr = new int[nfa.size()]; + for (int i = 0; i < nfa.size(); i++) { + final TokenizerData.NfaState tmp = nfa.get(i); + matchKindsArr[i] = (tmp == null) ? Integer.MAX_VALUE : tmp.kind; + } + JavaArrayHelper.emitIntArray(jcb, " ", "private", "jjmatchKinds", matchKindsArr); + + /* jjnextStateSet — flatten int[][] to 1D for clinit safety and cache efficiency. */ + final List nextStateRows = new ArrayList<>(nfa.size()); + for (int i = 0; i < nfa.size(); i++) { + final TokenizerData.NfaState tmp = nfa.get(i); + if (tmp == null || tmp.nextStates.isEmpty()) { + nextStateRows.add(null); + } else { + final int[] row = new int[tmp.nextStates.size()]; + int k = 0; + for (final int s : tmp.nextStates) { + row[k++] = s; } - jcb.print("\\u" + hexVal); - } - continue; - } + nextStateRows.add(row); + } } - jcb.print("\""); - } else { - jcb.print(" null"); - } + final JavaArrayHelper.FlatIntArray2D flatNextState = JavaArrayHelper.flatten(nextStateRows); + JavaArrayHelper.emitFlatIntArray2D(jcb, " ", "private", "jjnextStateSet", flatNextState); } - jcb.println(); - jcb.println(" };"); - jcb.println(); - - /* Bit masks. */ - generateBitVector(jcb, "jjtoToken", toToken); - jcb.println(); - generateBitVector(jcb, "jjtoSkip", toSkip); - jcb.println(); - generateBitVector(jcb, "jjtoSpecial", toSpecial); - jcb.println(); - generateBitVector(jcb, "jjtoMore", toMore); - jcb.println(); - - /* jjnewLexState. */ - jcb.println(" private static final int[] jjnewLexState = {"); - for (int i = 0; i < newStates.length; i++) { - if (i > 0) { - jcb.print(", "); - } else { - jcb.print(" "); - } - // codeGenerator.genCode("0x" + Integer.toHexString(newStates[i])); - jcb.print(Integer.toString(newStates[i])); + + private static void dumpMatchInfo(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { + final Map allMatches = tokenizerData.allMatches; + + // A bit ugly. + + final BitSet toSkip = new BitSet(allMatches.size()); + final BitSet toSpecial = new BitSet(allMatches.size()); + final BitSet toMore = new BitSet(allMatches.size()); + final BitSet toToken = new BitSet(allMatches.size()); + final int[] newStates = new int[allMatches.size()]; + toSkip.set(allMatches.size() + 1, true); + toToken.set(allMatches.size() + 1, true); + toMore.set(allMatches.size() + 1, true); + toSpecial.set(allMatches.size() + 1, true); + + /* jjstrLiteralImages — collect into String[], emit via init method. */ + final String[] literalImages = new String[allMatches.size()]; + for (int i = 0; i < allMatches.size(); i++) { + final TokenizerData.MatchInfo matchInfo = allMatches.get(i); + switch (matchInfo.matchType) { + case SKIP: + toSkip.set(i); + break; + case SPECIAL_TOKEN: + toSpecial.set(i); + break; + case MORE: + toMore.set(i); + break; + case TOKEN: + toToken.set(i); + break; + } + newStates[i] = matchInfo.newLexState; + final String image = matchInfo.image; + if (image != null) { + final StringBuilder imgBuilder = new StringBuilder("\""); + for (int j = 0; j < image.length(); j++) { + final int cj = image.charAt(j); + switch (cj) { + case '\b': + imgBuilder.append("\\b"); + continue; + case '\t': + imgBuilder.append("\\t"); + continue; + case '\n': + imgBuilder.append("\\n"); + continue; + case '\f': + imgBuilder.append("\\f"); + continue; + case '\r': + imgBuilder.append("\\r"); + continue; + case '\"': + imgBuilder.append("\\\""); + continue; + case '\'': + imgBuilder.append("\\\'"); + continue; + case '\\': + imgBuilder.append("\\\\"); + continue; + default: + if (cj <= 0xff) { + if (cj < 0x20 || (cj > 0x7e)) { + imgBuilder.append("0x").append(Integer.toHexString(cj)); + } else { + imgBuilder.append(image.charAt(j)); + } + } else { + String hexVal = Integer.toHexString(image.charAt(j)); + if (hexVal.length() == 3) { + hexVal = "0" + hexVal; + } + imgBuilder.append("\\u").append(hexVal); + } + continue; + } + } + imgBuilder.append("\""); + literalImages[i] = imgBuilder.toString(); + } + // null entries stay null in the array + } + JavaArrayHelper.emitStringArray(jcb, " ", "public", "jjstrLiteralImages", literalImages); + + /* Bit masks. */ + generateBitVector(jcb, "jjtoToken", toToken); + jcb.println(); + generateBitVector(jcb, "jjtoSkip", toSkip); + jcb.println(); + generateBitVector(jcb, "jjtoSpecial", toSpecial); + jcb.println(); + generateBitVector(jcb, "jjtoMore", toMore); + jcb.println(); + + /* jjnewLexState — emit via init method. */ + JavaArrayHelper.emitIntArray(jcb, " ", "private", "jjnewLexState", newStates); + + // Action functions. + + final String staticString = Options.getStatic() ? " static " : " "; + + // Token actions. + jcb.println(staticString + "void TokenLexicalActions(Token matchedToken) {"); + jcb.println(" // TOKEN lexical actions"); + // dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.TOKEN, "matchedToken.kind"); + dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.TOKEN, "jjmatchedKind"); + jcb.println(" }"); + jcb.println(); + + // Skip actions. + // TODO(sreeni) : Streamline this mess. + jcb.println(staticString + "void SkipLexicalActions(Token matchedToken) {"); + jcb.println(" // SKIP lexical actions"); + dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.SKIP, "jjmatchedKind"); + // jcb.println(" // SPECIAL_TOKEN lexical actions"); + // dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.SPECIAL_TOKEN, + // "jjmatchedKind"); + jcb.println(" }"); + jcb.println(); + + // More actions. + jcb.println(staticString + "void MoreLexicalActions() {"); + // jcb.println(" jjimageLen += (lengthOfMatch = jjmatchedPos + 1);"); + jcb.println(" // MORE lexical actions"); + dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.MORE, "jjmatchedKind"); + jcb.println(" }"); + jcb.println(); } - jcb.println(); - jcb.println(" };"); - jcb.println(); - - // Action functions. - - final String staticString = Options.getStatic() ? " static " : " "; - - // Token actions. - jcb.println(staticString + "void TokenLexicalActions(Token matchedToken) {"); - jcb.println(" // TOKEN lexical actions"); - // dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.TOKEN, "matchedToken.kind"); - dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.TOKEN, "jjmatchedKind"); - jcb.println(" }"); - jcb.println(); - - // Skip actions. - // TODO(sreeni) : Streamline this mess. - jcb.println(staticString + "void SkipLexicalActions(Token matchedToken) {"); - jcb.println(" // SKIP lexical actions"); - dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.SKIP, "jjmatchedKind"); - // jcb.println(" // SPECIAL_TOKEN lexical actions"); - // dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.SPECIAL_TOKEN, - // "jjmatchedKind"); - jcb.println(" }"); - jcb.println(); - - // More actions. - jcb.println(staticString + "void MoreLexicalActions() {"); - // jcb.println(" jjimageLen += (lengthOfMatch = jjmatchedPos + 1);"); - jcb.println(" // MORE lexical actions"); - dumpLexicalActions(jcb, allMatches, TokenizerData.MatchType.MORE, "jjmatchedKind"); - jcb.println(" }"); - jcb.println(); - } - - private static void dumpLexicalActions( - final JavaCodeBuilder jcb, - final Map allMatches, - final TokenizerData.MatchType matchType, - final String kindString) { - - jcb.println(" switch (" + kindString + ") {"); - for (final int i : allMatches.keySet()) { - final TokenizerData.MatchInfo matchInfo = allMatches.get(i); - if ((matchInfo.action == null) || (matchInfo.matchType != matchType)) { - continue; - } - jcb.println(" case " + i + ": {"); - // TODO check (MMa start added) comes from v7 output cf. JSqlParser - if (matchInfo.matchType == MatchType.SKIP) { - } else if (matchInfo.matchType == MatchType.MORE) { - jcb.println(" jjimageLen += (lengthOfMatch = jjmatchedPos);"); - } else if (matchInfo.matchType == MatchType.TOKEN) { - jcb.println( - " image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos)));"); - } - // TODO check (MMa end added) - jcb.println(" " + matchInfo.action.trim()); - jcb.println(" break;"); - jcb.println(" }"); + + private static void dumpLexicalActions( + final JavaCodeBuilder jcb, + final Map allMatches, + final TokenizerData.MatchType matchType, + final String kindString + ) { + jcb.println(" switch (" + kindString + ") {"); + for (final int i : allMatches.keySet()) { + final TokenizerData.MatchInfo matchInfo = allMatches.get(i); + if ((matchInfo.action == null) || (matchInfo.matchType != matchType)) { + continue; + } + jcb.println(" case " + i + ": {"); + // TODO check (MMa start added) comes from v7 output cf. JSqlParser + if (matchInfo.matchType == MatchType.SKIP) { + } else if (matchInfo.matchType == MatchType.MORE) { + jcb.println(" jjimageLen += (lengthOfMatch = jjmatchedPos);"); + } else if (matchInfo.matchType == MatchType.TOKEN) { + jcb.println( + " image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos)));" + ); + } + // TODO check (MMa end added) + jcb.println(" " + matchInfo.action.trim()); + jcb.println(" break;"); + jcb.println(" }"); + } + jcb.println(" default: break;"); + jcb.println(" }"); } - jcb.println(" default: break;"); - jcb.println(" }"); - } - - private static void generateBitVector( - final JavaCodeBuilder jcb, final String name, final BitSet bits) { - jcb.println(); - jcb.println(" private static final long[] " + name + " = {"); - final long[] longs = bits.toLongArray(); - for (int i = 0; i < longs.length; i++) { - if (i > 0) { - jcb.print(","); - } - // codeGenerator.genCode("0x" + Long.toHexString(longs[i]) + "L"); - jcb.print(" " + Long.toString(longs[i]) + "L"); + + private static void generateBitVector(final JavaCodeBuilder jcb, final String name, final BitSet bits) { + jcb.println(); + jcb.println(" private static final long[] " + name + " = {"); + final long[] longs = bits.toLongArray(); + for (int i = 0; i < longs.length; i++) { + if (i > 0) { + jcb.print(","); + } + // codeGenerator.genCode("0x" + Long.toHexString(longs[i]) + "L"); + jcb.print(" " + Long.toString(longs[i]) + "L"); + } + jcb.println(); + jcb.println(" };"); } - jcb.println(); - jcb.println(" };"); - } } diff --git a/src/main/resources/templates/java/TokenManagerDriver.template b/src/main/resources/templates/java/TokenManagerDriver.template index fda7648..cb79a7a 100644 --- a/src/main/resources/templates/java/TokenManagerDriver.template +++ b/src/main/resources/templates/java/TokenManagerDriver.template @@ -496,7 +496,7 @@ ${decls} // Some NFA states have epsilon transitions (move on empty string). // So we just start with all of them. Note that the nextStates array already adds // the epsilon closure. Only the initial state needs to do this explicitly. - for (int s : jjcompositeState[startState]) { + for (int s : jjcompositeState_row(startState)) { if (moved[s] != moveIndex) { stateSet[cnt++] = s; moved[s] = moveIndex; @@ -538,7 +538,7 @@ ${decls} if ((jjChars[state][vectorIndex] & bitpattern) != 0L) { // Current input character can move this NFA state. // So add all the next states of the current states for use with the next input char. - for (int newState : jjnextStateSet[state]) { + for (int newState : jjnextStateSet_row(state)) { if (moved[newState] != moveIndex) { // We add each state only once. newStateSet[newCnt++] = newState; From d6234212d361eb1335467e0bde0f3b8b9c5f93f5 Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Fri, 10 Apr 2026 22:52:23 +0700 Subject: [PATCH 02/12] Remove dead DBG_EXP debug code from generated parser and increase JJCalls GC threshold Strip all `if (DBG_EXP) System.out.println(...)` emissions from the Java parser code generator. These produced dead branches in the generated parser (DBG_EXP is a `static final boolean = false` constant) that inflated jj_scan_token bytecode, reducing HotSpot's ability to inline this critical method which is called from every phase-3 lookahead routine. Also increase MAX_NB_POS from 100 to 512, reducing the frequency of the JJCalls cleanup sweep in jj_consume_token from every 100 to every 512 consumed tokens. Both changes are logic-free: no control flow, branching, or error reporting behavior is altered. --- .../org/javacc/java/ParserCodeGenerator.java | 82 +------------------ 1 file changed, 1 insertion(+), 81 deletions(-) diff --git a/src/main/java/org/javacc/java/ParserCodeGenerator.java b/src/main/java/org/javacc/java/ParserCodeGenerator.java index 40d4c25..8a8c0b1 100644 --- a/src/main/java/org/javacc/java/ParserCodeGenerator.java +++ b/src/main/java/org/javacc/java/ParserCodeGenerator.java @@ -874,7 +874,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" }"); cb.println(); - cb.println(" private static final boolean DBG_EXP = false;"); cb.println(); if (context.globals().jj2index != 0) { @@ -909,18 +908,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.print(", final String loc"); } cb.println(") {"); - cb.println(" if (DBG_EXP) System.out.println(\"scan1: kind = \" + kind +"); - if (Options.getErrorReporting()) { - cb.println(" \", loc = \" + loc +"); - } - cb.println(" \", jj_la = \" + jj_la +"); - cb.println(" \", jj_scanpos = \" + jj_scanpos + \" \" + jj_scanpos.hashCode() +"); - if (Options.getErrorReporting()) { - cb.println(" \", jj_lastpos = \" + jj_lastpos + \" \" + jj_lastpos.hashCode() +"); - cb.println(" \", jj_rescan = \" + jj_rescan);"); - } else { - cb.println(" \", jj_lastpos = \" + jj_lastpos + \" \" + jj_lastpos.hashCode());"); - } cb.println(" if (jj_scanpos == jj_lastpos) {"); cb.println(" jj_la--;"); cb.println(" if (jj_scanpos.next == null) {"); @@ -951,22 +938,12 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData } else if (Options.getDebugLookahead()) { cb.println(" trace_scan(jj_scanpos, kind);"); } - cb.println(" if (DBG_EXP) System.out.println(\"scan2: kind = \" + kind +"); - cb.println(" \", jj_scanpos.kind = \" + jj_scanpos.kind +"); - cb.println(" \", jj_la = \" + jj_la +"); - cb.println(" \", jj_scanpos = \" + jj_scanpos + \" \" + jj_scanpos.hashCode() +"); - cb.println(" \", jj_lastpos = \" + jj_lastpos + \" \" + jj_lastpos.hashCode());"); cb.println(" if (jj_scanpos.kind != kind) {"); cb.println(" return LA_Scan_Token_Failure;"); cb.println(" }"); cb.println(" if (jj_la == 0 && jj_scanpos == jj_lastpos) {"); cb.println(" throw jj_ls;"); cb.println(" }"); - cb.println(" if (DBG_EXP) System.out.println(\"scan3: kind = \" + kind +"); - cb.println(" \", jj_scanpos.kind = \" + jj_scanpos.kind +"); - cb.println(" \", jj_la = \" + jj_la +"); - cb.println(" \", jj_scanpos = \" + jj_scanpos + \" \" + jj_scanpos.hashCode() +"); - cb.println(" \", jj_lastpos = \" + jj_lastpos + \" \" + jj_lastpos.hashCode());"); cb.println(" return LA_Scan_Token_Success;"); cb.println(" }"); cb.println(); @@ -1043,7 +1020,7 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" private " + pStatic + "int jj_kind = -1;"); cb.println(" private " + pStatic + "int[] jj_expentry;"); cb.println(" private " + pStatic + "String[] jj_expentry_loc;"); - cb.println(" private static final int MAX_NB_POS = 100;"); + cb.println(" private static final int MAX_NB_POS = 512;"); if (context.globals().jj2index != 0) { cb.println(" private " + pStatic + "int[] jj_lasttokens = new int[MAX_NB_POS];"); cb.println( @@ -1054,25 +1031,9 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData /* jj_add_error_token(int kind, int pos) */ cb.println( " private " + pStatic + "void jj_add_error_token(int kind, int pos, String loc) {"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_add_error_token: kind = \" + kind +"); - cb.println( - " \", pos = \" + pos + \", loc = \" + loc + \", jj_endpos = \" + jj_endpos);"); cb.println(" if (pos >= MAX_NB_POS) {"); cb.println(" return;"); cb.println(" }"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_lasttokens = \" + java.util.Arrays.toString(jj_lasttokens));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_lasttokens_loc = \" + java.util.Arrays.toString(jj_lasttokens_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_expentry = \" + java.util.Arrays.toString(jj_expentry));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_expentry_loc = \" + java.util.Arrays.toString(jj_expentry_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_expentries = \" + java.util.Arrays.deepToString(jj_expentries.toArray()));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet1: jj_expentries_loc = \" + java.util.Arrays.deepToString(jj_expentries_loc.toArray()));"); cb.println(" if (pos == jj_endpos + 1) {"); cb.println(" jj_lasttokens[jj_endpos] = kind;"); cb.println(" jj_lasttokens_loc[jj_endpos] = loc;"); @@ -1106,18 +1067,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" jj_endpos = pos;"); cb.println(" }"); cb.println(" }"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_lasttokens = \" + java.util.Arrays.toString(jj_lasttokens));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_lasttokens_loc = \" + java.util.Arrays.toString(jj_lasttokens_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_expentry = \" + java.util.Arrays.toString(jj_expentry));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_expentry_loc = \" + java.util.Arrays.toString(jj_expentry_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_expentries = \" + java.util.Arrays.deepToString(jj_expentries.toArray()));"); - cb.println( - " if (DBG_EXP) System.out.println(\"aet2: jj_expentries_loc = \" + java.util.Arrays.deepToString(jj_expentries_loc.toArray()));"); cb.println(" }"); } cb.println(); @@ -1126,20 +1075,8 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" /** Generate a ParseException. */"); cb.println( " public " + pStatic + "ParseException generateParseException(final String loc) {"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_la1 = \" + java.util.Arrays.toString(jj_la1));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_la1_loc = \" + java.util.Arrays.toString(jj_la1_loc));"); cb.println(" jj_expentries.clear();"); cb.println(" jj_expentries_loc.clear();"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_expentry = \" + java.util.Arrays.toString(jj_expentry));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_expentry_loc = \" + java.util.Arrays.toString(jj_expentry_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_expentries = \" + java.util.Arrays.deepToString(jj_expentries.toArray()));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe1: jj_expentries_loc = \" + java.util.Arrays.deepToString(jj_expentries_loc.toArray()));"); cb.println( " final boolean[] la1tokens = new boolean[" + context.globals().tokenCount @@ -1163,10 +1100,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" }"); cb.println(" }"); cb.println(" }"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe2: la1tokens = \" + java.util.Arrays.toString(la1tokens));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe2: la1tokens_loc = \" + java.util.Arrays.toString(la1tokens_loc));"); cb.println(" for (int k = 0; k < " + context.globals().tokenCount + "; k++) {"); cb.println(" if (la1tokens[k]) {"); cb.println(" jj_expentry = new int[1];"); @@ -1177,14 +1110,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" jj_expentries_loc.add(jj_expentry_loc);"); cb.println(" }"); cb.println(" }"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe3: jj_expentry = \" + java.util.Arrays.toString(jj_expentry));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe3: jj_expentry_loc = \" + java.util.Arrays.toString(jj_expentry_loc));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe3: jj_expentries = \" + java.util.Arrays.deepToString(jj_expentries.toArray()));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe3: jj_expentries_loc = \" + java.util.Arrays.deepToString(jj_expentries_loc.toArray()));"); if (context.globals().jj2index != 0) { cb.println(" jj_endpos = 0;"); cb.println(" jj_rescan_token();"); @@ -1200,10 +1125,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" exptokseqloc[x] = jj_expentries_loc.get(x);"); // } cb.println(" }"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe4: exptokseq = \" + java.util.Arrays.deepToString(exptokseq));"); - cb.println( - " if (DBG_EXP) System.out.println(\"gpe4: exptokseqloc = \" + java.util.Arrays.deepToString(exptokseqloc));"); if (isJavaModernMode) { cb.println( " return new ParseException(token, exptokseq, exptokseqloc, tokenImage, loc, "); @@ -1255,7 +1176,6 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData + JavaTemplates.getTokenMgrErrorClass() + ".addEscapes(t.image) + \"\\\"\";"); cb.println(" }"); - cb.println(" if (DBG_EXP) s += \" / \" + t.hashCode();"); cb.println(" s += \">\";"); cb.println(" return s;"); cb.println(" }"); From 468d53ca0b0e9979024d2320288c473ff5c3e644 Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Fri, 10 Apr 2026 22:59:59 +0700 Subject: [PATCH 03/12] Use two-arg Token.newToken(kind, image) in jjFillToken to avoid redundant field writes The default code path in jjFillToken created tokens via the one-arg Token.newToken(kind), which sets image to null, then immediately overwrote both t.kind (redundant, already set by constructor) and t.image. Switch to the two-arg Token.newToken(kind, image) that was already available behind the BINARY_NEW_TOKEN option flag, making it the unconditional default. This eliminates two field writes per token created. The BINARY_NEW_TOKEN conditional is removed as it is now the default path. --- .../resources/templates/java/TokenManagerDriver.template | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/resources/templates/java/TokenManagerDriver.template b/src/main/resources/templates/java/TokenManagerDriver.template index cb79a7a..d8b1bde 100644 --- a/src/main/resources/templates/java/TokenManagerDriver.template +++ b/src/main/resources/templates/java/TokenManagerDriver.template @@ -350,12 +350,8 @@ ${decls} } #if TOKEN_FACTORY final Token t = ${TOKEN_FACTORY}.newToken(jjmatchedKind, curTokenImage); -#elif BINARY_NEW_TOKEN - final Token t = Token.newToken(jjmatchedKind, curTokenImage); #else - final Token t = Token.newToken(jjmatchedKind); - t.kind = jjmatchedKind; - t.image = curTokenImage; + final Token t = Token.newToken(jjmatchedKind, curTokenImage); #fi #if KEEP_LINE_COLUMN t.beginLine = beginLine; From 32ebe98780768193661b96e772b4537b70ea89f8 Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Fri, 10 Apr 2026 23:14:56 +0700 Subject: [PATCH 04/12] Eliminate per-transition array allocation in NFA engine hot loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The jjMoveNfa inner loop called jjnextStateSet_row(state) on every NFA state transition and jjcompositeState_row(startState) for epsilon closure initialization. Both methods allocated a new int[] and did a System.arraycopy on every call — in the hottest loop of the tokenizer. Replace with direct indexed iteration over the existing flat data arrays (jjnextStateSet_data/offsets/lengths and jjcompositeState_data/ offsets/lengths). Same data, same order, zero allocation. The _row helper methods become dead code. Also includes the previously confirmed Token.newToken two-arg change (eliminates redundant kind/image field writes in jjFillToken). --- .../java/TokenManagerDriver.template | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/main/resources/templates/java/TokenManagerDriver.template b/src/main/resources/templates/java/TokenManagerDriver.template index d8b1bde..139bc21 100644 --- a/src/main/resources/templates/java/TokenManagerDriver.template +++ b/src/main/resources/templates/java/TokenManagerDriver.template @@ -492,10 +492,15 @@ ${decls} // Some NFA states have epsilon transitions (move on empty string). // So we just start with all of them. Note that the nextStates array already adds // the epsilon closure. Only the initial state needs to do this explicitly. - for (int s : jjcompositeState_row(startState)) { - if (moved[s] != moveIndex) { - stateSet[cnt++] = s; - moved[s] = moveIndex; + { + final int _csOff = jjcompositeState_offsets[startState]; + final int _csLen = jjcompositeState_lengths[startState]; + for (int _j = 0; _j < _csLen; _j++) { + final int s = jjcompositeState_data[_csOff + _j]; + if (moved[s] != moveIndex) { + stateSet[cnt++] = s; + moved[s] = moveIndex; + } } } @@ -534,11 +539,16 @@ ${decls} if ((jjChars[state][vectorIndex] & bitpattern) != 0L) { // Current input character can move this NFA state. // So add all the next states of the current states for use with the next input char. - for (int newState : jjnextStateSet_row(state)) { - if (moved[newState] != moveIndex) { - // We add each state only once. - newStateSet[newCnt++] = newState; - moved[newState] = moveIndex; + { + final int _nsOff = jjnextStateSet_offsets[state]; + final int _nsLen = jjnextStateSet_lengths[state]; + for (int _k = 0; _k < _nsLen; _k++) { + final int newState = jjnextStateSet_data[_nsOff + _k]; + if (moved[newState] != moveIndex) { + // We add each state only once. + newStateSet[newCnt++] = newState; + moved[newState] = moveIndex; + } } } int newKind = jjmatchKinds[state]; From 22ddac53c3d27838469190c5a746ab6c5225d825 Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Fri, 10 Apr 2026 23:30:10 +0700 Subject: [PATCH 05/12] Replace HashMap with sorted int[] binary search in string literal matching The startAndSize map in jjRunStringLiteralMatch used a HashMap to look up string literal match candidates by (lexState << 16 | firstChar). Every lookup autoboxed the int key to Integer. Replace with two sorted parallel int[] arrays (ssKeys, ssValues) and java.util.Arrays.binarySearch for zero-boxing lookup. For typical grammars with ~50-100 entries, binary search takes 6-7 int comparisons vs HashMap hash+equals+chain traversal. Also eliminates the InitStartAndSize() method and its 55 individual HashMap.put calls with new int[] allocations at class load time. --- .../java/TokenManagerCodeGenerator.java | 83 ++++++++++--------- .../java/TokenManagerDriver.template | 8 +- 2 files changed, 50 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java index b788c7a..6bf58c1 100644 --- a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java +++ b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java @@ -128,7 +128,7 @@ public void generateCode(final CodeGeneratorSettings settings, final TokenizerDa jcb.println(" static {"); if (!Options.getNoDfa()) { - jcb.println(" InitStartAndSize();"); + // ssKeys/ssValues are static final arrays; no init needed } jcb.println(" initJjChars();"); jcb.println(" }"); @@ -155,58 +155,65 @@ public void finish(final CodeGeneratorSettings settings, final TokenizerData tok private static void dumpDfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { /* stringLiterals — collect into int[], emit via init method to avoid overflow. */ - final List slData = new ArrayList<>(); - final Map startAndSize = new HashMap<>(); + // Pre-calculate total size to avoid boxing overhead from List. + int totalSize = 0; + for (final int key : tokenizerData.literalSequence.keySet()) { + final List l = tokenizerData.literalSequence.get(key); + final List kinds = tokenizerData.literalKinds.get(key); + int j = 0; + for (final String s : l) { + final int kind = kinds.get(j); + final boolean ignoreCase = tokenizerData.ignoreCaseKinds.contains(kind); + // length + ignoreCase flag + chars + (uppercased chars if ignoreCase) + kind + nfaStartState + totalSize += 2 + s.length() + (ignoreCase ? s.length() : 0) + 2; + j++; + } + } + final int[] slData = new int[totalSize]; + int slPos = 0; + final Map startAndSize = new HashMap<>(tokenizerData.literalSequence.size() * 4 / 3 + 1); for (final int key : tokenizerData.literalSequence.keySet()) { final int[] arr = new int[2]; final List l = tokenizerData.literalSequence.get(key); final List kinds = tokenizerData.literalKinds.get(key); - arr[0] = slData.size(); + arr[0] = slPos; arr[1] = l.size(); int j = 0; for (final String s : l) { final int kind = kinds.get(j); final boolean ignoreCase = tokenizerData.ignoreCaseKinds.contains(kind); - slData.add(s.length()); - slData.add(ignoreCase ? 1 : 0); + slData[slPos++] = s.length(); + slData[slPos++] = ignoreCase ? 1 : 0; for (int k = 0; k < s.length(); k++) { - slData.add((int) s.charAt(k)); + slData[slPos++] = s.charAt(k); } if (ignoreCase) { - for (int k = 0; k < s.length(); k++) { - slData.add((int) s.toUpperCase().charAt(k)); + final String upper = s.toUpperCase(); + for (int k = 0; k < upper.length(); k++) { + slData[slPos++] = upper.charAt(k); } } - slData.add(kind); - slData.add(tokenizerData.kindToNfaStartState.get(kind)); + slData[slPos++] = kind; + slData[slPos++] = tokenizerData.kindToNfaStartState.get(kind); j++; } startAndSize.put(key, arr); } - final int[] stringLiteralsArr = new int[slData.size()]; - for (int idx = 0; idx < slData.size(); idx++) { - stringLiteralsArr[idx] = slData.get(idx); - } - JavaArrayHelper.emitIntArray(jcb, " ", "private", "stringLiterals", stringLiteralsArr); - - /* startAndSize. */ - jcb.println(" private static final java.util.Map startAndSize ="); - jcb.println(" new java.util.HashMap();"); - jcb.println(); - - /* InitStartAndSize. */ - jcb.println(" // format of \"startAndSize.put(k, new int[] {ix, sz})\":"); - jcb.println( - " // k: key of map of lists of literals starting by char 'c', indexed by ((LexicalState << 16 | (int) c)" - ); - jcb.println(" // ix: index (list's start in stringLiterals)"); - jcb.println(" // sz: list's size"); - jcb.println(" private static void InitStartAndSize() {"); - for (final int key : tokenizerData.literalSequence.keySet()) { - final int[] arr = startAndSize.get(key); - jcb.println(" startAndSize.put(" + key + ", new int[] {" + arr[0] + ", " + arr[1] + "});"); + JavaArrayHelper.emitIntArray(jcb, " ", "private", "stringLiterals", slData); + + /* startAndSize — sorted parallel arrays for binary-search lookup (no autoboxing). */ + final List sortedKeys = new ArrayList<>(startAndSize.keySet()); + java.util.Collections.sort(sortedKeys); + final int[] ssKeysArr = new int[sortedKeys.size()]; + final int[] ssValuesArr = new int[sortedKeys.size() * 2]; + for (int idx = 0; idx < sortedKeys.size(); idx++) { + ssKeysArr[idx] = sortedKeys.get(idx); + final int[] v = startAndSize.get(sortedKeys.get(idx)); + ssValuesArr[idx * 2] = v[0]; + ssValuesArr[idx * 2 + 1] = v[1]; } - jcb.println(" }"); + JavaArrayHelper.emitIntArray(jcb, " ", "private", "ssKeys", ssKeysArr); + JavaArrayHelper.emitIntArray(jcb, " ", "private", "ssValues", ssValuesArr); jcb.println(); } @@ -279,8 +286,8 @@ private static void dumpNfaTables(final JavaCodeBuilder jcb, final TokenizerData /* jjCharData into a buffer. */ final Map nfa = tokenizerData.nfa; - final Map charDataVars = new HashMap(); - final Map charDataCdbs = new HashMap(); + final Map charDataVars = new HashMap<>(); + final Map charDataCdbs = new HashMap<>(); final StringBuilder sb = new StringBuilder(64 + 18 * nfa.size()); sb.append(" private static final long[][] jjCharData = {"); @@ -413,6 +420,7 @@ private static void dumpMatchInfo(final JavaCodeBuilder jcb, final TokenizerData /* jjstrLiteralImages — collect into String[], emit via init method. */ final String[] literalImages = new String[allMatches.size()]; + final StringBuilder imgBuilder = new StringBuilder(32); for (int i = 0; i < allMatches.size(); i++) { final TokenizerData.MatchInfo matchInfo = allMatches.get(i); switch (matchInfo.matchType) { @@ -432,7 +440,8 @@ private static void dumpMatchInfo(final JavaCodeBuilder jcb, final TokenizerData newStates[i] = matchInfo.newLexState; final String image = matchInfo.image; if (image != null) { - final StringBuilder imgBuilder = new StringBuilder("\""); + imgBuilder.setLength(0); + imgBuilder.append('"'); for (int j = 0; j < image.length(); j++) { final int cj = image.charAt(j); switch (cj) { diff --git a/src/main/resources/templates/java/TokenManagerDriver.template b/src/main/resources/templates/java/TokenManagerDriver.template index 139bc21..98f393d 100644 --- a/src/main/resources/templates/java/TokenManagerDriver.template +++ b/src/main/resources/templates/java/TokenManagerDriver.template @@ -367,10 +367,10 @@ ${decls} int curPos = 0; int key = (int) curLexState << 16 | curChar; int startState = jjInitStates[curLexState]; - if (startAndSize.containsKey(key)) { - int[] arr = startAndSize.get(key); - int index = arr[0]; - for (int i = 0; i < arr[1]; i++) { + int _ssPos = java.util.Arrays.binarySearch(ssKeys, key); + if (_ssPos >= 0) { + int index = ssValues[_ssPos * 2]; + for (int i = 0; i < ssValues[_ssPos * 2 + 1]; i++) { int len = stringLiterals[index++]; int ignoreCase = stringLiterals[index++]; #if DEBUG_TOKEN_MANAGER From 7fe802152c11e82d7ca8107b522a8b70dedc7a7d Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Fri, 10 Apr 2026 23:45:39 +0700 Subject: [PATCH 06/12] Skip jj_save on successful lookaheads in jj_2 methods The jj_save() call in each jj_2_N method was in a finally block, executing on every lookahead regardless of outcome. jj_save feeds jj_rescan_token which only runs during error reporting (generateParseException). Move jj_save inside the try block, conditional on lookahead failure. Successful lookaheads and LookaheadSuccess catches skip jj_save entirely. This eliminates the finally block from all 675 jj_2 methods, giving the JIT simpler control flow. Trade-off: on parse errors, only failed lookaheads contribute to the error token set. The most relevant lookahead (the failing one) is still captured. --- .../org/javacc/java/ParserCodeGenerator.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/javacc/java/ParserCodeGenerator.java b/src/main/java/org/javacc/java/ParserCodeGenerator.java index 8a8c0b1..c39ffcc 100644 --- a/src/main/java/org/javacc/java/ParserCodeGenerator.java +++ b/src/main/java/org/javacc/java/ParserCodeGenerator.java @@ -2377,6 +2377,10 @@ private void buildPhase2Routine(final Lookahead la) { cb.println(" try {"); NormalProduction prod = null; + final String saveCall = Options.getErrorReporting() + ? " jj_save(" + (Integer.parseInt(internalNames.get(e).substring(1)) - 1) + ", xla);" + : null; + if (Options.getDebugLookahead()) { // parent null for a top level lookahead expansion, // need to go through the lookahead itself (with mod in grammar) @@ -2393,11 +2397,24 @@ private void buildPhase2Routine(final Lookahead la) { + " LOOKAHEAD (\" + xla + \"/\" + jj_la + \") " + fmtAt(e, prod) + "\");"); + if (saveCall != null) { + cb.println(" if (rc) {"); + cb.println(saveCall); + cb.println(" }"); + } cb.println(" return (!rc);"); } else { // no DebugLookahead - cb.println(" return (!jj_3" + internalNames.get(e) + "()" + ret_suffix + ");"); + if (saveCall != null) { + cb.println(" final boolean _la_failed = jj_3" + internalNames.get(e) + "()" + ret_suffix + ";"); + cb.println(" if (_la_failed) {"); + cb.println(saveCall); + cb.println(" }"); + cb.println(" return !_la_failed;"); + } else { + cb.println(" return (!jj_3" + internalNames.get(e) + "()" + ret_suffix + ");"); + } } cb.println(" } catch (LookaheadSuccess ls) {"); @@ -2408,11 +2425,6 @@ private void buildPhase2Routine(final Lookahead la) { + "\");"); } cb.println(" return LA_Phase2_Success;"); - if (Options.getErrorReporting()) { - cb.println(" } finally {"); - cb.println( - " jj_save(" + (Integer.parseInt(internalNames.get(e).substring(1)) - 1) + ", xla);"); - } cb.println(" }"); cb.println(" }"); cb.println(); From 028e00aa4038ba14bc6a67631a953f4e1da292ba Mon Sep 17 00:00:00 2001 From: manticore-projects Date: Sat, 11 Apr 2026 21:58:40 +0700 Subject: [PATCH 07/12] fix: Prevent generated code from exceeding JVM 64KB method bytecode limit Split large generated methods into sub-methods when safety thresholds are exceeded, preventing MethodTooLargeException from javac or from ASM-based instrumentation tools (JaCoCo, ByteBuddy). ParserCodeGenerator: - Split jj_rescan_token switch into chunk sub-methods (threshold: 500) - Split jj_la1_init_* array init into chunk sub-methods (threshold: 4000) - Split phase3 Choice chains into continuation sub-methods (threshold: 1000) TokenManagerCodeGenerator: - Route canMatchAnyChar, jjInitStates, jjInitialMatchForLexState through JavaArrayHelper.emitIntArray() instead of inline static arrays - Route jjtoToken/Skip/Special/More through JavaArrayHelper.emitLongArray() - Wrap large CharDataConsts CHAR_DATA arrays and jjCharData in _init() methods JavaArrayHelper: - Add emitLongArray() with chunk splitting (2000 elements per chunk) All changes are backwards-compatible: splitting only activates when thresholds are exceeded. Existing grammars produce identical output. Fixes: org.objectweb.asm.MethodTooLargeException: Method too large: net/sf/jsqlparser/parser/CCJSqlParserTokenManager. ()V --- .../java/org/javacc/java/JavaArrayHelper.java | 79 ++++ .../org/javacc/java/ParserCodeGenerator.java | 385 +++++++++++++++--- .../java/TokenManagerCodeGenerator.java | 121 +++--- 3 files changed, 457 insertions(+), 128 deletions(-) diff --git a/src/main/java/org/javacc/java/JavaArrayHelper.java b/src/main/java/org/javacc/java/JavaArrayHelper.java index ff93a8e..61a6aa5 100644 --- a/src/main/java/org/javacc/java/JavaArrayHelper.java +++ b/src/main/java/org/javacc/java/JavaArrayHelper.java @@ -116,6 +116,85 @@ static void emitIntArray( jcb.println(); } + // ---------------------------------------------------------------- + // long[] + // ---------------------------------------------------------------- + + /** + * Emits a {@code static final long[]} field backed by init method(s). + * + *

Each {@code long} literal compiles to ~12 bytes of bytecode + * ({@code ldc2_w} + {@code lastore}), so the chunk size is halved + * compared to {@code int[]} to stay within the 64 KB limit.

+ * + * @param jcb the code builder + * @param indent leading whitespace + * @param vis visibility keyword + * @param name field name + * @param data the array data + */ + static void emitLongArray( + final JavaCodeBuilder jcb, final String indent, + final String vis, final String name, final long[] data) { + + // long literals are larger in bytecode, so use a smaller chunk + final int longChunkSize = CHUNK_SIZE / 2; + + jcb.println(indent + vis + " static final long[] " + name + " = " + name + "_init();"); + jcb.println(); + + if (data.length <= longChunkSize) { + jcb.println(indent + "private static long[] " + name + "_init() {"); + jcb.print(indent + " return new long[] {"); + jcb.println(); + for (int i = 0; i < data.length; i++) { + if (i % 8 == 0) { + if (i > 0) { + jcb.println(); + } + jcb.print(indent + " "); + } + jcb.print(data[i] + "L"); + if (i < data.length - 1) { + jcb.print(", "); + } + } + jcb.println(); + jcb.println(indent + " };"); + jcb.println(indent + "}"); + } else { + final int chunks = (data.length + longChunkSize - 1) / longChunkSize; + jcb.println(indent + "private static long[] " + name + "_init() {"); + jcb.println(indent + " final long[] r = new long[" + data.length + "];"); + for (int c = 0; c < chunks; c++) { + jcb.println(indent + " " + name + "_init_" + c + "(r);"); + } + jcb.println(indent + " return r;"); + jcb.println(indent + "}"); + jcb.println(); + for (int c = 0; c < chunks; c++) { + final int start = c * longChunkSize; + final int end = Math.min(start + longChunkSize, data.length); + jcb.println(indent + "private static void " + name + "_init_" + c + "(final long[] r) {"); + for (int i = start; i < end; i++) { + if ((i - start) % 8 == 0) { + if (i > start) { + jcb.println(); + } + jcb.print(indent + " "); + } + jcb.print("r[" + i + "]=" + data[i] + "L; "); + } + jcb.println(); + jcb.println(indent + "}"); + if (c < chunks - 1) { + jcb.println(); + } + } + } + jcb.println(); + } + // ---------------------------------------------------------------- // String[] // ---------------------------------------------------------------- diff --git a/src/main/java/org/javacc/java/ParserCodeGenerator.java b/src/main/java/org/javacc/java/ParserCodeGenerator.java index c39ffcc..3372b7f 100644 --- a/src/main/java/org/javacc/java/ParserCodeGenerator.java +++ b/src/main/java/org/javacc/java/ParserCodeGenerator.java @@ -97,6 +97,26 @@ class ParserCodeGenerator implements org.javacc.parser.ParserCodeGenerator { private GenericCodeBuilder cb; + /* + * Safety thresholds to prevent generated methods from exceeding + * the JVM's 64KB bytecode limit per method. + * + * Each int literal in an array init compiles to ~7 bytes of bytecode. + * Each switch case compiles to ~25 bytes. + * Each nested if-else in a Choice chain compiles to ~30 bytes. + * + * With a 64KB (65535 byte) limit, these thresholds provide ~2x safety margin. + */ + + /** Max switch cases in jj_rescan_token before splitting into sub-methods. */ + private static final int RESCAN_CHUNK_SIZE = 500; + + /** Max array elements per jj_la1_init method before splitting into sub-methods. */ + private static final int LA1_INIT_CHUNK_SIZE = 4000; + + /** Max Choice alternatives in a jj_3R method before splitting into sub-methods. */ + private static final int CHOICE_CHAIN_THRESHOLD = 1000; + /** * To be set to true to add debug comment tags in the generated code (to ease linking it with this * generator), false otherwise (which should be the normal case). @@ -265,6 +285,7 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData + context.globals().maskindex + "];"); final int tokenMaskSize = ((context.globals().tokenCount - 1) / 32) + 1; + final int maskCount = context.globals().maskVals.size(); for (int i = 0; i < tokenMaskSize; i++) { cb.println(" private static int[] jj_la1_" + i + ";"); } @@ -275,15 +296,43 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" jj_la1_init_" + i + "();"); } cb.println(" }"); + for (int i = 0; i < tokenMaskSize; i++) { cb.println(); - cb.println(" private static void jj_la1_init_" + i + "() {"); - cb.print(" jj_la1_" + i + " = new int[] {"); - for (final int[] tokenMask : context.globals().maskVals) { - cb.print("0x" + Integer.toHexString(tokenMask[i]) + ", "); + if (maskCount <= LA1_INIT_CHUNK_SIZE) { + // Small enough — original single-method behavior + cb.println(" private static void jj_la1_init_" + i + "() {"); + cb.print(" jj_la1_" + i + " = new int[] {"); + for (final int[] tokenMask : context.globals().maskVals) { + cb.print("0x" + Integer.toHexString(tokenMask[i]) + ", "); + } + cb.println("};"); + cb.println(" }"); + } else { + // Split: allocate array in main method, fill in chunk sub-methods + final int numChunks = (maskCount + LA1_INIT_CHUNK_SIZE - 1) / LA1_INIT_CHUNK_SIZE; + cb.println(" private static void jj_la1_init_" + i + "() {"); + cb.println(" jj_la1_" + i + " = new int[" + maskCount + "];"); + for (int chunk = 0; chunk < numChunks; chunk++) { + cb.println(" jj_la1_init_" + i + "_chunk_" + chunk + "(jj_la1_" + i + ");"); + } + cb.println(" }"); + + // Generate chunk sub-methods + final List maskVals = context.globals().maskVals; + for (int chunk = 0; chunk < numChunks; chunk++) { + final int lo = chunk * LA1_INIT_CHUNK_SIZE; + final int hi = Math.min(lo + LA1_INIT_CHUNK_SIZE, maskCount); + cb.println(); + cb.println(" private static void jj_la1_init_" + i + "_chunk_" + chunk + + "(final int[] a) {"); + for (int j = lo; j < hi; j++) { + cb.println(" a[" + j + "] = 0x" + + Integer.toHexString(maskVals.get(j)[i]) + ";"); + } + cb.println(" }"); + } } - cb.println("};"); - cb.println(" }"); } } if ((context.globals().jj2index != 0) && Options.getErrorReporting()) { @@ -1362,26 +1411,47 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData } // end else if (Options.getDebugLookahead()) if ((context.globals().jj2index != 0) && Options.getErrorReporting()) { + final int jj2cnt = context.globals().jj2index; cb.println( " /** When and for reporting error, rescans tokens (rerun phase 3 routines), to build ad-hoc info. */"); cb.println(" private " + pStatic + "void jj_rescan_token() {"); cb.println(" jj_rescan = true;"); - cb.println(" for (int i = 0; i < " + context.globals().jj2index + "; i++) {"); + cb.println(" for (int i = 0; i < " + jj2cnt + "; i++) {"); cb.println(" try {"); cb.println(" JJCalls p = jj_2_rtns[i];"); cb.println(" do {"); cb.println(" if (p.gen > jj_gen) {"); cb.println(" jj_la = p.arg;"); cb.println(" jj_lastpos = jj_scanpos = p.first;"); - cb.println(" switch (i) {"); - for (int i = 0; i < context.globals().jj2index; i++) { - cb.println(" case " + i + ":"); - cb.println(" jj_3_" + (i + 1) + "();"); + + if (jj2cnt <= RESCAN_CHUNK_SIZE) { + // Small enough for a single switch — original behavior + cb.println(" switch (i) {"); + for (int i = 0; i < jj2cnt; i++) { + cb.println(" case " + i + ":"); + cb.println(" jj_3_" + (i + 1) + "();"); + cb.println(" break;"); + } + cb.println(" default:"); cb.println(" break;"); + cb.println(" }"); + } else { + // Split into chunk sub-methods to stay under 64KB bytecode per method + final int numChunks = (jj2cnt + RESCAN_CHUNK_SIZE - 1) / RESCAN_CHUNK_SIZE; + for (int chunk = 0; chunk < numChunks; chunk++) { + final int lo = chunk * RESCAN_CHUNK_SIZE; + if (chunk == 0) { + cb.println(" if (i < " + (lo + RESCAN_CHUNK_SIZE) + ") {"); + } else if (chunk == numChunks - 1) { + cb.println(" } else {"); + } else { + cb.println(" } else if (i < " + (lo + RESCAN_CHUNK_SIZE) + ") {"); + } + cb.println(" jj_rescan_token_chunk_" + chunk + "(i);"); + } + cb.println(" }"); } - cb.println(" default:"); - cb.println(" break;"); - cb.println(" }"); + cb.println(" }"); cb.println(" p = p.next;"); cb.println(" } while (p != null);"); @@ -1393,6 +1463,27 @@ public void generateCode(final CodeGeneratorSettings settings, final ParserData cb.println(" }"); cb.println(); + // Generate chunk sub-methods if splitting was needed + if (jj2cnt > RESCAN_CHUNK_SIZE) { + final int numChunks = (jj2cnt + RESCAN_CHUNK_SIZE - 1) / RESCAN_CHUNK_SIZE; + for (int chunk = 0; chunk < numChunks; chunk++) { + final int lo = chunk * RESCAN_CHUNK_SIZE; + final int hi = Math.min(lo + RESCAN_CHUNK_SIZE, jj2cnt); + cb.println(" private " + pStatic + "void jj_rescan_token_chunk_" + chunk + "(final int i) {"); + cb.println(" switch (i) {"); + for (int i = lo; i < hi; i++) { + cb.println(" case " + i + ":"); + cb.println(" jj_3_" + (i + 1) + "();"); + cb.println(" break;"); + } + cb.println(" default:"); + cb.println(" break;"); + cb.println(" }"); + cb.println(" }"); + cb.println(); + } + } + cb.println(" private " + pStatic + "void jj_save(final int index, final int xla) {"); cb.println(" JJCalls p = jj_2_rtns[index];"); cb.println(" while (p.gen > jj_gen) {"); @@ -1523,6 +1614,18 @@ private void build() { enumeration.hasMoreElements(); ) { buildPhase3Routine(enumeration.nextElement(), false, ""); } + + // Emit deferred continuation methods for split Choice chains (Fix 3: code-too-large prevention) + for (final DeferredChoiceChunk chunk : deferredChoiceChunks) { + cb.println(" private " + JavaUtil.getStatic() + "boolean jj_3" + chunk.methodName + "() {"); + cb.println(" " + getTypeForToken() + " xsp;"); + emitChoiceChunkFlat(chunk.choice, chunk.lo, chunk.hi, + chunk.totalChoices, "", chunk.nextPartName); + cb.println(" return LA_Phase3_Success;"); + cb.println(" }"); + cb.println(); + } + deferredChoiceChunks.clear(); } /* @@ -2648,64 +2751,74 @@ private void buildPhase3Routine( } else if (e instanceof Choice) { final Choice e_nrw = (Choice) e; final int nbChoices = e_nrw.getChoices().size(); - if (nbChoices != 1) { - if (!xsp_declared) { - xsp_declared = true; - cb.println(ind + " " + getTypeForToken() + " xsp;"); - } - cb.println(ind + " xsp = jj_scanpos;"); - } - for (int i = 0; i < nbChoices; i++) { - String dec = ""; - for (int k = 0; k < i; k++) { - dec += " "; - } - final Sequence nested_seq = (Sequence) e_nrw.getChoices().get(i); - final Lookahead la = (Lookahead) nested_seq.units.get(0); - if (la.getActionTokens().size() != 0) { - // We have semantic lookahead that must be evaluated. - context.globals().lookaheadNeeded = true; - cb.println(dec + ind + " jj_lookingAhead = true;"); - cb.print(dec + ind + " jj_semLA = "); - cb.printTokenSetup(la.getActionTokens().get(0)); - for (final Iterator it = la.getActionTokens().iterator(); it.hasNext(); ) { - t = it.next(); - cb.printToken(t); + + if (nbChoices > CHOICE_CHAIN_THRESHOLD && !recursive_call) { + // Large Choice: split into continuation sub-methods to avoid 64KB bytecode limit. + // Each chunk handles up to CHOICE_CHAIN_THRESHOLD alternatives. + // The last alternative in each chunk (except the final chunk) delegates + // to the next continuation method instead of returning failure. + buildPhase3ChoiceSplit(e, e_nrw, nbChoices, inf, ind); + } else { + // Original behavior for small-to-medium choices + if (nbChoices != 1) { + if (!xsp_declared) { + xsp_declared = true; + cb.println(ind + " " + getTypeForToken() + " xsp;"); } - // gcb.printTrailingComments(t); - cb.println(";"); - cb.println(dec + ind + " jj_lookingAhead = false;"); - } - cb.print(dec + ind + " if ("); - if (DCT) { - cb.print("/*bp3r-ch1*/ "); + cb.println(ind + " xsp = jj_scanpos;"); } - if (la.getActionTokens().size() != 0) { - cb.print("!jj_semLA || "); + for (int i = 0; i < nbChoices; i++) { + String dec = ""; + for (int k = 0; k < i; k++) { + dec += " "; + } + final Sequence nested_seq = (Sequence) e_nrw.getChoices().get(i); + final Lookahead la = (Lookahead) nested_seq.units.get(0); + if (la.getActionTokens().size() != 0) { + // We have semantic lookahead that must be evaluated. + context.globals().lookaheadNeeded = true; + cb.println(dec + ind + " jj_lookingAhead = true;"); + cb.print(dec + ind + " jj_semLA = "); + cb.printTokenSetup(la.getActionTokens().get(0)); + for (final Iterator it = la.getActionTokens().iterator(); it.hasNext(); ) { + t = it.next(); + cb.printToken(t); + } + // gcb.printTrailingComments(t); + cb.println(";"); + cb.println(dec + ind + " jj_lookingAhead = false;"); + } + cb.print(dec + ind + " if ("); + if (DCT) { + cb.print("/*bp3r-ch1*/ "); + } + if (la.getActionTokens().size() != 0) { + cb.print("!jj_semLA || "); + } + cb.print(genjj_3Call(nested_seq)); + cb.println(") {"); + if (i != (nbChoices - 1)) { + cb.println(dec + ind + " jj_scanpos = xsp;"); + } else { + cb.println(dec + ind + " " + genReturn(true, i, ind)); + cb.print(dec + ind + " }"); + if (DCT) { + cb.print(" /*bp3r-ch2*/"); + } + cb.println(); + } } - cb.print(genjj_3Call(nested_seq)); - cb.println(") {"); - if (i != (nbChoices - 1)) { - cb.println(dec + ind + " jj_scanpos = xsp;"); - } else { - cb.println(dec + ind + " " + genReturn(true, i, ind)); - cb.print(dec + ind + " }"); + for (int i = nbChoices; i > 1; i--) { + for (int k = i - 1; k > 1; k--) { + cb.print(" "); + } + cb.print(ind + " }"); if (DCT) { - cb.print(" /*bp3r-ch2*/"); + cb.print(" /*bp3r-ch3*/"); } cb.println(); } } - for (int i = nbChoices; i > 1; i--) { - for (int k = i - 1; k > 1; k--) { - cb.print(" "); - } - cb.print(ind + " }"); - if (DCT) { - cb.print(" /*bp3r-ch3*/"); - } - cb.println(); - } } else if (e instanceof Sequence) { final Sequence e_nrw = (Sequence) e; @@ -2822,6 +2935,150 @@ private void buildPhase3Routine( } } + /** + * Generates a split Choice chain for phase 3 scanning when the number of alternatives + * exceeds {@link #CHOICE_CHAIN_THRESHOLD}. + * + *

Instead of one deeply-nested if-else chain that may exceed 64KB of bytecode, + * this generates a flat try-each-and-return pattern split across continuation + * sub-methods:

+ *
+   *   // Main method: tries alternatives 0..999
+   *   Token xsp;
+   *   xsp = jj_scanpos;
+   *   if (!(call(alt0))) return false;  // success
+   *   jj_scanpos = xsp;
+   *   if (!(call(alt1))) return false;
+   *   ...
+   *   jj_scanpos = xsp;
+   *   return jj_3R_Foo_part1();  // delegate to continuation
+   *
+   *   // Continuation method: tries alternatives 1000..1999
+   *   private boolean jj_3R_Foo_part1() { ... }
+   * 
+ */ + private void buildPhase3ChoiceSplit(final Expansion e, final Choice choice, + final int nbChoices, final Phase3Data inf, final String ind) { + // Compute the method name base from the expansion's internal name + final String baseName = internalNames.get(e); + final int numChunks = (nbChoices + CHOICE_CHAIN_THRESHOLD - 1) / CHOICE_CHAIN_THRESHOLD; + + if (!xsp_declared) { + xsp_declared = true; + cb.println(ind + " " + getTypeForToken() + " xsp;"); + } + + // Generate flat alternatives for the first chunk (inside the current method body) + emitChoiceChunkFlat(choice, 0, Math.min(CHOICE_CHAIN_THRESHOLD, nbChoices), nbChoices, ind, + numChunks > 1 ? baseName + "_part1" : null); + + // Generate continuation sub-methods for remaining chunks + for (int chunk = 1; chunk < numChunks; chunk++) { + final int lo = chunk * CHOICE_CHAIN_THRESHOLD; + final int hi = Math.min(lo + CHOICE_CHAIN_THRESHOLD, nbChoices); + final String nextPart = (chunk < numChunks - 1) + ? baseName + "_part" + (chunk + 1) + : null; + + // These continuation methods are emitted AFTER the enclosing method finishes, + // so we buffer them and emit after buildPhase3Routine completes. + // We use a simpler approach: emit them as deferred code via the cb directly, + // since buildPhase3Routine for non-recursive calls will close the method afterward. + deferredChoiceChunks.add(new DeferredChoiceChunk( + baseName + "_part" + chunk, choice, lo, hi, nbChoices, nextPart)); + } + } + + /** Buffer for deferred continuation methods generated by choice splitting. */ + private final List deferredChoiceChunks = new ArrayList<>(); + + /** Data for a deferred continuation method. */ + private static class DeferredChoiceChunk { + final String methodName; + final Choice choice; + final int lo, hi, totalChoices; + final String nextPartName; // null if this is the last chunk + + DeferredChoiceChunk(String methodName, Choice choice, + int lo, int hi, int totalChoices, String nextPartName) { + this.methodName = methodName; + this.choice = choice; + this.lo = lo; + this.hi = hi; + this.totalChoices = totalChoices; + this.nextPartName = nextPartName; + } + } + + /** + * Emits a flat sequence of alternatives (no deep nesting) for a Choice chunk. + * Each alternative is: if (!(call(alt_i))) return false; jj_scanpos = xsp; + * The last alternative either returns failure or delegates to a continuation method. + * + * @param choice the Choice expansion + * @param lo first alternative index (inclusive) + * @param hi last alternative index (exclusive) + * @param total total number of alternatives in the full Choice + * @param ind indentation + * @param nextMethod name of continuation method, or null for the last chunk + */ + private void emitChoiceChunkFlat(final Choice choice, final int lo, final int hi, + final int total, final String ind, final String nextMethod) { + Token t = null; + cb.println(ind + " xsp = jj_scanpos;"); + for (int i = lo; i < hi; i++) { + final Sequence nested_seq = (Sequence) choice.getChoices().get(i); + final Lookahead la = (Lookahead) nested_seq.units.get(0); + + if (la.getActionTokens().size() != 0) { + context.globals().lookaheadNeeded = true; + cb.println(ind + " jj_lookingAhead = true;"); + cb.print(ind + " jj_semLA = "); + cb.printTokenSetup(la.getActionTokens().get(0)); + for (final Iterator it = la.getActionTokens().iterator(); it.hasNext(); ) { + t = it.next(); + cb.printToken(t); + } + cb.println(";"); + cb.println(ind + " jj_lookingAhead = false;"); + } + + if (i == hi - 1 && nextMethod == null) { + // Last alternative of the last chunk: return failure if it fails + cb.print(ind + " if ("); + if (la.getActionTokens().size() != 0) { + cb.print("!jj_semLA || "); + } + cb.print(genjj_3Call(nested_seq)); + cb.println(") {"); + cb.println(ind + " return LA_Phase3_Failure;"); + cb.println(ind + " }"); + } else if (i == hi - 1 && nextMethod != null) { + // Last alternative of a non-final chunk: delegate to continuation + cb.print(ind + " if ("); + if (la.getActionTokens().size() != 0) { + cb.print("!jj_semLA || "); + } + cb.print(genjj_3Call(nested_seq)); + cb.println(") {"); + cb.println(ind + " jj_scanpos = xsp;"); + cb.println(ind + " return jj_3" + nextMethod + "();"); + cb.println(ind + " }"); + } else { + // Normal alternative: try it, reset on failure, continue + cb.print(ind + " if (!("); + if (la.getActionTokens().size() != 0) { + cb.print("!jj_semLA || "); + } + cb.print(genjj_3Call(nested_seq)); + cb.println(")) {"); + cb.println(ind + " return LA_Phase3_Success;"); + cb.println(ind + " }"); + cb.println(ind + " jj_scanpos = xsp;"); + } + } + } + private String genjj_3Call(final Expansion e) { if (internalNames.containsKey(e) && internalNames.get(e).startsWith("jj_scan_token")) { return "LA_Scan_Token_Failure == " + internalNames.get(e) + (DCT ? " /*g3c-s*/" : ""); diff --git a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java index 6bf58c1..50f4fec 100644 --- a/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java +++ b/src/main/java/org/javacc/java/TokenManagerCodeGenerator.java @@ -218,60 +218,29 @@ private static void dumpDfaTables(final JavaCodeBuilder jcb, final TokenizerData } private static void dumpNfaTables(final JavaCodeBuilder jcb, final TokenizerData tokenizerData) { - /* canMatchAnyChar. */ - jcb.print(" private static final int[] canMatchAnyChar = {"); - int v = 0; - for (int i = 0; i < tokenizerData.wildcardKind.size(); i++) { - if (v++ > 0) { - jcb.print(", "); - } else { - jcb.println(); - jcb.print(" "); + /* canMatchAnyChar — emit via init method for clinit safety. */ + { + final int[] arr = new int[tokenizerData.wildcardKind.size()]; + for (int i = 0; i < arr.length; i++) { + arr[i] = tokenizerData.wildcardKind.get(i); } - jcb.print(tokenizerData.wildcardKind.get(i)); + JavaArrayHelper.emitIntArray(jcb, " ", "private", "canMatchAnyChar", arr); } - if (!tokenizerData.wildcardKind.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); - } - jcb.println(); - /* jjInitStates. */ - jcb.print(" private static final int[] jjInitStates = {"); - v = 0; - for (final int i : tokenizerData.initialStates.keySet()) { - if (v++ > 0) { - jcb.print(", "); - } else { - jcb.println(); - jcb.print(" "); + /* jjInitStates — emit via init method. */ + { + final int[] keys = tokenizerData.initialStates.keySet().stream() + .mapToInt(Integer::intValue).toArray(); + final int[] arr = new int[keys.length]; + for (int i = 0; i < keys.length; i++) { + arr[i] = tokenizerData.initialStates.get(keys[i]); } - jcb.print(tokenizerData.initialStates.get(i)); - } - if (!tokenizerData.initialStates.isEmpty()) { - jcb.println(); - jcb.println(" };"); - } else { - jcb.println("};"); + JavaArrayHelper.emitIntArray(jcb, " ", "private", "jjInitStates", arr); } - jcb.println(); - /* jjInitialMatchForLexState. */ - jcb.print(" private static final int[] jjInitialMatchForLexState = {"); - v = 0; - for (int i = 0; i < tokenizerData.lexStateNames.length; i++) { - if (v++ > 0) { - jcb.print(", "); - } else { - jcb.println(); - jcb.print(" "); - } - jcb.print(tokenizerData.initialMatchForLexState[i]); - } - jcb.println("};"); - jcb.println(); + /* jjInitialMatchForLexState — emit via init method. */ + JavaArrayHelper.emitIntArray(jcb, " ", "private", "jjInitialMatchForLexState", + tokenizerData.initialMatchForLexState); // We do the following for Java so that the generated code is reasonable // size and can be compiled. May not be needed for other languages. @@ -342,15 +311,50 @@ private static void dumpNfaTables(final JavaCodeBuilder jcb, final TokenizerData sb.append(" };").append(EOL); } - // in order, for easier comparison with C# & C++ + // Emit CHAR_DATA_N arrays via init methods to prevent CharDataConsts. overflow. + // Each long literal compiles to ~12 bytes of bytecode; large Unicode character classes + // (like CHAR_DATA27/28/31 in full-Unicode grammars) can have 500+ RLE pairs, and with + // 70+ unique arrays the combined clinit easily exceeds 64KB. + final int CHAR_DATA_INLINE_LIMIT = 100; // elements; above this → init method for (int k = 1; k <= charDataCdbs.size(); k++) { final String key = charDataVarPrefix + Integer.toString(k); - jcb.println(" private static final long[] " + key + " = " + charDataCdbs.get(key) + ";"); + final String initExpr = charDataCdbs.get(key); // e.g. "new long[] {1, 4294977024L}" + // Count elements to decide inline vs init method + final int commaCount = initExpr.length() - initExpr.replace(",", "").length(); + final int elemCount = commaCount + 1; // rough count of array elements + if (elemCount <= CHAR_DATA_INLINE_LIMIT) { + // Small array — keep inline (original behavior) + jcb.println(" private static final long[] " + key + " = " + initExpr + ";"); + } else { + // Large array — wrap in init method to keep out of + jcb.println(" private static final long[] " + key + " = " + key + "_init();"); + jcb.println(" private static long[] " + key + "_init() {"); + jcb.println(" return " + initExpr + ";"); + jcb.println(" }"); + } } jcb.println(); - // now print jjCharData buffer - jcb.println(sb); + // Emit jjCharData reference array via init method when large. + // The StringBuilder 'sb' contains the full "private static final long[][] jjCharData = { ... };" + // declaration. For large NFA state counts (641+ states), this reference array alone + // contributes ~5KB+ to . Wrap in init method for safety. + if (nfa.size() > 500) { + // Replace inline declaration with init method + String jjCharDataDecl = sb.toString(); + // Change "private static final long[][] jjCharData = {" to return statement + jjCharDataDecl = jjCharDataDecl.replace( + "private static final long[][] jjCharData = {", + "private static final long[][] jjCharData = jjCharData_init();" + + EOL + " private static long[][] jjCharData_init() {" + + EOL + " return new long[][] {"); + // Close the init method after the array + jjCharDataDecl = jjCharDataDecl.replace("};", "};" + EOL + " }"); + jcb.println(jjCharDataDecl); + } else { + // Small enough — original inline behavior + jcb.println(sb); + } /* end class CharDataConsts. */ jcb.println(" }"); @@ -570,17 +574,6 @@ private static void dumpLexicalActions( } private static void generateBitVector(final JavaCodeBuilder jcb, final String name, final BitSet bits) { - jcb.println(); - jcb.println(" private static final long[] " + name + " = {"); - final long[] longs = bits.toLongArray(); - for (int i = 0; i < longs.length; i++) { - if (i > 0) { - jcb.print(","); - } - // codeGenerator.genCode("0x" + Long.toHexString(longs[i]) + "L"); - jcb.print(" " + Long.toString(longs[i]) + "L"); - } - jcb.println(); - jcb.println(" };"); + JavaArrayHelper.emitLongArray(jcb, " ", "private", name, bits.toLongArray()); } } From 0333bc15702c086c4ee1bdbf3fc05a98b29524db Mon Sep 17 00:00:00 2001 From: Andreas Reichel Date: Fri, 28 Aug 2026 17:02:31 +0700 Subject: [PATCH 08/12] chore: delete obsolete files --- examples/CORBA-IDL/README.md | 11 - examples/CORBA-IDL/files/Hello.exp_out | 2 - examples/CORBA-IDL/files/Hello.idl | 7 - examples/CORBA-IDL/pom.xml | 131 - examples/CORBA-IDL/src/main/javacc/IDL.jj | 865 -- examples/CustomTemplate/pom.xml | 147 - .../templates/java/ParseException.template | 258 - .../CustomTemplate/src/main/javacc/Simple1.jj | 110 - examples/CustomTemplate/verify-files.bsh | 26 - examples/GUIParsing/ParserVersion/README.md | 28 - examples/GUIParsing/ParserVersion/pom.xml | 50 - examples/GUIParsing/ParserVersion/run.cmd | 3 - .../ParserVersion/src/main/java/CalcGUI.java | 244 - .../java/CalcInputParserTreeConstants.java | 4 - .../ParserVersion/src/main/java/Main.java | 44 - .../src/main/java/ProducerConsumer.java | 60 - .../src/main/java/TokenCollector.java | 35 - .../src/main/javacc/CalcInput.jj | 140 - examples/GUIParsing/README.md | 12 - examples/GUIParsing/TokenMgrVersion/README.md | 38 - examples/GUIParsing/TokenMgrVersion/pom.xml | 50 - examples/GUIParsing/TokenMgrVersion/run.cmd | 3 - .../src/main/java/CalcGUI.java | 231 - .../src/main/java/CharCollector.java | 210 - .../TokenMgrVersion/src/main/java/Main.java | 42 - .../src/main/java/MyLexer.java | 49 - .../src/main/javacc/CalcInput.jj | 220 - examples/GUIParsing/pom.xml | 53 - examples/Gwt/README | 29 - examples/Gwt/checkstyle-suppress.xml | 42 - examples/Gwt/pom.xml | 193 - examples/Gwt/simple/err | 0 examples/Gwt/simple/out | 1 - examples/Gwt/simple/ref | 1 - .../Gwt/src/main/javacc/GwtSimpleParser.jj | 100 - .../Gwt/src/main/javacc/GwtUnicodeParser.jj | 100 - examples/Gwt/unicode/err | 0 examples/Gwt/unicode/out | 1 - examples/Gwt/unicode/ref | 1 - examples/Interpreter/README | 45 - .../Interpreter/files/fact/ast-fact.exp_err | 0 .../Interpreter/files/fact/ast-fact.exp_out | 9 - examples/Interpreter/files/fact/fact.in | 1 - examples/Interpreter/files/fact/fact.spl | 14 - .../Interpreter/files/fact/vst-fact.exp_err | 0 .../Interpreter/files/fact/vst-fact.exp_out | 9 - .../Interpreter/files/odd/ast-odd.exp_err | 0 .../Interpreter/files/odd/ast-odd.exp_out | 9 - examples/Interpreter/files/odd/odd.in | 1 - examples/Interpreter/files/odd/odd.spl | 13 - .../Interpreter/files/odd/vst-odd.exp_err | 0 .../Interpreter/files/odd/vst-odd.exp_out | 9 - .../Interpreter/files/sqrt/ast-sqrt.exp_err | 0 .../Interpreter/files/sqrt/ast-sqrt.exp_out | 9 - examples/Interpreter/files/sqrt/sqrt.in | 1 - examples/Interpreter/files/sqrt/sqrt.spl | 12 - .../Interpreter/files/sqrt/vst-sqrt.exp_err | 0 .../Interpreter/files/sqrt/vst-sqrt.exp_out | 9 - examples/Interpreter/pom.xml | 324 - .../Interpreter/src/main/java/ast/MyNode.java | 74 - .../src/main/java/ast/SPLMain.java | 109 - .../src/main/java/ast/STAddNode.java | 54 - .../src/main/java/ast/STAndNode.java | 58 - .../src/main/java/ast/STAssignment.java | 51 - .../src/main/java/ast/STBitwiseAndNode.java | 57 - .../src/main/java/ast/STBitwiseComplNode.java | 48 - .../src/main/java/ast/STBitwiseOrNode.java | 57 - .../src/main/java/ast/STBitwiseXorNode.java | 57 - .../src/main/java/ast/STBlock.java | 47 - .../src/main/java/ast/STCompilationUnit.java | 58 - .../src/main/java/ast/STDivNode.java | 52 - .../src/main/java/ast/STEQNode.java | 57 - .../src/main/java/ast/STFalseNode.java | 45 - .../src/main/java/ast/STGENode.java | 52 - .../src/main/java/ast/STGTNode.java | 52 - .../Interpreter/src/main/java/ast/STId.java | 47 - .../src/main/java/ast/STIfStatement.java | 54 - .../src/main/java/ast/STIntConstNode.java | 47 - .../src/main/java/ast/STLENode.java | 52 - .../src/main/java/ast/STLTNode.java | 52 - .../src/main/java/ast/STModNode.java | 52 - .../src/main/java/ast/STMulNode.java | 52 - .../src/main/java/ast/STNENode.java | 57 - .../src/main/java/ast/STNotNode.java | 48 - .../src/main/java/ast/STOrNode.java | 58 - .../src/main/java/ast/STReadStatement.java | 83 - .../main/java/ast/STStatementExpression.java | 48 - .../src/main/java/ast/STSubtractNode.java | 52 - .../src/main/java/ast/STTrueNode.java | 45 - .../src/main/java/ast/STVarDeclaration.java | 52 - .../src/main/java/ast/STWhileStatement.java | 55 - .../src/main/java/ast/STWriteStatement.java | 58 - .../src/main/java/vst/InterpreterVisitor.java | 467 -- .../src/main/java/vst/SPLMain.java | 110 - .../Interpreter/src/main/java/vst/ST_Id.java | 48 - .../src/main/java/vst/ST_IntConstNode.java | 48 - .../src/main/java/vst/ST_ReadStatement.java | 48 - .../src/main/java/vst/ST_VarDeclaration.java | 49 - .../src/main/java/vst/ST_WriteStatement.java | 48 - examples/Interpreter/src/main/jjtree/AST.jjt | 357 - examples/Interpreter/src/main/jjtree/VST.jjt | 366 - examples/JJTree/README | 196 - examples/JJTree/files/eg1.err | 0 examples/JJTree/files/eg1.in | 1 - examples/JJTree/files/eg1.out | 23 - examples/JJTree/files/eg1.ref | 23 - examples/JJTree/files/eg2.err | 0 examples/JJTree/files/eg2.in | 1 - examples/JJTree/files/eg2.out | 9 - examples/JJTree/files/eg2.ref | 9 - examples/JJTree/files/eg3.err | 0 examples/JJTree/files/eg3.in | 1 - examples/JJTree/files/eg3.out | 9 - examples/JJTree/files/eg3.ref | 9 - examples/JJTree/files/eg4.err | 0 examples/JJTree/files/eg4.in | 1 - examples/JJTree/files/eg4.out | 9 - examples/JJTree/files/eg4.ref | 9 - examples/JJTree/pom.xml | 218 - .../JJTree/src/main/java/eg2/ASTMyID.java | 62 - .../JJTree/src/main/java/eg3/ASTMyID.java | 65 - .../JJTree/src/main/java/eg4/ASTMyID.java | 64 - .../src/main/java/eg4/ASTMyOtherID.java | 70 - .../src/main/java/eg4/Eg4DumpVisitor.java | 111 - .../src/main/java/eg4/MyVisException.java | 35 - examples/JJTree/src/main/jjtree/eg1.jjt | 809 -- examples/JJTree/src/main/jjtree/eg2.jjt | 174 - examples/JJTree/src/main/jjtree/eg3.jjt | 173 - examples/JJTree/src/main/jjtree/eg4.jjt | 177 - examples/JavaCC/Java1.5.jj | 2113 ----- examples/JavaCC/checkstyle-suppress.xml | 42 - examples/JavaCC/pom.xml | 97 - examples/JavaCC/src/main/javacc/JavaCC.jj | 1517 ---- examples/Lookahead/README | 823 -- examples/Lookahead/pom.xml | 72 - .../Lookahead/src/main/javacc/Example1.jj | 66 - .../Lookahead/src/main/javacc/Example10.jj | 74 - .../Lookahead/src/main/javacc/Example2.jj | 71 - .../Lookahead/src/main/javacc/Example3.jj | 74 - .../Lookahead/src/main/javacc/Example4.jj | 61 - .../Lookahead/src/main/javacc/Example5.jj | 73 - .../Lookahead/src/main/javacc/Example6.jj | 71 - .../Lookahead/src/main/javacc/Example7.jj | 63 - .../Lookahead/src/main/javacc/Example8.jj | 74 - .../Lookahead/src/main/javacc/Example9.jj | 69 - .../NestedLookaheadGrammar_Example11.jj | 220 - .../NonChoiceLookaheadGrammar_Example12.jj | 1419 ---- .../ReadingLookahedDebugTrace_Example8.jj | 103 - .../main/javacc/RewrittenGrammar_Example14.jj | 282 - .../javacc/VersionAwareGrammar_Example13.jj | 467 -- examples/MailProcessing/README | 110 - examples/MailProcessing/files/1.exp_out.html | 39 - examples/MailProcessing/files/1.out.html | 39 - examples/MailProcessing/files/2.exp_out.html | 20 - examples/MailProcessing/files/2.out.html | 20 - examples/MailProcessing/files/3.exp_out.html | 22 - examples/MailProcessing/files/3.out.html | 22 - examples/MailProcessing/files/cpy.1.out.html | 39 - examples/MailProcessing/files/cpy.2.out.html | 20 - examples/MailProcessing/files/cpy.3.out.html | 22 - .../MailProcessing/files/cpy.index.out.html | 5 - .../MailProcessing/files/digestFile.exp_out | 102 - .../MailProcessing/files/index.exp_out.html | 5 - examples/MailProcessing/files/index.out.html | 5 - .../MailProcessing/files/sampleMailFile.in | 237 - examples/MailProcessing/pom.xml | 182 - .../src/main/java/dig/DigestMain.java | 79 - .../src/main/java/faq/FaqMain.java | 81 - .../MailProcessing/src/main/javacc/Digest.jj | 180 - .../MailProcessing/src/main/javacc/Faq.jj | 195 - examples/Obfuscator/README | 99 - examples/Obfuscator/in/package1/Main.java | 40 - examples/Obfuscator/in/package2/Incr.java | 43 - examples/Obfuscator/obf/maps | 4 - examples/Obfuscator/obf/nochangeids | 6 - examples/Obfuscator/obf/useids | 5 - examples/Obfuscator/out/O01/MyMath.java | 15 - .../Obfuscator/out/html/randomNumber.java | 12 - examples/Obfuscator/out/package1/Main.java | 9 - examples/Obfuscator/pom.xml | 154 - examples/Obfuscator/ref/O01/MyMath.java | 15 - .../Obfuscator/ref/html/randomNumber.java | 12 - examples/Obfuscator/ref/package1/Main.java | 9 - .../Obfuscator/src/main/java/Globals.java | 76 - examples/Obfuscator/src/main/java/Main.java | 113 - .../Obfuscator/src/main/java/Obfuscator.java | 268 - .../Obfuscator/src/main/javacc/IdsFile.jj | 195 - .../Obfuscator/src/main/javacc/Java1.1.jj | 1108 --- .../Obfuscator/src/main/javacc/MapFile.jj | 193 - examples/README.md | 5 - examples/Simple/README | 403 - examples/Simple/idlist/err | 0 examples/Simple/idlist/in | 2 - examples/Simple/idlist/out | 6 - examples/Simple/idlist/ref | 6 - examples/Simple/pom.xml | 256 - examples/Simple/simple1/err | 0 examples/Simple/simple1/in | 1 - examples/Simple/simple1/out | 1 - examples/Simple/simple1/ref | 1 - examples/Simple/simple2/err | 0 examples/Simple/simple2/in | 2 - examples/Simple/simple2/out | 12 - examples/Simple/simple2/ref | 12 - examples/Simple/simple3/err | 0 examples/Simple/simple3/in | 1 - examples/Simple/simple3/out | 2 - examples/Simple/simple3/ref | 2 - examples/Simple/src/main/javacc/IdList.jj | 91 - examples/Simple/src/main/javacc/NL_Xlator.jj | 195 - examples/Simple/src/main/javacc/Simple1.jj | 110 - examples/Simple/src/main/javacc/Simple2.jj | 98 - examples/Simple/src/main/javacc/Simple3.jj | 102 - examples/Simple/xlator/err | 0 examples/Simple/xlator/in | 1 - examples/Simple/xlator/out | 6 - examples/Simple/xlator/ref | 6 - examples/Transformer/README | 62 - examples/Transformer/divide.in | 37 - examples/Transformer/divide.out | 37 - examples/Transformer/divide.ref | 37 - examples/Transformer/pom.xml | 104 - .../src/main/java/ASTCompilationUnit.java | 60 - .../src/main/java/ASTSpecialBlock.java | 54 - examples/Transformer/src/main/java/Node.java | 154 - .../Transformer/src/main/jjtree/ToyJava.jjt | 1076 --- examples/VTransformer/Main.err | 1 - examples/VTransformer/Main.in | 63 - examples/VTransformer/Main.out | 42 - examples/VTransformer/README | 141 - examples/VTransformer/pom.xml | 75 - .../java/VTransformer/AddAcceptVisitor.java | 65 - .../src/main/java/VTransformer/Main.java | 65 - .../src/main/java/VTransformer/Node.java | 156 - .../java/VTransformer/UnparseVisitor.java | 527 -- .../VTransformer/src/main/jjtree/Java1.1.jjt | 1075 --- examples/invoker.properties | 10 - examples/pom.xml | 89 - grammars/README.md | 6 - grammars/asn1/pom.xml | 48 - grammars/asn1/src/main/javacc/AsnParser.jj | 719 -- grammars/c/main.c | 3 - grammars/c/pom.xml | 72 - grammars/c/src/main/javacc/CParser.jj | 599 -- grammars/chemical/pom.xml | 48 - .../chemical/src/main/javacc/ChemNumber.jj | 174 - grammars/cobol/pom.xml | 72 - grammars/cobol/src/main/javacc/Cobol.jj | 2882 ------- grammars/cobol/src/main/test/VARS.cob | 33 - grammars/dtd/pom.xml | 48 - grammars/dtd/src/main/javacc/DTDParser.jj | 204 - grammars/ecma/invoker.properties | 2 - grammars/ecma/pom.xml | 160 - .../ecma/src/main/java/ASTIdentifier.java | 20 - grammars/ecma/src/main/java/ASTLiteral.java | 41 - grammars/ecma/src/main/jjtree/EcmaScript.jjt | 2326 ------ grammars/ecma/src/main/test/main.ecma | 0 grammars/express/pom.xml | 48 - .../express/src/main/javacc/ExpressParser.jj | 1412 ---- grammars/formsplsql/pom.xml | 48 - .../formsplsql/src/main/javacc/FormsPlSql.jj | 1153 --- grammars/gdmo/pom.xml | 48 - .../gdmo/src/main/javacc/GdmoTranslator.jj | 609 -- grammars/idl/pom.xml | 48 - grammars/idl/src/main/javacc/IDLParser.jj | 836 -- grammars/infosapient/invoker.properties | 2 - grammars/infosapient/pom.xml | 48 - .../src/main/javacc/infosapient.jj | 795 -- grammars/invoker.properties | 10 - grammars/java/Java1.0.2.jj | 968 --- grammars/java/Java1.0.2LS.jj | 1010 --- grammars/java/Java1.1-cpp.jj.not_here | 1670 ---- grammars/java/Java1.1.jj | 1697 ---- grammars/java/Java1.1noLA.jj | 1541 ---- grammars/java/JavaGenerics.java | 13 - grammars/java/OPTIMIZING | 267 - grammars/java/README | 71 - grammars/java/Test.java | 15 - grammars/java/pom.xml | 72 - grammars/java/src/main/java/Main.java | 48 - grammars/java/src/main/java/MyToken.java | 22 - grammars/java/src/main/javacc/Java1.5.jj | 2113 ----- grammars/javacc/JavaCC.jj | 1465 ---- grammars/json/pom.xml | 48 - grammars/json/src/main/javacc/JSONParser.jjt | 393 - grammars/oberon/pom.xml | 48 - .../oberon/src/main/javacc/OberonParser.jj | 383 - grammars/petal/invoker.properties | 2 - grammars/petal/pom.xml | 48 - grammars/petal/src/main/javacc/PetalParser.jj | 257 - grammars/php/pom.xml | 48 - grammars/php/src/main/javacc/PHP.jj | 638 -- grammars/plsql/pom.xml | 72 - grammars/plsql/src/main/javacc/PlSql.jj | 1500 ---- grammars/plsql/src/main/test/main.sql | 14 - grammars/pom.xml | 76 - grammars/rtf/invoker.properties | 2 - grammars/rtf/pom.xml | 48 - grammars/rtf/src/main/javacc/RTFParser.jj | 1079 --- grammars/sql/invoker.properties | 2 - grammars/sql/pom.xml | 48 - grammars/sql/src/main/javacc/SQLParser.jj | 7118 ----------------- issues/.gitattributes | 5 - issues/README.md | 22 - issues/bas01/files/clc1.exp_err | 428 - issues/bas01/files/clc1.exp_out | 6 - issues/bas01/files/clc1.in | 4 - issues/bas01/files/clc2.exp_err | 138 - issues/bas01/files/clc2.exp_out | 2 - issues/bas01/files/clc2.in | 3 - issues/bas01/files/clc3.exp_err | 170 - issues/bas01/files/clc3.exp_out | 2 - issues/bas01/files/clc3.in | 3 - issues/bas01/files/clc4.exp_err | 2 - issues/bas01/files/clc4.exp_out | 0 issues/bas01/files/clc4.in | 0 issues/bas01/pom.xml | 252 - .../src/main/javacc/ComplexLineComment.jj | 149 - issues/bas02/files/bug1.exp_err | 1 - issues/bas02/files/bug1.exp_out | 13 - issues/bas02/files/bug1.in | 1 - issues/bas02/files/bug2.exp_err | 6 - issues/bas02/files/bug2.exp_out | 9 - issues/bas02/files/bug2.in | 1 - issues/bas02/files/bug3.exp_err | 1 - issues/bas02/files/bug3.exp_out | 18 - issues/bas02/files/bug3.in | 1 - issues/bas02/pom.xml | 213 - issues/bas02/src/main/javacc/Bug002.jj | 177 - issues/invoker.properties | 10 - issues/issue-7-#1/pom.xml | 50 - issues/issue-7-#1/src/main/javacc/Issue_1.jj | 154 - issues/pom.xml | 79 - it/README.md | 8 - it/build-utils.xml | 119 - it/invoker.properties | 2 - it/pom.xml | 353 - it/settings.xml | 64 - keystore | Bin 2249 -> 0 bytes 339 files changed, 64323 deletions(-) delete mode 100644 examples/CORBA-IDL/README.md delete mode 100644 examples/CORBA-IDL/files/Hello.exp_out delete mode 100644 examples/CORBA-IDL/files/Hello.idl delete mode 100644 examples/CORBA-IDL/pom.xml delete mode 100644 examples/CORBA-IDL/src/main/javacc/IDL.jj delete mode 100644 examples/CustomTemplate/pom.xml delete mode 100644 examples/CustomTemplate/src/main/custom/templates/java/ParseException.template delete mode 100644 examples/CustomTemplate/src/main/javacc/Simple1.jj delete mode 100644 examples/CustomTemplate/verify-files.bsh delete mode 100644 examples/GUIParsing/ParserVersion/README.md delete mode 100644 examples/GUIParsing/ParserVersion/pom.xml delete mode 100644 examples/GUIParsing/ParserVersion/run.cmd delete mode 100644 examples/GUIParsing/ParserVersion/src/main/java/CalcGUI.java delete mode 100644 examples/GUIParsing/ParserVersion/src/main/java/CalcInputParserTreeConstants.java delete mode 100644 examples/GUIParsing/ParserVersion/src/main/java/Main.java delete mode 100644 examples/GUIParsing/ParserVersion/src/main/java/ProducerConsumer.java delete mode 100644 examples/GUIParsing/ParserVersion/src/main/java/TokenCollector.java delete mode 100644 examples/GUIParsing/ParserVersion/src/main/javacc/CalcInput.jj delete mode 100644 examples/GUIParsing/README.md delete mode 100644 examples/GUIParsing/TokenMgrVersion/README.md delete mode 100644 examples/GUIParsing/TokenMgrVersion/pom.xml delete mode 100644 examples/GUIParsing/TokenMgrVersion/run.cmd delete mode 100644 examples/GUIParsing/TokenMgrVersion/src/main/java/CalcGUI.java delete mode 100644 examples/GUIParsing/TokenMgrVersion/src/main/java/CharCollector.java delete mode 100644 examples/GUIParsing/TokenMgrVersion/src/main/java/Main.java delete mode 100644 examples/GUIParsing/TokenMgrVersion/src/main/java/MyLexer.java delete mode 100644 examples/GUIParsing/TokenMgrVersion/src/main/javacc/CalcInput.jj delete mode 100644 examples/GUIParsing/pom.xml delete mode 100644 examples/Gwt/README delete mode 100644 examples/Gwt/checkstyle-suppress.xml delete mode 100644 examples/Gwt/pom.xml delete mode 100644 examples/Gwt/simple/err delete mode 100644 examples/Gwt/simple/out delete mode 100644 examples/Gwt/simple/ref delete mode 100644 examples/Gwt/src/main/javacc/GwtSimpleParser.jj delete mode 100644 examples/Gwt/src/main/javacc/GwtUnicodeParser.jj delete mode 100644 examples/Gwt/unicode/err delete mode 100644 examples/Gwt/unicode/out delete mode 100644 examples/Gwt/unicode/ref delete mode 100644 examples/Interpreter/README delete mode 100644 examples/Interpreter/files/fact/ast-fact.exp_err delete mode 100644 examples/Interpreter/files/fact/ast-fact.exp_out delete mode 100644 examples/Interpreter/files/fact/fact.in delete mode 100644 examples/Interpreter/files/fact/fact.spl delete mode 100644 examples/Interpreter/files/fact/vst-fact.exp_err delete mode 100644 examples/Interpreter/files/fact/vst-fact.exp_out delete mode 100644 examples/Interpreter/files/odd/ast-odd.exp_err delete mode 100644 examples/Interpreter/files/odd/ast-odd.exp_out delete mode 100644 examples/Interpreter/files/odd/odd.in delete mode 100644 examples/Interpreter/files/odd/odd.spl delete mode 100644 examples/Interpreter/files/odd/vst-odd.exp_err delete mode 100644 examples/Interpreter/files/odd/vst-odd.exp_out delete mode 100644 examples/Interpreter/files/sqrt/ast-sqrt.exp_err delete mode 100644 examples/Interpreter/files/sqrt/ast-sqrt.exp_out delete mode 100644 examples/Interpreter/files/sqrt/sqrt.in delete mode 100644 examples/Interpreter/files/sqrt/sqrt.spl delete mode 100644 examples/Interpreter/files/sqrt/vst-sqrt.exp_err delete mode 100644 examples/Interpreter/files/sqrt/vst-sqrt.exp_out delete mode 100644 examples/Interpreter/pom.xml delete mode 100644 examples/Interpreter/src/main/java/ast/MyNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/SPLMain.java delete mode 100644 examples/Interpreter/src/main/java/ast/STAddNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STAndNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STAssignment.java delete mode 100644 examples/Interpreter/src/main/java/ast/STBitwiseAndNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STBitwiseComplNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STBitwiseOrNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STBitwiseXorNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STBlock.java delete mode 100644 examples/Interpreter/src/main/java/ast/STCompilationUnit.java delete mode 100644 examples/Interpreter/src/main/java/ast/STDivNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STEQNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STFalseNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STGENode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STGTNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STId.java delete mode 100644 examples/Interpreter/src/main/java/ast/STIfStatement.java delete mode 100644 examples/Interpreter/src/main/java/ast/STIntConstNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STLENode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STLTNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STModNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STMulNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STNENode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STNotNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STOrNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STReadStatement.java delete mode 100644 examples/Interpreter/src/main/java/ast/STStatementExpression.java delete mode 100644 examples/Interpreter/src/main/java/ast/STSubtractNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STTrueNode.java delete mode 100644 examples/Interpreter/src/main/java/ast/STVarDeclaration.java delete mode 100644 examples/Interpreter/src/main/java/ast/STWhileStatement.java delete mode 100644 examples/Interpreter/src/main/java/ast/STWriteStatement.java delete mode 100644 examples/Interpreter/src/main/java/vst/InterpreterVisitor.java delete mode 100644 examples/Interpreter/src/main/java/vst/SPLMain.java delete mode 100644 examples/Interpreter/src/main/java/vst/ST_Id.java delete mode 100644 examples/Interpreter/src/main/java/vst/ST_IntConstNode.java delete mode 100644 examples/Interpreter/src/main/java/vst/ST_ReadStatement.java delete mode 100644 examples/Interpreter/src/main/java/vst/ST_VarDeclaration.java delete mode 100644 examples/Interpreter/src/main/java/vst/ST_WriteStatement.java delete mode 100644 examples/Interpreter/src/main/jjtree/AST.jjt delete mode 100644 examples/Interpreter/src/main/jjtree/VST.jjt delete mode 100644 examples/JJTree/README delete mode 100644 examples/JJTree/files/eg1.err delete mode 100644 examples/JJTree/files/eg1.in delete mode 100644 examples/JJTree/files/eg1.out delete mode 100644 examples/JJTree/files/eg1.ref delete mode 100644 examples/JJTree/files/eg2.err delete mode 100644 examples/JJTree/files/eg2.in delete mode 100644 examples/JJTree/files/eg2.out delete mode 100644 examples/JJTree/files/eg2.ref delete mode 100644 examples/JJTree/files/eg3.err delete mode 100644 examples/JJTree/files/eg3.in delete mode 100644 examples/JJTree/files/eg3.out delete mode 100644 examples/JJTree/files/eg3.ref delete mode 100644 examples/JJTree/files/eg4.err delete mode 100644 examples/JJTree/files/eg4.in delete mode 100644 examples/JJTree/files/eg4.out delete mode 100644 examples/JJTree/files/eg4.ref delete mode 100644 examples/JJTree/pom.xml delete mode 100644 examples/JJTree/src/main/java/eg2/ASTMyID.java delete mode 100644 examples/JJTree/src/main/java/eg3/ASTMyID.java delete mode 100644 examples/JJTree/src/main/java/eg4/ASTMyID.java delete mode 100644 examples/JJTree/src/main/java/eg4/ASTMyOtherID.java delete mode 100644 examples/JJTree/src/main/java/eg4/Eg4DumpVisitor.java delete mode 100644 examples/JJTree/src/main/java/eg4/MyVisException.java delete mode 100644 examples/JJTree/src/main/jjtree/eg1.jjt delete mode 100644 examples/JJTree/src/main/jjtree/eg2.jjt delete mode 100644 examples/JJTree/src/main/jjtree/eg3.jjt delete mode 100644 examples/JJTree/src/main/jjtree/eg4.jjt delete mode 100644 examples/JavaCC/Java1.5.jj delete mode 100644 examples/JavaCC/checkstyle-suppress.xml delete mode 100644 examples/JavaCC/pom.xml delete mode 100644 examples/JavaCC/src/main/javacc/JavaCC.jj delete mode 100644 examples/Lookahead/README delete mode 100644 examples/Lookahead/pom.xml delete mode 100644 examples/Lookahead/src/main/javacc/Example1.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example10.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example2.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example3.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example4.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example5.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example6.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example7.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example8.jj delete mode 100644 examples/Lookahead/src/main/javacc/Example9.jj delete mode 100644 examples/Lookahead/src/main/javacc/NestedLookaheadGrammar_Example11.jj delete mode 100644 examples/Lookahead/src/main/javacc/NonChoiceLookaheadGrammar_Example12.jj delete mode 100644 examples/Lookahead/src/main/javacc/ReadingLookahedDebugTrace_Example8.jj delete mode 100644 examples/Lookahead/src/main/javacc/RewrittenGrammar_Example14.jj delete mode 100644 examples/Lookahead/src/main/javacc/VersionAwareGrammar_Example13.jj delete mode 100644 examples/MailProcessing/README delete mode 100644 examples/MailProcessing/files/1.exp_out.html delete mode 100644 examples/MailProcessing/files/1.out.html delete mode 100644 examples/MailProcessing/files/2.exp_out.html delete mode 100644 examples/MailProcessing/files/2.out.html delete mode 100644 examples/MailProcessing/files/3.exp_out.html delete mode 100644 examples/MailProcessing/files/3.out.html delete mode 100644 examples/MailProcessing/files/cpy.1.out.html delete mode 100644 examples/MailProcessing/files/cpy.2.out.html delete mode 100644 examples/MailProcessing/files/cpy.3.out.html delete mode 100644 examples/MailProcessing/files/cpy.index.out.html delete mode 100644 examples/MailProcessing/files/digestFile.exp_out delete mode 100644 examples/MailProcessing/files/index.exp_out.html delete mode 100644 examples/MailProcessing/files/index.out.html delete mode 100644 examples/MailProcessing/files/sampleMailFile.in delete mode 100644 examples/MailProcessing/pom.xml delete mode 100644 examples/MailProcessing/src/main/java/dig/DigestMain.java delete mode 100644 examples/MailProcessing/src/main/java/faq/FaqMain.java delete mode 100644 examples/MailProcessing/src/main/javacc/Digest.jj delete mode 100644 examples/MailProcessing/src/main/javacc/Faq.jj delete mode 100644 examples/Obfuscator/README delete mode 100644 examples/Obfuscator/in/package1/Main.java delete mode 100644 examples/Obfuscator/in/package2/Incr.java delete mode 100644 examples/Obfuscator/obf/maps delete mode 100644 examples/Obfuscator/obf/nochangeids delete mode 100644 examples/Obfuscator/obf/useids delete mode 100644 examples/Obfuscator/out/O01/MyMath.java delete mode 100644 examples/Obfuscator/out/html/randomNumber.java delete mode 100644 examples/Obfuscator/out/package1/Main.java delete mode 100644 examples/Obfuscator/pom.xml delete mode 100644 examples/Obfuscator/ref/O01/MyMath.java delete mode 100644 examples/Obfuscator/ref/html/randomNumber.java delete mode 100644 examples/Obfuscator/ref/package1/Main.java delete mode 100644 examples/Obfuscator/src/main/java/Globals.java delete mode 100644 examples/Obfuscator/src/main/java/Main.java delete mode 100644 examples/Obfuscator/src/main/java/Obfuscator.java delete mode 100644 examples/Obfuscator/src/main/javacc/IdsFile.jj delete mode 100644 examples/Obfuscator/src/main/javacc/Java1.1.jj delete mode 100644 examples/Obfuscator/src/main/javacc/MapFile.jj delete mode 100644 examples/README.md delete mode 100644 examples/Simple/README delete mode 100644 examples/Simple/idlist/err delete mode 100644 examples/Simple/idlist/in delete mode 100644 examples/Simple/idlist/out delete mode 100644 examples/Simple/idlist/ref delete mode 100644 examples/Simple/pom.xml delete mode 100644 examples/Simple/simple1/err delete mode 100644 examples/Simple/simple1/in delete mode 100644 examples/Simple/simple1/out delete mode 100644 examples/Simple/simple1/ref delete mode 100644 examples/Simple/simple2/err delete mode 100644 examples/Simple/simple2/in delete mode 100644 examples/Simple/simple2/out delete mode 100644 examples/Simple/simple2/ref delete mode 100644 examples/Simple/simple3/err delete mode 100644 examples/Simple/simple3/in delete mode 100644 examples/Simple/simple3/out delete mode 100644 examples/Simple/simple3/ref delete mode 100644 examples/Simple/src/main/javacc/IdList.jj delete mode 100644 examples/Simple/src/main/javacc/NL_Xlator.jj delete mode 100644 examples/Simple/src/main/javacc/Simple1.jj delete mode 100644 examples/Simple/src/main/javacc/Simple2.jj delete mode 100644 examples/Simple/src/main/javacc/Simple3.jj delete mode 100644 examples/Simple/xlator/err delete mode 100644 examples/Simple/xlator/in delete mode 100644 examples/Simple/xlator/out delete mode 100644 examples/Simple/xlator/ref delete mode 100644 examples/Transformer/README delete mode 100644 examples/Transformer/divide.in delete mode 100644 examples/Transformer/divide.out delete mode 100644 examples/Transformer/divide.ref delete mode 100644 examples/Transformer/pom.xml delete mode 100644 examples/Transformer/src/main/java/ASTCompilationUnit.java delete mode 100644 examples/Transformer/src/main/java/ASTSpecialBlock.java delete mode 100644 examples/Transformer/src/main/java/Node.java delete mode 100644 examples/Transformer/src/main/jjtree/ToyJava.jjt delete mode 100644 examples/VTransformer/Main.err delete mode 100644 examples/VTransformer/Main.in delete mode 100644 examples/VTransformer/Main.out delete mode 100644 examples/VTransformer/README delete mode 100644 examples/VTransformer/pom.xml delete mode 100644 examples/VTransformer/src/main/java/VTransformer/AddAcceptVisitor.java delete mode 100644 examples/VTransformer/src/main/java/VTransformer/Main.java delete mode 100644 examples/VTransformer/src/main/java/VTransformer/Node.java delete mode 100644 examples/VTransformer/src/main/java/VTransformer/UnparseVisitor.java delete mode 100644 examples/VTransformer/src/main/jjtree/Java1.1.jjt delete mode 100644 examples/invoker.properties delete mode 100644 examples/pom.xml delete mode 100644 grammars/README.md delete mode 100644 grammars/asn1/pom.xml delete mode 100644 grammars/asn1/src/main/javacc/AsnParser.jj delete mode 100644 grammars/c/main.c delete mode 100644 grammars/c/pom.xml delete mode 100644 grammars/c/src/main/javacc/CParser.jj delete mode 100644 grammars/chemical/pom.xml delete mode 100644 grammars/chemical/src/main/javacc/ChemNumber.jj delete mode 100644 grammars/cobol/pom.xml delete mode 100644 grammars/cobol/src/main/javacc/Cobol.jj delete mode 100644 grammars/cobol/src/main/test/VARS.cob delete mode 100644 grammars/dtd/pom.xml delete mode 100644 grammars/dtd/src/main/javacc/DTDParser.jj delete mode 100644 grammars/ecma/invoker.properties delete mode 100644 grammars/ecma/pom.xml delete mode 100644 grammars/ecma/src/main/java/ASTIdentifier.java delete mode 100644 grammars/ecma/src/main/java/ASTLiteral.java delete mode 100644 grammars/ecma/src/main/jjtree/EcmaScript.jjt delete mode 100644 grammars/ecma/src/main/test/main.ecma delete mode 100644 grammars/express/pom.xml delete mode 100644 grammars/express/src/main/javacc/ExpressParser.jj delete mode 100644 grammars/formsplsql/pom.xml delete mode 100644 grammars/formsplsql/src/main/javacc/FormsPlSql.jj delete mode 100644 grammars/gdmo/pom.xml delete mode 100644 grammars/gdmo/src/main/javacc/GdmoTranslator.jj delete mode 100644 grammars/idl/pom.xml delete mode 100644 grammars/idl/src/main/javacc/IDLParser.jj delete mode 100644 grammars/infosapient/invoker.properties delete mode 100644 grammars/infosapient/pom.xml delete mode 100644 grammars/infosapient/src/main/javacc/infosapient.jj delete mode 100644 grammars/invoker.properties delete mode 100644 grammars/java/Java1.0.2.jj delete mode 100644 grammars/java/Java1.0.2LS.jj delete mode 100644 grammars/java/Java1.1-cpp.jj.not_here delete mode 100644 grammars/java/Java1.1.jj delete mode 100644 grammars/java/Java1.1noLA.jj delete mode 100644 grammars/java/JavaGenerics.java delete mode 100644 grammars/java/OPTIMIZING delete mode 100644 grammars/java/README delete mode 100644 grammars/java/Test.java delete mode 100644 grammars/java/pom.xml delete mode 100644 grammars/java/src/main/java/Main.java delete mode 100644 grammars/java/src/main/java/MyToken.java delete mode 100644 grammars/java/src/main/javacc/Java1.5.jj delete mode 100644 grammars/javacc/JavaCC.jj delete mode 100644 grammars/json/pom.xml delete mode 100644 grammars/json/src/main/javacc/JSONParser.jjt delete mode 100644 grammars/oberon/pom.xml delete mode 100644 grammars/oberon/src/main/javacc/OberonParser.jj delete mode 100644 grammars/petal/invoker.properties delete mode 100644 grammars/petal/pom.xml delete mode 100644 grammars/petal/src/main/javacc/PetalParser.jj delete mode 100644 grammars/php/pom.xml delete mode 100644 grammars/php/src/main/javacc/PHP.jj delete mode 100644 grammars/plsql/pom.xml delete mode 100644 grammars/plsql/src/main/javacc/PlSql.jj delete mode 100644 grammars/plsql/src/main/test/main.sql delete mode 100644 grammars/pom.xml delete mode 100644 grammars/rtf/invoker.properties delete mode 100644 grammars/rtf/pom.xml delete mode 100644 grammars/rtf/src/main/javacc/RTFParser.jj delete mode 100644 grammars/sql/invoker.properties delete mode 100644 grammars/sql/pom.xml delete mode 100644 grammars/sql/src/main/javacc/SQLParser.jj delete mode 100644 issues/.gitattributes delete mode 100644 issues/README.md delete mode 100644 issues/bas01/files/clc1.exp_err delete mode 100644 issues/bas01/files/clc1.exp_out delete mode 100644 issues/bas01/files/clc1.in delete mode 100644 issues/bas01/files/clc2.exp_err delete mode 100644 issues/bas01/files/clc2.exp_out delete mode 100644 issues/bas01/files/clc2.in delete mode 100644 issues/bas01/files/clc3.exp_err delete mode 100644 issues/bas01/files/clc3.exp_out delete mode 100644 issues/bas01/files/clc3.in delete mode 100644 issues/bas01/files/clc4.exp_err delete mode 100644 issues/bas01/files/clc4.exp_out delete mode 100644 issues/bas01/files/clc4.in delete mode 100644 issues/bas01/pom.xml delete mode 100644 issues/bas01/src/main/javacc/ComplexLineComment.jj delete mode 100644 issues/bas02/files/bug1.exp_err delete mode 100644 issues/bas02/files/bug1.exp_out delete mode 100644 issues/bas02/files/bug1.in delete mode 100644 issues/bas02/files/bug2.exp_err delete mode 100644 issues/bas02/files/bug2.exp_out delete mode 100644 issues/bas02/files/bug2.in delete mode 100644 issues/bas02/files/bug3.exp_err delete mode 100644 issues/bas02/files/bug3.exp_out delete mode 100644 issues/bas02/files/bug3.in delete mode 100644 issues/bas02/pom.xml delete mode 100644 issues/bas02/src/main/javacc/Bug002.jj delete mode 100644 issues/invoker.properties delete mode 100644 issues/issue-7-#1/pom.xml delete mode 100644 issues/issue-7-#1/src/main/javacc/Issue_1.jj delete mode 100644 issues/pom.xml delete mode 100644 it/README.md delete mode 100644 it/build-utils.xml delete mode 100644 it/invoker.properties delete mode 100644 it/pom.xml delete mode 100644 it/settings.xml delete mode 100644 keystore diff --git a/examples/CORBA-IDL/README.md b/examples/CORBA-IDL/README.md deleted file mode 100644 index dfe33cb..0000000 --- a/examples/CORBA-IDL/README.md +++ /dev/null @@ -1,11 +0,0 @@ -This directory contains an CORBA 2.0 grammar for [IDL](src/main/java/IDL.jj). - -It parses an input file and just outputs a success or failure message. - -Build it in the usual manner with [pom.xml](pom.xml): - -- Maven: - -``` - mvn clean verify -``` diff --git a/examples/CORBA-IDL/files/Hello.exp_out b/examples/CORBA-IDL/files/Hello.exp_out deleted file mode 100644 index 46511fc..0000000 --- a/examples/CORBA-IDL/files/Hello.exp_out +++ /dev/null @@ -1,2 +0,0 @@ -IDL Parser Version 0.1: Reading from file ${project-basedir}/files/Hello.idl . . . -IDL Parser Version 0.1: IDL file parsed successfully. diff --git a/examples/CORBA-IDL/files/Hello.idl b/examples/CORBA-IDL/files/Hello.idl deleted file mode 100644 index 0dc1964..0000000 --- a/examples/CORBA-IDL/files/Hello.idl +++ /dev/null @@ -1,7 +0,0 @@ -module HelloApp -{ - interface Hello - { - string sayHello(); - }; -}; diff --git a/examples/CORBA-IDL/pom.xml b/examples/CORBA-IDL/pom.xml deleted file mode 100644 index 9a0a63f..0000000 --- a/examples/CORBA-IDL/pom.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - corba-idl - jar - - JavaCC Java code generator / examples / CORBA-IDL - - - - - - - org.apache.maven.plugins - maven-clean-plugin - - - clear-res-test - process-test-resources - - clean - - - true - - - files - - *.out - *.err - - - - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - - exec-test - test - - run - - - ${skip.test.java.examples.CORBA-IDL} - - - - - - - - - - - - check-res-test - test - - run - - - ${skip.test.java.examples.CORBA-IDL} - ${failOnError.check.java.examples.CORBA-IDL} - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/CORBA-IDL/src/main/javacc/IDL.jj b/examples/CORBA-IDL/src/main/javacc/IDL.jj deleted file mode 100644 index e519e7d..0000000 --- a/examples/CORBA-IDL/src/main/javacc/IDL.jj +++ /dev/null @@ -1,865 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(IDLParser) - -public class IDLParser { - - public static void main(String args[]) { - IDLParser parser; - if (args.length == 0) { - System.out.println("IDL Parser Version 0.1: Reading from standard input . . ."); - parser = new IDLParser(System.in); - } else if (args.length == 1) { - System.out.println("IDL Parser Version 0.1: Reading from file " + args[0] + " . . ."); - try { - parser = new IDLParser(new java.io.FileInputStream(args[0])); - } catch (java.io.FileNotFoundException e) { - System.out.println("IDL Parser Version 0.1: File " + args[0] + " not found."); - return; - } - } else { - System.out.println("IDL Parser Version 0.1: Usage is one of:"); - System.out.println(" java IDLParser < inputfile"); - System.out.println("OR"); - System.out.println(" java IDLParser inputfile"); - return; - } - try { - parser.specification(); - System.out.println("IDL Parser Version 0.1: IDL file parsed successfully."); - } catch (ParseException e) { - System.out.println("IDL Parser Version 0.1: Encountered errors during parse."); - } - } - -} - -PARSER_END(IDLParser) - -/* - * Tokens to ignore in the BNF follow. - */ - -SKIP : -{ - < " " > -| < "\t" > -| < "\n" > -| < "\r" > -| < "//" (~["\n"])* "\n" > -| <"/*" (~["*"])* "*" (~["/"] (~["*"])* "*")* "/"> -| < "#" ([" ","\t"])* (["0"-"9"])+ - (([" ","\t"])* "\"" (~["\""])+ "\"" - ([" ","\t"])* (["0"-"9"])* ([" ","\t"])* (["0"-"9"])*)? "\n" > -} - -/* Production 1 */ - -void specification() : -{} -{ - ( definition() )+ -} - -/* Production 2 */ - -void definition() : -{} -{ - type_dcl() ";" -| - const_dcl() ";" -| - except_dcl() ";" -| - interfacex() ";" -| - module() ";" -} - -/* Production 3 */ - -void module() : -{} -{ - "module" identifier() "{" ( definition() )+ "}" -} - -/* Production 4 */ - -void interfacex() : -{} -{ - LOOKAHEAD(3) - interface_dcl() -| - forward_dcl() -} - -/* Production 5 */ - -void interface_dcl() : -{} -{ - interface_header() "{" interface_body() "}" -} - -/* Production 6 */ - -void forward_dcl() : -{} -{ - "interface" identifier() -} - -/* Production 7 */ - -void interface_header() : -{} -{ - "interface" identifier() [ inheritance_spec() ] -} - -/* Production 8 */ - -void interface_body() : -{} -{ - ( export() )* -} - -/* Production 9 */ - -void export() : -{} -{ - type_dcl() ";" -| - const_dcl() ";" -| - except_dcl() ";" -| - attr_dcl() ";" -| - op_dcl() ";" -} - -/* Production 10 */ - -void inheritance_spec() : -{} -{ - ":" scoped_name() ( "," scoped_name() )* -} - -/* Production 11 */ - -void scoped_name() : -{} -{ - [ "::" ] identifier() ( "::" identifier() )* -} - -/* Production 12 */ - -void const_dcl() : -{} -{ - "const" const_type() identifier() "=" const_exp() -} - -/* Production 13 */ - -void const_type() : -{} -{ - integer_type() -| - char_type() -| - boolean_type() -| - floating_pt_type() -| - string_type() -| - scoped_name() -} - -/* Production 14 */ - -void const_exp() : -{} -{ - or_expr() -} - -/* Production 15 */ - -void or_expr() : -{} -{ - xor_expr() ( "|" xor_expr() )* -} - -/* Production 16 */ - -void xor_expr() : -{} -{ - and_expr() ( "^" and_expr() )* -} - -/* Production 17 */ - -void and_expr() : -{} -{ - shift_expr() ( "&" shift_expr() )* -} - -/* Production 18 */ - -void shift_expr() : -{} -{ - add_expr() ( ( ">>" | "<<" ) add_expr() )* -} - -/* Production 19 */ - -void add_expr() : -{} -{ - mult_expr() ( ( "+" | "-" ) mult_expr() )* -} - -/* Production 20 */ - -void mult_expr() : -{} -{ - unary_expr() ( ( "*" | "/" | "%" ) unary_expr() )* -} - -/* Production 21 */ - -void unary_expr() : -{} -{ - [ unary_operator() ] primary_expr() -} - -/* Production 22 */ -void unary_operator() : -{} -{ - "-" -| - "+" -| - "~" -} - -/* Production 23 */ - -void primary_expr() : -{} -{ - scoped_name() -| - literal() -| - "(" const_exp() ")" -} - -/* Production 24 */ - -void literal() : -{} -{ - integer_literal() -| - string_literal() -| - character_literal() -| - floating_pt_literal() -| - boolean_literal() -} - -/* Production 25 */ - -void boolean_literal() : -{} -{ - "TRUE" -| - "FALSE" -} - -/* Production 26 */ - -void positive_int_const() : -{} -{ - const_exp() -} - -/* Production 27 */ - -void type_dcl() : -{} -{ - "typedef" type_declarator() -| - struct_type() -| - union_type() -| - enum_type() -} - -/* Production 28 */ - -void type_declarator() : -{} -{ - type_spec() declarators() -} - -/* Production 29 */ - -void type_spec() : -{} -{ - simple_type_spec() -| - constr_type_spec() -} - -/* Production 30 */ - -void simple_type_spec() : -{} -{ - base_type_spec() -| - template_type_spec() -| - scoped_name() -} - -/* Production 31 */ - -void base_type_spec() : -{} -{ - floating_pt_type() -| - integer_type() -| - char_type() -| - boolean_type() -| - octet_type() -| - any_type() -} - -/* Production 32 */ - -void template_type_spec() : -{} -{ - sequence_type() -| - string_type() -} - -/* Production 33 */ - -void constr_type_spec() : -{} -{ - struct_type() -| - union_type() -| - enum_type() -} - -/* Production 34 */ - -void declarators() : -{} -{ - declarator() ( "," declarator() )* -} - -/* Production 35 */ - -void declarator() : -{} -{ - LOOKAHEAD(2) - complex_declarator() -| - simple_declarator() -} - -/* Production 36 */ - -void simple_declarator() : -{} -{ - identifier() -} - -/* Production 37 */ - -void complex_declarator() : -{} -{ - array_declarator() -} - -/* Production 38 */ - -void floating_pt_type() : -{} -{ - "float" -| - "double" -} - -/* Production 39 */ - -void integer_type() : -{} -{ - signed_int() -| - unsigned_int() -} - -/* Production 40 */ - -void signed_int() : -{} -{ - signed_long_int() -| - signed_short_int() -} - -/* Production 41 */ - -void signed_long_int() : -{} -{ - "long" -} - -/* Production 42 */ - -void signed_short_int() : -{} -{ - "short" -} - -/* Production 43 */ - -void unsigned_int() : -{} -{ - LOOKAHEAD(2) - unsigned_long_int() -| - unsigned_short_int() -} - -/* Production 44 */ - -void unsigned_long_int() : -{} -{ - "unsigned" "long" -} - -/* Production 45 */ - -void unsigned_short_int() : -{} -{ - "unsigned" "short" -} - -/* Production 46 */ - -void char_type() : -{} -{ - "char" -} - -/* Production 47 */ - -void boolean_type() : -{} -{ - "boolean" -} - -/* Production 48 */ - -void octet_type() : -{} -{ - "octet" -} - -/* Production 49 */ - -void any_type() : -{} -{ - "any" -} - -/* Production 50 */ - -void struct_type() : -{} -{ - "struct" identifier() "{" member_list() "}" -} - -/* Production 51 */ - -void member_list() : -{} -{ - ( member() )+ -} - -/* Production 52 */ - -void member() : -{} -{ - type_spec() declarators() ";" -} - -/* Production 53 */ - -void union_type() : -{} -{ - "union" identifier() "switch" "(" switch_type_spec() ")" "{" switch_body() "}" -} - -/* Production 54 */ - -void switch_type_spec() : -{} -{ - integer_type() -| - char_type() -| - boolean_type() -| - enum_type() -| - scoped_name() -} - -/* Production 55 */ - -void switch_body() : -{} -{ - ( casex() )+ -} - -/* Production 56 */ - -void casex() : -{} -{ - ( case_label() )+ element_spec() ";" -} - -/* Production 57 */ - -void case_label() : -{} -{ - "case" const_exp() ":" -| - "default" ":" -} - -/* Production 58 */ - -void element_spec() : -{} -{ - type_spec() declarator() -} - -/* Production 59 */ - -void enum_type() : -{} -{ - "enum" identifier() "{" enumerator() ( "," enumerator() )* "}" -} - -/* Production 60 */ - -void enumerator() : -{} -{ - identifier() -} - -/* Production 61 */ - -void sequence_type() : -{} -{ - "sequence" "<" simple_type_spec() [ "," positive_int_const() ] ">" -} - -/* Production 62 */ - -void string_type() : -{} -{ - "string" [ "<" positive_int_const() ">" ] -} - -/* Production 63 */ - -void array_declarator() : -{} -{ - identifier() ( fixed_array_size() )+ -} - -/* Production 64 */ - -void fixed_array_size() : -{} -{ - "[" positive_int_const() "]" -} - -/* Production 65 */ - -void attr_dcl() : -{} -{ - [ "readonly" ] "attribute" param_type_spec() simple_declarator() ( "," simple_declarator() )* -} - -/* Production 66 */ - -void except_dcl() : -{} -{ - "exception" identifier() "{" ( member() )* "}" -} - -/* Production 67 */ - -void op_dcl() : -{} -{ - [ op_attribute() ] op_type_spec() identifier() parameter_dcls() [ raises_expr() ] [ context_expr() ] -} - -/* Production 68 */ - -void op_attribute() : -{} -{ - "oneway" -} - -/* Production 69 */ - -void op_type_spec() : -{} -{ - param_type_spec() -| - "void" -} - -/* Production 70 */ - -void parameter_dcls() : -{} -{ - "(" [ param_dcl() ( "," param_dcl() )* ] ")" -} - -/* Production 71 */ - -void param_dcl() : -{} -{ - param_attribute() param_type_spec() simple_declarator() -} - -/* Production 72 */ - -void param_attribute() : -{} -{ - "in" -| - "out" -| - "inout" -} - -/* Production 73 */ - -void raises_expr() : -{} -{ - "raises" "(" scoped_name() ( "," scoped_name() )* ")" -} - -/* Production 74 */ - -void context_expr() : -{} -{ - "context" "(" string_literal() ( "," string_literal() )* ")" -} - -/* Production 75 */ - -void param_type_spec() : -{} -{ - base_type_spec() -| - string_type() -| - scoped_name() -} - -/* Definitions of complex regular expressions follow */ - -void identifier() : -{} -{ - -} - -void integer_literal() : -{} -{ - -| - -| - -} - -void string_literal() : -{} -{ - -} - -void character_literal() : -{} -{ - -} - -void floating_pt_literal() : -{} -{ - -| - -} - -TOKEN : -{ - < ID : ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_"])* > -| < OCTALINT : "0" (["0"-"7"])* (["u","U","l","L"])? > -| < DECIMALINT : ["1"-"9"] (["0"-"9"])* (["u","U","l","L"])? > -| < HEXADECIMALINT : ("0x"|"0X") (["0"-"9","a"-"f","A"-"F"])+ (["u","U","l","L"])? > -| < FLOATONE : ((["0"-"9"])+ "." (["0"-"9"])* | (["0"-"9"])* "." (["0"-"9"])+) - (["e","E"] (["-","+"])? (["0"-"9"])+)? (["f","F","l","L"])? > -| < FLOATTWO : (["0"-"9"])+ ["e","E"] (["-","+"])? - (["0"-"9"])+ (["f","F","l","L"])? > -| < CHARACTER : "'" - ( (~["'","\\","\n","\r"]) - | ("\\" ( - ["n","t","v","b","r","f","a","\\","?","'","\""] - | - "0" (["0"-"7"])* - | - ["1"-"9"] (["0"-"9"])* - | - ("0x" | "0X") (["0"-"9","a"-"f","A"-"F"])+ - ) - ) - ) - "'" > -| < STRING : "\"" - ( ( ~["\"","\\","\n","\r"]) - | ("\\" ( - ["n","t","v","b","r","f","a","\\","?","'","\""] - | - "0" (["0"-"7"])* - | - ["1"-"9"] (["0"-"9"])* - | - ("0x" | "0X") (["0"-"9","a"-"f","A"-"F"])+ - ) - ) - )* - "\"" > -} diff --git a/examples/CustomTemplate/pom.xml b/examples/CustomTemplate/pom.xml deleted file mode 100644 index 30b999e..0000000 --- a/examples/CustomTemplate/pom.xml +++ /dev/null @@ -1,147 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - CustomTemplate - jar - - JavaCC Java code generator / CustomTemplate - - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - custom-dir - initialize - - copy-resources - - - ${basedir}/target/custom - - - ${basedir}/src/main/custom - - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - jar-cust-jar - initialize - - exec - - - jar - - cf - ${basedir}/target/custom/cust-tpt.jar - -C - ${basedir}/src/main/custom - templates/java - - - - - - - - - - org.apache.maven.plugins - maven-install-plugin - - - install-cust-file - initialize - - install-file - - - - - ${basedir}/target/custom/cust-tpt.jar - org.javacc.generator.java.examples.CustomTemplate - custom-jar - 1.1.0-SNAPSHOT - jar - - - - - - - org.javacc.plugin - javacc-maven-plugin - - - org.javacc.generator.java.examples.CustomTemplate - custom-jar - 1.1.0-SNAPSHOT - runtime - - - - - - - - - \ No newline at end of file diff --git a/examples/CustomTemplate/src/main/custom/templates/java/ParseException.template b/examples/CustomTemplate/src/main/custom/templates/java/ParseException.template deleted file mode 100644 index f0112ed..0000000 --- a/examples/CustomTemplate/src/main/custom/templates/java/ParseException.template +++ /dev/null @@ -1,258 +0,0 @@ -#if PRINT_LICENSE -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -#fi -// !!!!!!!!!!!!!!!!!!!!!!!!!! -// !!! Customization test !!! -// !!!!!!!!!!!!!!!!!!!!!!!!!! -/** - * The class generated by Javacc/java (by JavaTemplates.java with java/ParseException.template) - * that is thrown when parse errors are encountered.
- * You can explicitly create objects of this exception type by calling the method - * generateParseException() in the generated parser. - * You can modify this class to customize your error reporting mechanisms - * so long as you retain the public fields. - */ -public class ParseException extends Exception { - - /** - * The version identifier for this Serializable class.
- * Increment only if the serialized form of the class changes. - */ - private static final long serialVersionUID = 1L; - - /** The end of line string for this system. */ - protected static String EOL = System.getProperty("line.separator", "\n"); - - /** - * This constructor is used by the method "generateParseException" in the generated parser.
- * Calling this constructor generates a new object of this type with the fields "currentToken", - * "expectedTokenSequences", "expectedTokenSequencesLoc", "tokenImage and "locationVal" set. - */ - public ParseException( Token currentTokenVal, - int[][] expectedTokenSequencesVal, - String[][] expectedTokenSequencesLocVal, - String[] tokenImageVal, - String locationVal) { - super(initialise(currentTokenVal, - expectedTokenSequencesVal, - expectedTokenSequencesLocVal, - tokenImageVal, - locationVal)); - currentToken = currentTokenVal; - expectedTokenSequences = expectedTokenSequencesVal; - expectedTokenSequencesLoc = expectedTokenSequencesLocVal; - tokenImage = tokenImageVal; - location = locationVal; - } - - /* - * The following constructors are for use by you for whatever purpose you can think of. - * Constructing the exception in this manner makes the exception behave in the normal way. - * The fields "errorToken", "expectedTokenSequences", "tokenImage and "location" - * will not contain relevant information. - * The JavaCC generated code does not use these constructors. - */ - - /** Constructor without message. */ - public ParseException() { - super(); - } - - /** Constructor with message. */ - public ParseException(String message) { - super(message); - } - - /** - * This is the last token that has been consumed successfully.
- * If this object has been created due to a parse error, - * the token following this token will (therefore) be the first error token. - */ - public Token currentToken; - - /** - * Each entry in this array is an array of integers.
- * Each array of integers represents a sequence of tokens (by their ordinal values) - * that are expected at this point of the parse. - */ - public int[][] expectedTokenSequences; - - /** - * Each entry in this array is an array of strings.
- * Each array of strings represents a sequence of tokens images (by their ordinal values) - * that are expected at this point of the parse. - */ - public String[][] expectedTokenSequencesLoc; - - /** - * This is a reference to the "tokenImage" array of the generated parser within which - * the parse error occurred.
- * This array is defined in the generated ParserConstants interface. - */ - public String[] tokenImage; - - /** - * The location of the expansion where the exception arose. - */ - public String location; - - /** - * Generate a parse error message and returns it.
- * If this object has been created due to a parse error and you do not catch it - * (i.e. it gets thrown from the parser), the correct error message gets displayed. - */ - private static String initialise( Token currToken, - int[][] expTokenSequences, - String[][] expTokenSequencesLoc, - String[] tokImage, - String loc) { - - final StringBuilder expected = new StringBuilder(32); - int maxSize = 0; - - // outer: - for (int i = 0; i < expTokenSequences.length; i++) { - final int[] expTkSeq = expTokenSequences[i]; - // for the moment we prefer to keep printing duplicated sequences, - // hoping we can find a way to print their (different) locations in the grammar - // for (int k = 0; k < i; k++) { - // // don't print duplicated sequences - // if (java.util.Arrays.equals(expTkSeq, expTokenSequences[k])) { - // continue outer; - // } - // } - if (maxSize < expTkSeq.length) { - maxSize = expTkSeq.length; - } - for (int j = 0; j < expTkSeq.length; j++) { - if (j > 0) { - expected.append(' '); - } else { - expected.append(" "); - } - expected.append(tokImage[expTkSeq[j]]).append(' '); - expected.append("(inside ").append(expTokenSequencesLoc[i][j]).append(") "); - } - if (expTkSeq[expTkSeq.length - 1] != 0) { - expected.append("..."); - } - expected.append(EOL); - } - - final StringBuilder sb = new StringBuilder(64); - - // temp debug - /* - sb.append("currToken = " + currToken).append(EOL); - for (int i = 0; i < expTokenSequences.length; i++) { - sb.append("expTokenSequences[" + i + "] = " + java.util.Arrays.toString(expTokenSequences[i])).append(EOL); - } - sb.append("tokImage = " + java.util.Arrays.toString(tokImage)).append(EOL); - sb.append("loc = " + loc).append(EOL); - */ - - sb.append("Encountered:"); - Token tok = currToken.next; - for (int i = 0; i < maxSize; i++) { - sb.append(' '); - if (tok.kind == 0) { - sb.append(tokImage[0]); - break; - } - sb.append(tokImage[tok.kind]).append(" / \"").append(add_escapes(tok.image)).append('"'); - tok = tok.next; - } -#if KEEP_LINE_COLUMN - sb.append(", at line ").append(currToken.next.beginLine) - .append(", column ").append(currToken.next.beginColumn); -#fi - sb.append('.').append(EOL); - - if (expTokenSequences.length == 0) { - // Nothing to add here - } else { - if (expTokenSequences.length == 1) { - sb.append("Was expecting this terminal"); - } else { - sb.append("Was expecting one of these terminals"); - } - sb.append(" within expansion starting at ").append(loc).append(':').append(EOL); - sb.append(expected.toString()); - } - return sb.toString(); - - } - - /** - * Used to convert raw characters to their escaped version when these raw version - * cannot be used as part of an ASCII string literal. - */ - static String add_escapes(String str) { - final StringBuilder retval = new StringBuilder(); - char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) { - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - } - } - return retval.toString(); - } -} diff --git a/examples/CustomTemplate/src/main/javacc/Simple1.jj b/examples/CustomTemplate/src/main/javacc/Simple1.jj deleted file mode 100644 index e93a239..0000000 --- a/examples/CustomTemplate/src/main/javacc/Simple1.jj +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - LOOKAHEAD = 1; - CHOICE_AMBIGUITY_CHECK = 2; - OTHER_AMBIGUITY_CHECK = 1; - STATIC = true; - DEBUG_PARSER = false; - DEBUG_LOOKAHEAD = false; - DEBUG_TOKEN_MANAGER = false; - ERROR_REPORTING = true; - JAVA_UNICODE_ESCAPE = false; - UNICODE_INPUT = false; - IGNORE_CASE = false; - USER_TOKEN_MANAGER = false; - USER_CHAR_STREAM = false; - BUILD_PARSER = true; - BUILD_TOKEN_MANAGER = true; - SANITY_CHECK = true; - FORCE_LA_CHECK = false; -} - -PARSER_BEGIN(Simple1) -package simple1; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - - -/** Simple brace matcher. */ -public class Simple1 { - - /** Main entry point. */ - public static void main(String args[]) throws ParseException, FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; - input = new FileInputStream(args[0]); - prevOutput = output; - output = new PrintStream(args[1]); - prevError = error; - error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - Simple1 parser = new Simple1(input); - parser.Input(); - output.println("matched"); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(Simple1) - -/** Root production. */ -void Input() : -{} -{ - MatchedBraces() ("\n"|"\r")* -} - -/** Brace matching production. */ -void MatchedBraces() : -{} -{ - "{" [ MatchedBraces() ] "}" -} diff --git a/examples/CustomTemplate/verify-files.bsh b/examples/CustomTemplate/verify-files.bsh deleted file mode 100644 index 0a2f34f..0000000 --- a/examples/CustomTemplate/verify-files.bsh +++ /dev/null @@ -1,26 +0,0 @@ -import java.io.*; -import java.util.*; -import org.codehaus.plexus.util.*; - -// just checks for a java file with customized contents - -try -{ - File of = new File( basedir, "target/generated-sources/java/simple1/ParseException.java" ); - - String contents = FileUtils.fileRead( of, "UTF-8" ); - if ( !contents.contains( "// !!! Customization test !!!" ) ) - { - System.err.println( "Generated ParseException.java is not the customized one expected" ); - return false; - } - - System.out.println( "Generated ParseException.java is the customized one expected" ); -} -catch( Throwable t ) -{ - t.printStackTrace(); - return false; -} - -return true; diff --git a/examples/GUIParsing/ParserVersion/README.md b/examples/GUIParsing/ParserVersion/README.md deleted file mode 100644 index 196579d..0000000 --- a/examples/GUIParsing/ParserVersion/README.md +++ /dev/null @@ -1,28 +0,0 @@ -This version of the GUI parsing example defines the GUI interaction as a JavaCC grammar using tokens that are generated by a user built token manager. -Note that these tokens appear in the parser (`CalcInput.jj`) without definitions (such as ``, ``, etc.). -JavaCC does not require token definitions when `USER_TOKEN_MANAGER` is set to `true`. -The token manager is implemented in `TokenCollector.java` to extract tokens from a producer-consumer object in `ProducerConsumer.java`. -The tokens are stuffed into `ProducerConsumer.java` by the GUI which is defined in `CalcGUI.java`. -The whole system is invoked through `Main.java`. - -The point of this example is to illustrate: - -- How a parser can be used without the standard token manager. -- The fact that tokens can be generated by entities that are not even streams (a GUI in this example). -- That GUI interaction can be modeled as a grammar and this grammar can then be used to implement the innards of a GUI based tool. - -Build it in the usual manner with [pom.xml](pom.xml): - -- Maven: - -``` - mvn clean verify -``` - -Then run the GUI: - -- command line: - -``` - java -cp target/classes/ Main -``` diff --git a/examples/GUIParsing/ParserVersion/pom.xml b/examples/GUIParsing/ParserVersion/pom.xml deleted file mode 100644 index 2731c31..0000000 --- a/examples/GUIParsing/ParserVersion/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java.examples - guiparsing - 1.1.0-SNAPSHOT - - - org.javacc.examples.java.guiparsing - ParserVersion - jar - - JavaCC Java code generator / examples / GUIParsing / ParserVersion - - - - \ No newline at end of file diff --git a/examples/GUIParsing/ParserVersion/run.cmd b/examples/GUIParsing/ParserVersion/run.cmd deleted file mode 100644 index ca7b6f3..0000000 --- a/examples/GUIParsing/ParserVersion/run.cmd +++ /dev/null @@ -1,3 +0,0 @@ -Rem script to run the calculator -java -cp target/classes Main -Pause \ No newline at end of file diff --git a/examples/GUIParsing/ParserVersion/src/main/java/CalcGUI.java b/examples/GUIParsing/ParserVersion/src/main/java/CalcGUI.java deleted file mode 100644 index 953ea1f..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/java/CalcGUI.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -import java.awt.*; - -public class CalcGUI extends Frame implements CalcInputParserConstants { - - /** - * A button object is created for each calculator button.
- * Since there is going to be only one calculator GUI, these objects can be static. - */ - static Button one = new Button("1"); - static Button two = new Button("2"); - static Button three = new Button("3"); - static Button four = new Button("4"); - static Button five = new Button("5"); - static Button six = new Button("6"); - static Button seven = new Button("7"); - static Button eight = new Button("8"); - static Button nine = new Button("9"); - static Button zero = new Button("0"); - static Button dot = new Button("."); - static Button equal = new Button("="); - static Button add = new Button("+"); - static Button sub = new Button("-"); - static Button mul = new Button("*"); - static Button div = new Button("/"); - static Button quit = new Button("QUIT"); - - /** The display window with its initial setting. */ - static Label display = new Label("0 "); - - /** - * Constructor that creates the full GUI.
- * This is called by the main program to create one calculator GUI. - */ - public CalcGUI() { - - super("Calculator"); - GridBagLayout gb = new GridBagLayout(); - setLayout(gb); - GridBagConstraints gbc = new GridBagConstraints(); - - display.setFont(new Font("TimesRoman", Font.BOLD, 18)); - display.setAlignment(Label.RIGHT); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.BOTH; - gbc.weightx = 1.0; - gbc.weighty = 0.0; - gb.setConstraints(display, gbc); - add(display); - - Panel buttonPanel = new Panel(); - buttonPanel.setFont(new Font("TimesRoman", Font.BOLD, 14)); - buttonPanel.setLayout(new GridLayout(4, 4)); - buttonPanel.add(one); - buttonPanel.add(two); - buttonPanel.add(three); - buttonPanel.add(four); - buttonPanel.add(five); - buttonPanel.add(six); - buttonPanel.add(seven); - buttonPanel.add(eight); - buttonPanel.add(nine); - buttonPanel.add(zero); - buttonPanel.add(dot); - buttonPanel.add(equal); - buttonPanel.add(add); - buttonPanel.add(sub); - buttonPanel.add(mul); - buttonPanel.add(div); - gbc.weighty = 1.0; - gb.setConstraints(buttonPanel, gbc); - add(buttonPanel); - - quit.setFont(new Font("TimesRoman", Font.BOLD, 14)); - gbc.gridheight = GridBagConstraints.REMAINDER; - gbc.weighty = 0.0; - gb.setConstraints(quit, gbc); - add(quit); - pack(); - show(); - } - - /** - * Note how handleEvent creates tokens and sends them to the parser through the producer-consumer. - */ - public boolean handleEvent(Event evt) { - Token t; - if (evt.id != Event.ACTION_EVENT) { - return false; - } - if (evt.target == one) { - t = new Token(); - t.kind = DIGIT; - t.image = "1"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == two) { - t = new Token(); - t.kind = DIGIT; - t.image = "2"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == three) { - t = new Token(); - t.kind = DIGIT; - t.image = "3"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == four) { - t = new Token(); - t.kind = DIGIT; - t.image = "4"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == five) { - t = new Token(); - t.kind = DIGIT; - t.image = "5"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == six) { - t = new Token(); - t.kind = DIGIT; - t.image = "6"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == seven) { - t = new Token(); - t.kind = DIGIT; - t.image = "7"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == eight) { - t = new Token(); - t.kind = DIGIT; - t.image = "8"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == nine) { - t = new Token(); - t.kind = DIGIT; - t.image = "9"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == zero) { - t = new Token(); - t.kind = DIGIT; - t.image = "0"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == dot) { - t = new Token(); - t.kind = DOT; - t.image = "."; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == equal) { - t = new Token(); - t.kind = EQ; - t.image = "="; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == add) { - t = new Token(); - t.kind = ADD; - t.image = "+"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == sub) { - t = new Token(); - t.kind = SUB; - t.image = "-"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == mul) { - t = new Token(); - t.kind = MUL; - t.image = "*"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == div) { - t = new Token(); - t.kind = DIV; - t.image = "/"; - ProducerConsumer.pc.addToken(t); - return true; - } - if (evt.target == quit) { - System.exit(0); - } - return false; - } - - public static void print(double value) { - display.setText(Double.toString(value) + " "); - } - - public static void print(String image) { - display.setText(image + " "); - } -} diff --git a/examples/GUIParsing/ParserVersion/src/main/java/CalcInputParserTreeConstants.java b/examples/GUIParsing/ParserVersion/src/main/java/CalcInputParserTreeConstants.java deleted file mode 100644 index fd2175d..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/java/CalcInputParserTreeConstants.java +++ /dev/null @@ -1,4 +0,0 @@ - -public interface CalcInputParserTreeConstants { - -} diff --git a/examples/GUIParsing/ParserVersion/src/main/java/Main.java b/examples/GUIParsing/ParserVersion/src/main/java/Main.java deleted file mode 100644 index a6b9c79..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/java/Main.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -public class Main { - - public static void main(String[] args) { - new CalcGUI(); - TokenManager tm = new TokenCollector(); - CalcInputParser cp = new CalcInputParser(tm); - while (true) { - try { - cp.Input(); - } catch (ParseException e) { - CalcGUI.print("ERROR (click 0)"); - } - } - } -} diff --git a/examples/GUIParsing/ParserVersion/src/main/java/ProducerConsumer.java b/examples/GUIParsing/ParserVersion/src/main/java/ProducerConsumer.java deleted file mode 100644 index 4f1fa74..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/java/ProducerConsumer.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -public class ProducerConsumer { - - /** A single producer-consumer instance that is used by others. */ - public static ProducerConsumer pc = new ProducerConsumer(); - - /** The data structure where the tokens are stored. */ - private java.util.Vector queue = new java.util.Vector(); - - /** The producer calls this method to add a new token whenever it is available. */ - public synchronized void addToken(Token token) { - queue.addElement(token); - notify(); - } - - /** - * The consumer calls this method to get the next token in the queue.
- * If the queue is empty, this method blocks until a token becomes available. - */ - public synchronized Token getToken() { - if (queue.isEmpty()) { - try { - wait(); - } catch (InterruptedException willNotHappen) { - throw new Error(); - } - } - Token retval = (Token) (queue.elementAt(0)); - queue.removeElementAt(0); - return retval; - } -} diff --git a/examples/GUIParsing/ParserVersion/src/main/java/TokenCollector.java b/examples/GUIParsing/ParserVersion/src/main/java/TokenCollector.java deleted file mode 100644 index 057fe35..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/java/TokenCollector.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -public class TokenCollector implements TokenManager { - - public Token getNextToken() { - return ProducerConsumer.pc.getToken(); - } -} diff --git a/examples/GUIParsing/ParserVersion/src/main/javacc/CalcInput.jj b/examples/GUIParsing/ParserVersion/src/main/javacc/CalcInput.jj deleted file mode 100644 index 67b6d51..0000000 --- a/examples/GUIParsing/ParserVersion/src/main/javacc/CalcInput.jj +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - USER_TOKEN_MANAGER = true; -} - -PARSER_BEGIN(CalcInputParser) - -public class CalcInputParser {} - -PARSER_END(CalcInputParser) - -void Input() : -{ - double larg = 0.0; - double rarg; -} -{ - ( - [ - larg = Number() - { - CalcGUI.print(larg); - } - ] - ( - < ADD > - rarg = Number() - { - larg = larg + rarg; - CalcGUI.print(larg); - } - | - < SUB > - rarg = Number() - { - larg = larg - rarg; - CalcGUI.print(larg); - } - | - < MUL > - rarg = Number() - { - larg = larg * rarg; - CalcGUI.print(larg); - } - | - < DIV > - rarg = Number() - { - larg = (rarg == 0) ? Float.POSITIVE_INFINITY : (larg / rarg); - CalcGUI.print(larg); - } - )* - < EQ : "=" > - )* -} - -double Number() : -{ - Token t; - String image = ""; - double value = 0.0; - double decimalPlace = 1.0; -} -{ - ( - t = < DIGIT > - { - image += t.image; - value = value * 10 + Integer.parseInt(t.image); - CalcGUI.print(image); - } - )+ - [ - < DOT > - { - image += "."; - CalcGUI.print(image); - } - ( - t = < DIGIT > - { - image += t.image; - decimalPlace *= 0.1; - value = value + Integer.parseInt(t.image) * decimalPlace; - CalcGUI.print(image); - } - )+ - ] - { - return value; - } -| - < DOT > - { - image = "0."; - CalcGUI.print(image); - } - ( - t = < DIGIT > - { - image += t.image; - decimalPlace *= 0.1; - value = value + Integer.parseInt(t.image) * decimalPlace; - CalcGUI.print(image); - } - )+ - { - return value; - } -} diff --git a/examples/GUIParsing/README.md b/examples/GUIParsing/README.md deleted file mode 100644 index f99bda5..0000000 --- a/examples/GUIParsing/README.md +++ /dev/null @@ -1,12 +0,0 @@ -In this directory are two examples that illustrate the use of JavaCC generated parsers to collect input from a GUI and process it appropriately. - -The example used is a simple calculator. - -There are two versions of this example: - -- A version that uses a JavaCC parser without the JavaCC token manager in directory ParserVersion. - -- A version that uses a JavaCC token manager without the JavaCC parser in directory TokenMgrVersion. -This example also illustrates the ability to build a state machine as a lexical specification. - -The README.md files in these directories provide more details. diff --git a/examples/GUIParsing/TokenMgrVersion/README.md b/examples/GUIParsing/TokenMgrVersion/README.md deleted file mode 100644 index 3cb5445..0000000 --- a/examples/GUIParsing/TokenMgrVersion/README.md +++ /dev/null @@ -1,38 +0,0 @@ -This version of the GUI parsing example defines the GUI interaction as a JavaCC lexical specification where the characters are read from the GUI and there is an finite automaton (FA) built out of lexical states that have moves on these characters. -In the grammar, the `USER_CHAR_STREAM option` has been set to `true` and the `BUILD_PARSER` option has been set to `false`. -The event handler method stuffs the characters into a buffer from which characters are returned to the lexical analyzer (by `readChar()`). -The whole system is invoked through`Main.java`. - -The point of this example is to illustrate: - -- A very detailed example of an FA simulation using lexical states where every character moves the FA. - -- How a lexical analyzer can be used without a standard (JavaCC generated) CharStream object. - -- How a lexical analyzer can be used without a parser. - -- The fact that input can come from entities that are not even streams (a GUI in this example). - -- That GUI interaction can be modeled as a regular expression specification. - -Build it in the usual manner with [pom.xml](pom.xml): - -- Maven: - -``` - mvn clean verify -``` - -Then run the GUI: - -- command line: - -``` - java -cp target/classes/ Main -``` - -Homework: - - Simplify the grammar so that (["0"-"9"])* is treated as a single - entity for moving the FA. - diff --git a/examples/GUIParsing/TokenMgrVersion/pom.xml b/examples/GUIParsing/TokenMgrVersion/pom.xml deleted file mode 100644 index 544d4a4..0000000 --- a/examples/GUIParsing/TokenMgrVersion/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java.examples - guiparsing - 1.1.0-SNAPSHOT - - - org.javacc.examples.java.guiparsing - TokenMgrVersion - jar - - JavaCC Java code generator / examples / GUIParsing / TokenMgrVersion - - - - \ No newline at end of file diff --git a/examples/GUIParsing/TokenMgrVersion/run.cmd b/examples/GUIParsing/TokenMgrVersion/run.cmd deleted file mode 100644 index ca7b6f3..0000000 --- a/examples/GUIParsing/TokenMgrVersion/run.cmd +++ /dev/null @@ -1,3 +0,0 @@ -Rem script to run the calculator -java -cp target/classes Main -Pause \ No newline at end of file diff --git a/examples/GUIParsing/TokenMgrVersion/src/main/java/CalcGUI.java b/examples/GUIParsing/TokenMgrVersion/src/main/java/CalcGUI.java deleted file mode 100644 index 4b2eb98..0000000 --- a/examples/GUIParsing/TokenMgrVersion/src/main/java/CalcGUI.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -import java.awt.*; - -public class CalcGUI extends Frame implements CalcInputParserConstants { - - /* - * A button object is created for each calculator button. Since there is going to be only one - * calculator GUI, these objects can be static. - */ - - static Button one = new Button("1"); - static Button two = new Button("2"); - static Button three = new Button("3"); - static Button four = new Button("4"); - static Button five = new Button("5"); - static Button six = new Button("6"); - static Button seven = new Button("7"); - static Button eight = new Button("8"); - static Button nine = new Button("9"); - static Button zero = new Button("0"); - static Button dot = new Button("."); - static Button equal = new Button("="); - static Button add = new Button("+"); - static Button sub = new Button("-"); - static Button mul = new Button("*"); - static Button div = new Button("/"); - static Button quit = new Button("QUIT"); - - /** The display window with its initial setting. */ - static Label display = new Label("0 "); - - /** The class that collects the characters produced by the GUI */ - static final CharCollector collector = new CharCollector(); - - static final CharStream getCollector() { - return collector; - } - - /** string that holds what the calculator displays */ - static String label = "0"; - - /** flag to indicate if this is the first digit. */ - static boolean firstDigit = true; - - /** Indicates an error has occured */ - static boolean error = false; - - /** - * Constructor that creates the full GUI.
- * This is called by the main program to create one calculator GUI. - */ - public CalcGUI() { - - super("Calculator"); - - GridBagLayout gb = new GridBagLayout(); - setLayout(gb); - GridBagConstraints gbc = new GridBagConstraints(); - - display.setFont(new Font("TimesRoman", Font.BOLD, 18)); - display.setAlignment(Label.RIGHT); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.BOTH; - gbc.weightx = 1.0; - gbc.weighty = 0.0; - gb.setConstraints(display, gbc); - add(display); - - Panel buttonPanel = new Panel(); - buttonPanel.setFont(new Font("TimesRoman", Font.BOLD, 14)); - buttonPanel.setLayout(new GridLayout(4, 4)); - buttonPanel.add(one); - buttonPanel.add(two); - buttonPanel.add(three); - buttonPanel.add(four); - buttonPanel.add(five); - buttonPanel.add(six); - buttonPanel.add(seven); - buttonPanel.add(eight); - buttonPanel.add(nine); - buttonPanel.add(zero); - buttonPanel.add(dot); - buttonPanel.add(equal); - buttonPanel.add(add); - buttonPanel.add(sub); - buttonPanel.add(mul); - buttonPanel.add(div); - gbc.weighty = 1.0; - gb.setConstraints(buttonPanel, gbc); - add(buttonPanel); - - quit.setFont(new Font("TimesRoman", Font.BOLD, 14)); - gbc.gridheight = GridBagConstraints.REMAINDER; - gbc.weighty = 0.0; - gb.setConstraints(quit, gbc); - add(quit); - pack(); - show(); - } - - /** Here we just return the character that is input. */ - public boolean handleEvent(Event evt) { - char c = 0; - - if (evt.id != Event.ACTION_EVENT) { - return false; - } - - if (evt.target == quit) { - System.exit(0); - } - - if (error) { - if (evt.target == zero) { - error = false; - print("0"); - firstDigit = true; - return true; - } - - return false; - } - - if (evt.target == equal) { - c = '='; - firstDigit = true; - } else if (evt.target == add) { - c = '+'; - label = "0"; - firstDigit = true; - } else if (evt.target == sub) { - c = '-'; - label = "0"; - firstDigit = true; - } else if (evt.target == mul) { - c = '*'; - label = "0"; - firstDigit = true; - } else if (evt.target == div) { - c = '/'; - label = "0"; - firstDigit = true; - } else { - if (firstDigit) label = ""; - firstDigit = false; - - if (evt.target == one) { - c = '1'; - label += c; - } else if (evt.target == two) { - c = '2'; - label += c; - } else if (evt.target == three) { - c = '3'; - label += c; - } else if (evt.target == four) { - c = '4'; - label += c; - } else if (evt.target == five) { - c = '5'; - label += c; - } else if (evt.target == six) { - c = '6'; - label += c; - } else if (evt.target == seven) { - c = '7'; - label += c; - } else if (evt.target == eight) { - c = '8'; - label += c; - } else if (evt.target == nine) { - c = '9'; - label += c; - } else if (evt.target == zero) { - c = '0'; - label += c; - } else if (evt.target == dot) { - c = '.'; - label += "."; - } else return false; - } - - print(label); - collector.put(c); - return true; - } - - public static void print(double value) { - display.setText(label = Double.toString(value)); - } - - public static void print(String image) { - display.setText(label = image); - } - - public static void Error(String image) { - print(image); - Toolkit.getDefaultToolkit().beep(); - collector.Clear(); - label = "0"; - error = true; - } -} diff --git a/examples/GUIParsing/TokenMgrVersion/src/main/java/CharCollector.java b/examples/GUIParsing/TokenMgrVersion/src/main/java/CharCollector.java deleted file mode 100644 index a544f89..0000000 --- a/examples/GUIParsing/TokenMgrVersion/src/main/java/CharCollector.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * A CharStream implementation for an event driven stream that produces / consumes one character at - * a time.
- * Adapted from the SimpleCharStream, removing constructors and reinitialize methods, removing - * internal lines & columns updates (which is different from lines & columns tracking), filling the - * buffer directly. - */ -public class CharCollector implements CharStream { - - int bufsize; - int available; - int tokenBegin; - public int bufpos = -1; - - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int inBuf = 0; - - protected boolean trackLineColumn = true; - protected int tabSize = 1; - - /** Puts a character into the buffer. Called by the GUI. */ - public final synchronized void put(char c) { - buffer[maxNextCharInd++] = c; - notify(); - } - - public void Clear() { - bufpos = -1; - maxNextCharInd = 0; - inBuf = 0; - } - - public char BeginToken() throws java.io.IOException { - tokenBegin = -1; - char c = readChar(); - tokenBegin = bufpos; - - return c; - } - - // same as in SimpleCharStream but shorter (and with chars forced in the ASCII range) - public final synchronized char readChar() throws java.io.IOException { - if (inBuf > 0) { - --inBuf; - return (char) ((char) 0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); - } - - if (++bufpos >= maxNextCharInd) { - FillBuff(); - } - return buffer[bufpos]; - } - - private final void FillBuff() { - if (maxNextCharInd == available) { - if (available == bufsize) { - if (tokenBegin > 2048) { - bufpos = maxNextCharInd = 0; - available = tokenBegin; - } else if (tokenBegin < 0) { - bufpos = maxNextCharInd = 0; - } else { - ExpandBuff(false); - } - } else if (available > tokenBegin) { - available = bufsize; - } else if ((tokenBegin - available) < 2048) { - ExpandBuff(true); - } else { - available = tokenBegin; - } - } - try { - wait(); - } catch (InterruptedException willNotHappen) { - throw new Error(); - } - } - - private final void ExpandBuff(boolean wrapAround) { - char[] newbuffer = new char[bufsize + 2048]; - - try { - if (wrapAround) { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); - buffer = newbuffer; - maxNextCharInd = (bufpos += (bufsize - tokenBegin)); - } else { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - buffer = newbuffer; - maxNextCharInd = (bufpos -= tokenBegin); - } - } catch (Throwable t) { - System.out.println("Error : " + t.getClass().getName()); - throw new Error(); - } - - bufsize += 2048; - available = bufsize; - tokenBegin = 0; - } - - public final void backup(int amount) { - inBuf += amount; - if ((bufpos -= amount) < 0) { - bufpos += bufsize; - } - } - - public void Done() { - buffer = null; - } - - public final String GetImage() { - if (bufpos >= tokenBegin) { - return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); - } else - return new String(buffer, tokenBegin, bufsize - tokenBegin) - + new String(buffer, 0, bufpos + 1); - } - - public final char[] GetSuffix(int len) { - char[] ret = new char[len]; - if (bufpos + 1 >= len) { - System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); - } else { - System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); - System.arraycopy(buffer, 0, ret, len - bufpos, bufpos + 1); - } - return ret; - } - - public CharCollector() { - available = bufsize = 4096; - buffer = new char[4096]; - } - - @Deprecated - public final int getLine() { - return 0; - } - - @Deprecated - public final int getColumn() { - return 0; - } - - public final int getBeginLine() { - return 0; - } - - public final int getBeginColumn() { - return 0; - } - - public final int getEndLine() { - return 0; - } - - public final int getEndColumn() { - return 0; - } - - public boolean getTrackLineColumn() { - return trackLineColumn; - } - - public void setTrackLineColumn(boolean tlc) { - trackLineColumn = tlc; - } - - public int getTabSize() { - return tabSize; - } - - public void setTabSize(int i) { - tabSize = i; - } -} diff --git a/examples/GUIParsing/TokenMgrVersion/src/main/java/Main.java b/examples/GUIParsing/TokenMgrVersion/src/main/java/Main.java deleted file mode 100644 index 21e322d..0000000 --- a/examples/GUIParsing/TokenMgrVersion/src/main/java/Main.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -public class Main { - - public static void main(String[] args) { - CalcGUI gui = new CalcGUI(); - MyLexer lexer = new MyLexer(gui); - while (true) { - try { - lexer.getNextToken(); - } catch (TokenMgrError e) { - } - } - } -} diff --git a/examples/GUIParsing/TokenMgrVersion/src/main/java/MyLexer.java b/examples/GUIParsing/TokenMgrVersion/src/main/java/MyLexer.java deleted file mode 100644 index 3e9f433..0000000 --- a/examples/GUIParsing/TokenMgrVersion/src/main/java/MyLexer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * A subclass of CalcInputTokenManager so that we can do better error reporting via the GUI object. - */ -class MyLexer extends CalcInputParserTokenManager { - - public MyLexer(CalcGUI guiObj) { - super(guiObj.getCollector(), OPERAND); - gui = guiObj; - } - - /** - * We redefined the lexical error reporting function so that it beeps and displays a message - * through the GUI. - */ - protected void LexicalError() { - CalcGUI.Error("ERROR (click 0)"); - ReInit(gui.getCollector(), OPERAND); - result = 0.0; - } -} diff --git a/examples/GUIParsing/TokenMgrVersion/src/main/javacc/CalcInput.jj b/examples/GUIParsing/TokenMgrVersion/src/main/javacc/CalcInput.jj deleted file mode 100644 index 00ce2e0..0000000 --- a/examples/GUIParsing/TokenMgrVersion/src/main/javacc/CalcInput.jj +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - BUILD_PARSER = false; - USER_CHAR_STREAM = true; -// DEBUG_TOKEN_MANAGER = true; // (JavaCC - default false) -} - -PARSER_BEGIN(CalcInputParser) - -public class CalcInputParser {} - -PARSER_END(CalcInputParser) - -/** - * This example shows an elaborate example to construct a Finite Automaton, - * where for every character there is a move. - */ -TOKEN_MGR_DECLS: -{ - /** A pointer to the GUI object. */ - static CalcGUI gui; - - /** Holds the result of the expression evaluation so far. */ - static double result = 0.0; - - /** Flag to indicate the very first operand so that the correct result is displayed in this case. */ - static boolean firstOperand = true; - - /** Shows the result. */ - private static void ShowResult() - { - if (firstOperand) - { - String s = input_stream.GetImage(); -// System.err.println("first operand; s = <" + s + ">"); - if (s.length() > 0) - { - if (s.length() > 1) - { - // remove the operator character - s = s.substring(0, s.length() - 1); - } - result = Double.valueOf(s).doubleValue(); - } - else - { - result = 0.0; - } - firstOperand = false; -// } el m.err.println("not first operand"); - } - gui.print(result); - } -} - -/** - * The first operand - */ - MORE : -{ - < ["0"-"9"] > -| - "." : REQUIRED_DIGIT -} - -/** - * This state is entered when we need to get at least one digit (after a .) - */ - MORE : -{ - < ["0"-"9"] > : OPTIONAL_DIGIT -} - -/** - * FA for (["0"-"9"])*. - */ - MORE : -{ - < ["0"-"9"] > -} - -/** - * You can get an operator at any time (in any lexical state), except when a digit is required (after a .). - * Then just go to a state where the next operand is scanned (for that particular operator). - */ - SKIP : -{ - < PLUS : "+" > { ShowResult(); } : SEEN_PLUS -| - < MINUS : "-" > { ShowResult(); } : SEEN_MINUS -| - < STAR : "*" > { ShowResult(); } : SEEN_STAR -| - < SLASH : "/" > { ShowResult(); } : SEEN_SLASH -} - -/** - * If you get a = in any state, just display the current result. - */ - SKIP : -{ - < EQ : "=" > { ShowResult(); } : OP_OR_OPERAND -} - -/** - * Here you can either give an operand (to start a new expression) - * or give an operator that works on the current result. - */ - SKIP : -{ - "=" -} - - MORE : -{ - < ["0"-"9"] > { firstOperand = true; } : OPERAND -| - "." { firstOperand = true; } : REQUIRED_DIGIT -} - - MORE : -{ - < ["0"-"9"] > : ADD_RIGHT_OPERAND -| - "." : ADD_REQUIRED_DIGIT -} - - MORE : -{ - < ["0"-"9"] > : DO_ADD -} - - SKIP : -{ - "" - { result += Double.valueOf(input_stream.GetImage()).doubleValue(); } : OP_LOOP -} - - MORE : -{ - < ["0"-"9"] > : SUB_RIGHT_OPERAND -| - "." : SUB_REQUIRED_DIGIT -} - - MORE : -{ - < ["0"-"9"] > : DO_SUB -} - - SKIP : -{ - "" - { result -= Double.valueOf(input_stream.GetImage()).doubleValue(); } : OP_LOOP -} - - MORE : -{ - < ["0"-"9"] > : MUL_RIGHT_OPERAND -| - "." : MUL_REQUIRED_DIGIT -} - - MORE : -{ - < ["0"-"9"] > : DO_MUL -} - - SKIP : -{ - "" - { result *= Double.valueOf(input_stream.GetImage()).doubleValue(); } : OP_LOOP -} - - MORE : -{ - < ["0"-"9"] > : DIV_RIGHT_OPERAND -| - "." : DIV_REQUIRED_DIGIT -} - - MORE : -{ - < ["0"-"9"] > : DO_DIV -} - - SKIP : -{ - "" - { result /= Double.valueOf(input_stream.GetImage()).doubleValue(); } : OP_LOOP -} diff --git a/examples/GUIParsing/pom.xml b/examples/GUIParsing/pom.xml deleted file mode 100644 index 8356dee..0000000 --- a/examples/GUIParsing/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - guiparsing - pom - - JavaCC Java code generator / examples / GUIParsing - - - ParserVersion - TokenMgrVersion - - - \ No newline at end of file diff --git a/examples/Gwt/README b/examples/Gwt/README deleted file mode 100644 index da73714..0000000 --- a/examples/Gwt/README +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This directory contains two examples using the modern template (compatible with GWT). \ No newline at end of file diff --git a/examples/Gwt/checkstyle-suppress.xml b/examples/Gwt/checkstyle-suppress.xml deleted file mode 100644 index 67fe8cb..0000000 --- a/examples/Gwt/checkstyle-suppress.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/Gwt/pom.xml b/examples/Gwt/pom.xml deleted file mode 100644 index 8ec94bc..0000000 --- a/examples/Gwt/pom.xml +++ /dev/null @@ -1,193 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - gwt - jar - - JavaCC Java code generator / examples / Gwt - - - - - - - org.apache.maven.plugins - maven-clean-plugin - - - clear-res-test - process-test-resources - - clean - - - true - - - files - - *.out - *.err - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - exec-test-1 - test - - java - - - GwtSimpleParser - - ${project.basedir}/simple/out - ${project.basedir}/simple/err - - - - - unicode - test - - java - - - GwtUnicodeParser - - ${project.basedir}/unicode/out - ${project.basedir}/unicode/err - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - compare-simple - test - - run - - - - - - - - - - - - - - - - compare-unicode - test - - run - - - - - - - - - - - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.6.0 - - google_checks.xml - true - true - UTF-8 - target/generated-sources/java - checkstyle.suppressions.file - checkstyle-suppress.xml - error - - - - validate - generate-sources - - check - - - - - - - - \ No newline at end of file diff --git a/examples/Gwt/simple/err b/examples/Gwt/simple/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Gwt/simple/out b/examples/Gwt/simple/out deleted file mode 100644 index ce01362..0000000 --- a/examples/Gwt/simple/out +++ /dev/null @@ -1 +0,0 @@ -hello diff --git a/examples/Gwt/simple/ref b/examples/Gwt/simple/ref deleted file mode 100644 index b6fc4c6..0000000 --- a/examples/Gwt/simple/ref +++ /dev/null @@ -1 +0,0 @@ -hello \ No newline at end of file diff --git a/examples/Gwt/src/main/javacc/GwtSimpleParser.jj b/examples/Gwt/src/main/javacc/GwtSimpleParser.jj deleted file mode 100644 index 09658fc..0000000 --- a/examples/Gwt/src/main/javacc/GwtSimpleParser.jj +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - LOOKAHEAD = 1; - CHOICE_AMBIGUITY_CHECK = 2; - OTHER_AMBIGUITY_CHECK = 1; - STATIC = true; - DEBUG_PARSER = false; - DEBUG_LOOKAHEAD = false; - DEBUG_TOKEN_MANAGER = false; - ERROR_REPORTING = true; - JAVA_UNICODE_ESCAPE = false; - UNICODE_INPUT = false; - IGNORE_CASE = false; - USER_TOKEN_MANAGER = false; - USER_CHAR_STREAM = false; - BUILD_PARSER = true; - BUILD_TOKEN_MANAGER = true; - SANITY_CHECK = true; - FORCE_LA_CHECK = false; - JAVA_TEMPLATE_TYPE = "modern"; -} - -PARSER_BEGIN(GwtSimpleParser) - -import java.io.IOException; -import java.io.PrintStream; - -/** Simple brace matcher. */ -public class GwtSimpleParser { - - /** Main entry point. */ - public static void main(String[] args) throws ParseException, IOException { - PrintStream output = System.out; - PrintStream error = System.err; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 2) { - prevOutput = output; - output = new PrintStream(args[0]); - prevError = error; - error = new PrintStream(args[1]); - System.setOut(output); - System.setErr(error); - } - try { - GwtSimpleParser parser = new GwtSimpleParser(new StringProvider("A")); - parser.Input(); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevOutput != null) { - System.setOut(prevOutput); - } - if (prevError != null) { - System.setErr(prevError); - } - } - } - -} - -PARSER_END(GwtSimpleParser) - -/** Root production. */ -void Input() : -{} -{ - - "A" { - System.out.println("hello"); - } -} \ No newline at end of file diff --git a/examples/Gwt/src/main/javacc/GwtUnicodeParser.jj b/examples/Gwt/src/main/javacc/GwtUnicodeParser.jj deleted file mode 100644 index 43164a3..0000000 --- a/examples/Gwt/src/main/javacc/GwtUnicodeParser.jj +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - LOOKAHEAD = 1; - CHOICE_AMBIGUITY_CHECK = 2; - OTHER_AMBIGUITY_CHECK = 1; - STATIC = true; - DEBUG_PARSER = false; - DEBUG_LOOKAHEAD = false; - DEBUG_TOKEN_MANAGER = false; - ERROR_REPORTING = true; - JAVA_UNICODE_ESCAPE = true; - UNICODE_INPUT = false; - IGNORE_CASE = false; - USER_TOKEN_MANAGER = false; - USER_CHAR_STREAM = false; - BUILD_PARSER = true; - BUILD_TOKEN_MANAGER = true; - SANITY_CHECK = true; - FORCE_LA_CHECK = false; - JAVA_TEMPLATE_TYPE = "modern"; -} - -PARSER_BEGIN(GwtUnicodeParser) - -import java.io.IOException; -import java.io.PrintStream; - -/** Simple brace matcher. */ -public class GwtUnicodeParser { - - /** Main entry point. */ - public static void main(String[] args) throws ParseException, IOException { - PrintStream output = System.out; - PrintStream error = System.err; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 2) { - prevOutput = output; - output = new PrintStream(args[0]); - prevError = error; - error = new PrintStream(args[1]); - System.setOut(output); - System.setErr(error); - } - try { - GwtUnicodeParser parser = new GwtUnicodeParser(new StringProvider("A")); - parser.Input(); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevOutput != null) { - System.setOut(prevOutput); - } - if (prevError != null) { - System.setErr(prevError); - } - } - } - -} - -PARSER_END(GwtUnicodeParser) - -/** Root production. */ -void Input() : -{} -{ - - "A" { - System.out.println("hello"); - } -} \ No newline at end of file diff --git a/examples/Gwt/unicode/err b/examples/Gwt/unicode/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Gwt/unicode/out b/examples/Gwt/unicode/out deleted file mode 100644 index ce01362..0000000 --- a/examples/Gwt/unicode/out +++ /dev/null @@ -1 +0,0 @@ -hello diff --git a/examples/Gwt/unicode/ref b/examples/Gwt/unicode/ref deleted file mode 100644 index b6fc4c6..0000000 --- a/examples/Gwt/unicode/ref +++ /dev/null @@ -1 +0,0 @@ -hello \ No newline at end of file diff --git a/examples/Interpreter/README b/examples/Interpreter/README deleted file mode 100644 index 09f7e08..0000000 --- a/examples/Interpreter/README +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This is an interpreter for SPL (Stupid Programming Language). It builds -jjtree's for a given SPL program and interprets it. It shows how you can -implement simple loop and conditional constructs. - -Note how easy it is to annotate a grammar file to build useful tree nodes -and then extend these nodes for purposes of interpreting, etc. - -This example will be improved as JJTree evolves. - -To run it : - - jjtree SPL.jjt - javacc SPL.jj - javac *.java - java SPL fact.spl - java SPL sqrt.spl - java SPL odd.spl diff --git a/examples/Interpreter/files/fact/ast-fact.exp_err b/examples/Interpreter/files/fact/ast-fact.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/fact/ast-fact.exp_out b/examples/Interpreter/files/fact/ast-fact.exp_out deleted file mode 100644 index 6bca0bf..0000000 --- a/examples/Interpreter/files/fact/ast-fact.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int n -Executing: int fact -Executing: read n -Enter a value for 'n' (int) : -Read this value for 'n' (int) : 4 -Executing: fact = 1 ; -Executing: while ( n > 1 ) { fact = fact * n ; n = n - 1 ; } -Executing: write fact -Value of fact : 24 diff --git a/examples/Interpreter/files/fact/fact.in b/examples/Interpreter/files/fact/fact.in deleted file mode 100644 index bf0d87a..0000000 --- a/examples/Interpreter/files/fact/fact.in +++ /dev/null @@ -1 +0,0 @@ -4 \ No newline at end of file diff --git a/examples/Interpreter/files/fact/fact.spl b/examples/Interpreter/files/fact/fact.spl deleted file mode 100644 index 38417a8..0000000 --- a/examples/Interpreter/files/fact/fact.spl +++ /dev/null @@ -1,14 +0,0 @@ -int n; -int fact; - -read n; - -fact = 1; - -while (n > 1) -{ - fact = fact * n; - n = n - 1; -} - -write fact; diff --git a/examples/Interpreter/files/fact/vst-fact.exp_err b/examples/Interpreter/files/fact/vst-fact.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/fact/vst-fact.exp_out b/examples/Interpreter/files/fact/vst-fact.exp_out deleted file mode 100644 index 6bca0bf..0000000 --- a/examples/Interpreter/files/fact/vst-fact.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int n -Executing: int fact -Executing: read n -Enter a value for 'n' (int) : -Read this value for 'n' (int) : 4 -Executing: fact = 1 ; -Executing: while ( n > 1 ) { fact = fact * n ; n = n - 1 ; } -Executing: write fact -Value of fact : 24 diff --git a/examples/Interpreter/files/odd/ast-odd.exp_err b/examples/Interpreter/files/odd/ast-odd.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/odd/ast-odd.exp_out b/examples/Interpreter/files/odd/ast-odd.exp_out deleted file mode 100644 index c38779c..0000000 --- a/examples/Interpreter/files/odd/ast-odd.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int num -Executing: boolean odd -Executing: num = 10 ; -Executing: read num -Enter a value for 'num' (int) : -Read this value for 'num' (int) : 3 -Executing: if ( num % 2 != 0 ) odd = true ; else odd = false ; -Executing: write odd -Value of odd : true diff --git a/examples/Interpreter/files/odd/odd.in b/examples/Interpreter/files/odd/odd.in deleted file mode 100644 index e440e5c..0000000 --- a/examples/Interpreter/files/odd/odd.in +++ /dev/null @@ -1 +0,0 @@ -3 \ No newline at end of file diff --git a/examples/Interpreter/files/odd/odd.spl b/examples/Interpreter/files/odd/odd.spl deleted file mode 100644 index 5f81dd7..0000000 --- a/examples/Interpreter/files/odd/odd.spl +++ /dev/null @@ -1,13 +0,0 @@ -int num; -boolean odd; - -num = 10; - -read num; - -if (num % 2 != 0) - odd = true; -else - odd = false; - -write odd; diff --git a/examples/Interpreter/files/odd/vst-odd.exp_err b/examples/Interpreter/files/odd/vst-odd.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/odd/vst-odd.exp_out b/examples/Interpreter/files/odd/vst-odd.exp_out deleted file mode 100644 index c38779c..0000000 --- a/examples/Interpreter/files/odd/vst-odd.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int num -Executing: boolean odd -Executing: num = 10 ; -Executing: read num -Enter a value for 'num' (int) : -Read this value for 'num' (int) : 3 -Executing: if ( num % 2 != 0 ) odd = true ; else odd = false ; -Executing: write odd -Value of odd : true diff --git a/examples/Interpreter/files/sqrt/ast-sqrt.exp_err b/examples/Interpreter/files/sqrt/ast-sqrt.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/sqrt/ast-sqrt.exp_out b/examples/Interpreter/files/sqrt/ast-sqrt.exp_out deleted file mode 100644 index 3a54659..0000000 --- a/examples/Interpreter/files/sqrt/ast-sqrt.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int val -Executing: read val -Enter a value for 'val' (int) : -Read this value for 'val' (int) : 9 -Executing: int sqrt -Executing: sqrt = 1 ; -Executing: while ( sqrt * sqrt <= val && ( ( sqrt + 1 ) * ( sqrt + 1 ) ) <= val ) sqrt = sqrt + 1 ; -Executing: write sqrt -Value of sqrt : 3 diff --git a/examples/Interpreter/files/sqrt/sqrt.in b/examples/Interpreter/files/sqrt/sqrt.in deleted file mode 100644 index f11c82a..0000000 --- a/examples/Interpreter/files/sqrt/sqrt.in +++ /dev/null @@ -1 +0,0 @@ -9 \ No newline at end of file diff --git a/examples/Interpreter/files/sqrt/sqrt.spl b/examples/Interpreter/files/sqrt/sqrt.spl deleted file mode 100644 index c82568a..0000000 --- a/examples/Interpreter/files/sqrt/sqrt.spl +++ /dev/null @@ -1,12 +0,0 @@ - -int val; - -read val; -int sqrt; - -sqrt = 1; - -while (sqrt * sqrt <= val && ((sqrt + 1) * (sqrt + 1)) <= val) - sqrt = sqrt + 1; - -write sqrt diff --git a/examples/Interpreter/files/sqrt/vst-sqrt.exp_err b/examples/Interpreter/files/sqrt/vst-sqrt.exp_err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Interpreter/files/sqrt/vst-sqrt.exp_out b/examples/Interpreter/files/sqrt/vst-sqrt.exp_out deleted file mode 100644 index 3a54659..0000000 --- a/examples/Interpreter/files/sqrt/vst-sqrt.exp_out +++ /dev/null @@ -1,9 +0,0 @@ -Executing: int val -Executing: read val -Enter a value for 'val' (int) : -Read this value for 'val' (int) : 9 -Executing: int sqrt -Executing: sqrt = 1 ; -Executing: while ( sqrt * sqrt <= val && ( ( sqrt + 1 ) * ( sqrt + 1 ) ) <= val ) sqrt = sqrt + 1 ; -Executing: write sqrt -Value of sqrt : 3 diff --git a/examples/Interpreter/pom.xml b/examples/Interpreter/pom.xml deleted file mode 100644 index c0eb391..0000000 --- a/examples/Interpreter/pom.xml +++ /dev/null @@ -1,324 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - Interpreter - jar - - JavaCC Java code generator / examples / Interpreter - - - - - - - org.apache.maven.plugins - maven-clean-plugin - - - clear-res-test - process-test-resources - - clean - - - true - - - files - - **/*.out - **/*.err - - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - ast.fact - test - - java - - - ast.SPLMain - - ${project.basedir}/files/fact/fact.spl - ${project.basedir}/files/fact/fact.in - ${project.basedir}/files/fact/ast-fact.out - ${project.basedir}/files/fact/ast-fact.err - - - - - ast.odd - test - - java - - - ast.SPLMain - - ${project.basedir}/files/odd/odd.spl - ${project.basedir}/files/odd/odd.in - ${project.basedir}/files/odd/ast-odd.out - ${project.basedir}/files/odd/ast-odd.err - - - - - ast.sqrt - test - - java - - - ast.SPLMain - - ${project.basedir}/files/sqrt/sqrt.spl - ${project.basedir}/files/sqrt/sqrt.in - ${project.basedir}/files/sqrt/ast-sqrt.out - ${project.basedir}/files/sqrt/ast-sqrt.err - - - - - - vst.fact - test - - java - - - vst.SPLMain - - ${project.basedir}/files/fact/fact.spl - ${project.basedir}/files/fact/fact.in - ${project.basedir}/files/fact/vst-fact.out - ${project.basedir}/files/fact/vst-fact.err - - - - - vst.odd - test - - java - - - vst.SPLMain - - ${project.basedir}/files/odd/odd.spl - ${project.basedir}/files/odd/odd.in - ${project.basedir}/files/odd/vst-odd.out - ${project.basedir}/files/odd/vst-odd.err - - - - - vst.sqrt - test - - java - - - vst.SPLMain - - ${project.basedir}/files/sqrt/sqrt.spl - ${project.basedir}/files/sqrt/sqrt.in - ${project.basedir}/files/sqrt/vst-sqrt.out - ${project.basedir}/files/sqrt/vst-sqrt.err - - - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - compare-ast.fact - test - - run - - - - - - - - - - - - - - - - - - compare-ast.odd - test - - run - - - - - - - - - - - - - - - - - - compare-ast.sqrt - test - - run - - - - - - - - - - - - - - - - - - - compare-vst.fact - test - - run - - - - - - - - - - - - - - - - - - compare-vst.odd - test - - run - - - - - - - - - - - - - - - - - - compare-vst.sqrt - test - - run - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/Interpreter/src/main/java/ast/MyNode.java b/examples/Interpreter/src/main/java/ast/MyNode.java deleted file mode 100644 index bbb07c9..0000000 --- a/examples/Interpreter/src/main/java/ast/MyNode.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Writer; -import java.util.Hashtable; - -/** Specialised node. */ -public abstract class MyNode { - - /** Symbol table: key = name, val = type */ - protected static Hashtable symtab = new Hashtable<>(); - - /** "Stack" for calculations. */ - protected static Object[] stack = new Object[1024]; - - /** Top of the "stack". */ - protected static int top = -1; - - /** - * @throws UnsupportedOperationException if called - */ - public void interpret() { - // It better not come here. (well, we did!) - throw new UnsupportedOperationException("UOE in " + this.getClass().getSimpleName()); - } - - protected static Writer out = new PrintWriter(System.out); - protected static Reader in = new InputStreamReader(System.in); - - /** - * @param in the input to set - */ - public static void setIn(Reader in) { - MyNode.in = in; - } - - /** - * @param out the output to set - */ - public static void setOut(Writer out) { - MyNode.out = out; - } -} diff --git a/examples/Interpreter/src/main/java/ast/SPLMain.java b/examples/Interpreter/src/main/java/ast/SPLMain.java deleted file mode 100644 index 32443c3..0000000 --- a/examples/Interpreter/src/main/java/ast/SPLMain.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -/** Simple Programming Language parser. */ -public class SPLMain { - - /** Main entry point. */ - public static void main(String args[]) { - InputStream spl = null; - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - - try { - SPLParser parser; - switch (args.length) { - case 1: - output.println( - "Simple Programming Language Interpreter (AST): Reading from file " - + args[0] - + " . . ."); - try { - parser = new SPLParser(new FileInputStream(args[0])); - } catch (FileNotFoundException e) { - error.println( - "Simple Programming Language Interpreter (AST): File " - + args[0] - + " not found."); - return; - } - break; - case 4: - spl = new FileInputStream(args[0]); - prevInput = input; - input = new FileInputStream(args[1]); - System.setIn(input); - prevOutput = output; - output = new PrintStream(args[2]); - System.setOut(output); - prevError = error; - error = new PrintStream(args[3]); - System.setErr(error); - parser = new SPLParser(spl); - break; - default: - output.println("Simple Programming Language Interpreter (AST): Usage :"); - output.println(" java SPLMain spl [in out err]"); - return; - } - parser.CompilationUnit(); - parser.jjtree.rootNode().interpret(); - } catch (ParseException e) { - error.println( - "Simple Programming Language Interpreter (AST): Encountered errors during parse."); - e.printStackTrace(); - } catch (Exception e1) { - error.println( - "Simple Programming Language Interpreter (AST): Encountered errors during interpretation/tree building."); - e1.printStackTrace(); - } finally { - try { - input.close(); - output.close(); - error.close(); - } catch (IOException e) { - } - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} diff --git a/examples/Interpreter/src/main/java/ast/STAddNode.java b/examples/Interpreter/src/main/java/ast/STAddNode.java deleted file mode 100644 index cccca26..0000000 --- a/examples/Interpreter/src/main/java/ast/STAddNode.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -import ast.Node; - -public class STAddNode extends Node { - - public STAddNode(int id) { - super(id); - } - - public STAddNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // MultiplicativeExpression() - jjtGetChild(0).interpret(); - - // MultiplicativeExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() + ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STAndNode.java b/examples/Interpreter/src/main/java/ast/STAndNode.java deleted file mode 100644 index ac8ec65..0000000 --- a/examples/Interpreter/src/main/java/ast/STAndNode.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STAndNode extends Node { - - public STAndNode(int id) { - super(id); - } - - public STAndNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // InclusiveOrExpression() - jjtGetChild(0).interpret(); - - if (!((Boolean) stack[top]).booleanValue()) { - stack[top] = new Boolean(false); - return; - } - - // InclusiveOrExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() && ((Boolean) stack[top + 1]).booleanValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STAssignment.java b/examples/Interpreter/src/main/java/ast/STAssignment.java deleted file mode 100644 index 9c10e62..0000000 --- a/examples/Interpreter/src/main/java/ast/STAssignment.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STAssignment extends Node { - - public STAssignment(int id) { - super(id); - } - - public STAssignment(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // Expression() - jjtGetChild(1).interpret(); - - // PrimaryExpression() - // note that here we do not interpret the child! - String name = ((STId) jjtGetChild(0)).name; - symtab.put(name, stack[top]); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STBitwiseAndNode.java b/examples/Interpreter/src/main/java/ast/STBitwiseAndNode.java deleted file mode 100644 index 08c7e0b..0000000 --- a/examples/Interpreter/src/main/java/ast/STBitwiseAndNode.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STBitwiseAndNode extends Node { - - public STBitwiseAndNode(int id) { - super(id); - } - - public STBitwiseAndNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // EqualityExpression() - jjtGetChild(0).interpret(); - - // EqualityExpression() - jjtGetChild(1).interpret(); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() & ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() & ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STBitwiseComplNode.java b/examples/Interpreter/src/main/java/ast/STBitwiseComplNode.java deleted file mode 100644 index e32f391..0000000 --- a/examples/Interpreter/src/main/java/ast/STBitwiseComplNode.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STBitwiseComplNode extends Node { - - public STBitwiseComplNode(int id) { - super(id); - } - - public STBitwiseComplNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // UnaryExpression() - jjtGetChild(0).interpret(); - - stack[top] = new Integer(~((Integer) stack[top]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STBitwiseOrNode.java b/examples/Interpreter/src/main/java/ast/STBitwiseOrNode.java deleted file mode 100644 index 489d5a5..0000000 --- a/examples/Interpreter/src/main/java/ast/STBitwiseOrNode.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STBitwiseOrNode extends Node { - - public STBitwiseOrNode(int id) { - super(id); - } - - public STBitwiseOrNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // ExclusiveOrExpression() - jjtGetChild(0).interpret(); - - // ExclusiveOrExpression() - jjtGetChild(1).interpret(); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() | ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() | ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STBitwiseXorNode.java b/examples/Interpreter/src/main/java/ast/STBitwiseXorNode.java deleted file mode 100644 index cbea9a9..0000000 --- a/examples/Interpreter/src/main/java/ast/STBitwiseXorNode.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STBitwiseXorNode extends Node { - - public STBitwiseXorNode(int id) { - super(id); - } - - public STBitwiseXorNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // AndExpression() - jjtGetChild(0).interpret(); - - // AndExpression() - jjtGetChild(1).interpret(); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() ^ ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() ^ ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STBlock.java b/examples/Interpreter/src/main/java/ast/STBlock.java deleted file mode 100644 index d639532..0000000 --- a/examples/Interpreter/src/main/java/ast/STBlock.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STBlock extends Node { - - public STBlock(int id) { - super(id); - } - - public STBlock(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - for (Node child : children) - // Statement() - child.interpret(); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STCompilationUnit.java b/examples/Interpreter/src/main/java/ast/STCompilationUnit.java deleted file mode 100644 index d16f61b..0000000 --- a/examples/Interpreter/src/main/java/ast/STCompilationUnit.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STCompilationUnit extends Node { - - public STCompilationUnit(int id) { - super(id); - } - - public STCompilationUnit(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - for (Node child : children) { - - System.out.print("Executing:"); - Token first = child.jjtGetFirstToken(); - Token last = child.jjtGetLastToken(); - for (Token t = first; t != null; t = t.next) { - System.out.print(" " + t); - if (t == last) break; - } - System.out.println(); - - // VarDeclaration() | Statement() - child.interpret(); - } - } -} diff --git a/examples/Interpreter/src/main/java/ast/STDivNode.java b/examples/Interpreter/src/main/java/ast/STDivNode.java deleted file mode 100644 index d7e86e7..0000000 --- a/examples/Interpreter/src/main/java/ast/STDivNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STDivNode extends Node { - - public STDivNode(int id) { - super(id); - } - - public STDivNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // UnaryExpression() - jjtGetChild(0).interpret(); - - // UnaryExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() / ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STEQNode.java b/examples/Interpreter/src/main/java/ast/STEQNode.java deleted file mode 100644 index 7af2a66..0000000 --- a/examples/Interpreter/src/main/java/ast/STEQNode.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STEQNode extends Node { - - public STEQNode(int id) { - super(id); - } - - public STEQNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // RelationalExpression() - jjtGetChild(0).interpret(); - - // RelationalExpression() - jjtGetChild(1).interpret(); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() == ((Boolean) stack[top + 1]).booleanValue()); - else - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() == ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STFalseNode.java b/examples/Interpreter/src/main/java/ast/STFalseNode.java deleted file mode 100644 index d234df3..0000000 --- a/examples/Interpreter/src/main/java/ast/STFalseNode.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STFalseNode extends Node { - - public STFalseNode(int id) { - super(id); - } - - public STFalseNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - stack[++top] = new Boolean(false); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STGENode.java b/examples/Interpreter/src/main/java/ast/STGENode.java deleted file mode 100644 index 23cd2f8..0000000 --- a/examples/Interpreter/src/main/java/ast/STGENode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STGENode extends Node { - - public STGENode(int id) { - super(id); - } - - public STGENode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // AdditiveExpression() - jjtGetChild(0).interpret(); - - // AdditiveExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() >= ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STGTNode.java b/examples/Interpreter/src/main/java/ast/STGTNode.java deleted file mode 100644 index 0a637b7..0000000 --- a/examples/Interpreter/src/main/java/ast/STGTNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STGTNode extends Node { - - public STGTNode(int id) { - super(id); - } - - public STGTNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // AdditiveExpression() - jjtGetChild(0).interpret(); - - // AdditiveExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() > ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STId.java b/examples/Interpreter/src/main/java/ast/STId.java deleted file mode 100644 index 5773a1d..0000000 --- a/examples/Interpreter/src/main/java/ast/STId.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STId extends Node { - - String name; - - public STId(int id) { - super(id); - } - - public STId(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - stack[++top] = symtab.get(name); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STIfStatement.java b/examples/Interpreter/src/main/java/ast/STIfStatement.java deleted file mode 100644 index 14fe5ab..0000000 --- a/examples/Interpreter/src/main/java/ast/STIfStatement.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STIfStatement extends Node { - - public STIfStatement(int id) { - super(id); - } - - public STIfStatement(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // Expression() - jjtGetChild(0).interpret(); - - if (((Boolean) stack[top--]).booleanValue()) { - // Statement() - jjtGetChild(1).interpret(); - } else if (jjtGetNumChildren() == 3) { - // Statement() - jjtGetChild(2).interpret(); - } - } -} diff --git a/examples/Interpreter/src/main/java/ast/STIntConstNode.java b/examples/Interpreter/src/main/java/ast/STIntConstNode.java deleted file mode 100644 index b2eed5a..0000000 --- a/examples/Interpreter/src/main/java/ast/STIntConstNode.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STIntConstNode extends Node { - - int val; - - public STIntConstNode(int id) { - super(id); - } - - public STIntConstNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - stack[++top] = new Integer(val); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STLENode.java b/examples/Interpreter/src/main/java/ast/STLENode.java deleted file mode 100644 index b639a92..0000000 --- a/examples/Interpreter/src/main/java/ast/STLENode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STLENode extends Node { - - public STLENode(int id) { - super(id); - } - - public STLENode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // AdditiveExpression() - jjtGetChild(0).interpret(); - - // AdditiveExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() <= ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STLTNode.java b/examples/Interpreter/src/main/java/ast/STLTNode.java deleted file mode 100644 index acc2f8d..0000000 --- a/examples/Interpreter/src/main/java/ast/STLTNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STLTNode extends Node { - - public STLTNode(int id) { - super(id); - } - - public STLTNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // AdditiveExpression() - jjtGetChild(0).interpret(); - - // AdditiveExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() < ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STModNode.java b/examples/Interpreter/src/main/java/ast/STModNode.java deleted file mode 100644 index e99dce3..0000000 --- a/examples/Interpreter/src/main/java/ast/STModNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STModNode extends Node { - - public STModNode(int id) { - super(id); - } - - public STModNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // UnaryExpression() - jjtGetChild(0).interpret(); - - // UnaryExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() % ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STMulNode.java b/examples/Interpreter/src/main/java/ast/STMulNode.java deleted file mode 100644 index a2715b8..0000000 --- a/examples/Interpreter/src/main/java/ast/STMulNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STMulNode extends Node { - - public STMulNode(int id) { - super(id); - } - - public STMulNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // UnaryExpression() - jjtGetChild(0).interpret(); - - // UnaryExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() * ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STNENode.java b/examples/Interpreter/src/main/java/ast/STNENode.java deleted file mode 100644 index b4cc4d1..0000000 --- a/examples/Interpreter/src/main/java/ast/STNENode.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STNENode extends Node { - - public STNENode(int id) { - super(id); - } - - public STNENode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // RelationalExpression() - jjtGetChild(0).interpret(); - - // RelationalExpression() - jjtGetChild(1).interpret(); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() != ((Boolean) stack[top + 1]).booleanValue()); - else - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() != ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STNotNode.java b/examples/Interpreter/src/main/java/ast/STNotNode.java deleted file mode 100644 index 5f2224d..0000000 --- a/examples/Interpreter/src/main/java/ast/STNotNode.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STNotNode extends Node { - - public STNotNode(int id) { - super(id); - } - - public STNotNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // UnaryExpression() - jjtGetChild(0).interpret(); - - stack[top] = new Boolean(!((Boolean) stack[top]).booleanValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STOrNode.java b/examples/Interpreter/src/main/java/ast/STOrNode.java deleted file mode 100644 index 1442eca..0000000 --- a/examples/Interpreter/src/main/java/ast/STOrNode.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STOrNode extends Node { - - public STOrNode(int id) { - super(id); - } - - public STOrNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // ConditionalAndExpression() - jjtGetChild(0).interpret(); - - if (((Boolean) stack[top]).booleanValue()) { - stack[top] = new Boolean(true); - return; - } - - // ConditionalAndExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() || ((Boolean) stack[top + 1]).booleanValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STReadStatement.java b/examples/Interpreter/src/main/java/ast/STReadStatement.java deleted file mode 100644 index 826f08c..0000000 --- a/examples/Interpreter/src/main/java/ast/STReadStatement.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -import java.io.IOException; - -public class STReadStatement extends Node { - - String name; - - public STReadStatement(int id) { - super(id); - } - - public STReadStatement(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - Object o = symtab.get(name); - byte[] b = new byte[64]; - - if (o == null) { - System.out.flush(); - System.err.println("Undefined variable : " + name); - System.err.flush(); - System.exit(1); - } - - try { - System.out.flush(); - if (o instanceof Boolean) { - System.out.println("Enter a value for \'" + name + "\' (boolean) : "); - System.in.read(b); - Boolean bb = new Boolean((new String(b)).trim()); - System.out.println("Read this value for \'" + name + "\' (boolean) : " + bb); - symtab.put(name, bb); - } else if (o instanceof Integer) { - System.out.println("Enter a value for \'" + name + "\' (int) : "); - System.in.read(b); - Integer bi = new Integer((new String(b)).trim()); - System.out.println("Read this value for \'" + name + "\' (int) : " + bi); - symtab.put(name, bi); - } - } catch (IOException ioe) { - ioe.printStackTrace(); - System.exit(2); - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - System.exit(4); - } catch (Exception e) { - e.printStackTrace(); - System.exit(32); - } - } -} diff --git a/examples/Interpreter/src/main/java/ast/STStatementExpression.java b/examples/Interpreter/src/main/java/ast/STStatementExpression.java deleted file mode 100644 index bdedbec..0000000 --- a/examples/Interpreter/src/main/java/ast/STStatementExpression.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STStatementExpression extends Node { - - public STStatementExpression(int id) { - super(id); - } - - public STStatementExpression(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // Assignment() - jjtGetChild(0).interpret(); - - top--; // just throw away the value. - } -} diff --git a/examples/Interpreter/src/main/java/ast/STSubtractNode.java b/examples/Interpreter/src/main/java/ast/STSubtractNode.java deleted file mode 100644 index e67d16b..0000000 --- a/examples/Interpreter/src/main/java/ast/STSubtractNode.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STSubtractNode extends Node { - - public STSubtractNode(int id) { - super(id); - } - - public STSubtractNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - // MultiplicativeExpression() - jjtGetChild(0).interpret(); - - // MultiplicativeExpression() - jjtGetChild(1).interpret(); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() - ((Integer) stack[top + 1]).intValue()); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STTrueNode.java b/examples/Interpreter/src/main/java/ast/STTrueNode.java deleted file mode 100644 index 43d6640..0000000 --- a/examples/Interpreter/src/main/java/ast/STTrueNode.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STTrueNode extends Node { - - public STTrueNode(int id) { - super(id); - } - - public STTrueNode(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - stack[++top] = new Boolean(true); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STVarDeclaration.java b/examples/Interpreter/src/main/java/ast/STVarDeclaration.java deleted file mode 100644 index 2eba0cd..0000000 --- a/examples/Interpreter/src/main/java/ast/STVarDeclaration.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STVarDeclaration extends Node implements SPLParserConstants { - - int type; - String name; - - public STVarDeclaration(int id) { - super(id); - } - - public STVarDeclaration(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - if (type == BOOL) { - symtab.put(name, Boolean.FALSE); - } else { - symtab.put(name, Integer.valueOf(0)); - } - } -} diff --git a/examples/Interpreter/src/main/java/ast/STWhileStatement.java b/examples/Interpreter/src/main/java/ast/STWhileStatement.java deleted file mode 100644 index e79a15e..0000000 --- a/examples/Interpreter/src/main/java/ast/STWhileStatement.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -public class STWhileStatement extends Node { - - public STWhileStatement(int id) { - super(id); - } - - public STWhileStatement(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - do { - // Expression() - jjtGetChild(0).interpret(); - - if (((Boolean) stack[top--]).booleanValue()) { - // Statement() - jjtGetChild(1).interpret(); - } else { - break; - } - } while (true); - } -} diff --git a/examples/Interpreter/src/main/java/ast/STWriteStatement.java b/examples/Interpreter/src/main/java/ast/STWriteStatement.java deleted file mode 100644 index 75b3ec3..0000000 --- a/examples/Interpreter/src/main/java/ast/STWriteStatement.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package ast; - -import java.io.IOException; - -public class STWriteStatement extends Node { - - String name; - - public STWriteStatement(int id) { - super(id); - } - - public STWriteStatement(SPLParser p, int id) { - super(p, id); - } - - public void interpret() { - Object o = symtab.get(name); - - if (o == null) { - System.out.flush(); - System.err.println("Undefined variable : " + name); - System.err.flush(); - System.exit(-1); - } else { - System.out.println("Value of " + name + " : " + o); - } - } -} diff --git a/examples/Interpreter/src/main/java/vst/InterpreterVisitor.java b/examples/Interpreter/src/main/java/vst/InterpreterVisitor.java deleted file mode 100644 index 4a13b05..0000000 --- a/examples/Interpreter/src/main/java/vst/InterpreterVisitor.java +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.Stack; - -public class InterpreterVisitor implements SPLParserVisitor { - - private final InputStream in; - private final PrintStream out; - private final PrintStream err; - - /** Symbol table: key = name, val = type */ - Hashtable symtab = new Hashtable<>(); - - /** "Stack" for calculations. */ - Object[] stack = new Object[10]; - - // Stack nodestack; - - /** Top of the "stack". */ - int top = -1; - - InterpreterVisitor(final InputStream in, final PrintStream out, final PrintStream err) { - this.in = in; - this.out = out; - this.err = err; - } - - @Override - public void visit(final Node node, Object data) {} - - @Override - public void visit(final ST_CompilationUnit node, Object data) { - if (node.children != null) { - for (Node child : node.children) { - out.print("Executing:"); - final Token first = child.jjtGetFirstToken(); - final Token last = child.jjtGetLastToken(); - for (Token t = first; t != null; t = t.next) { - out.print(" " + t); - if (t == last) break; - } - out.println(); - // VarDeclaration() | Statement() - child.jjtAccept(this, data); - } - } - } - - @Override - public void visit(final ST_VarDeclaration node, Object data) { - if (node.type == SPLParserConstants.BOOL) { - symtab.put(node.name, Boolean.FALSE); - } else { - symtab.put(node.name, Integer.valueOf(0)); - } - } - - @Override - public void visit(final ST_Assignment node, Object data) { - // Expression() - node.jjtGetChild(1).jjtAccept(this, data); - - // PrimaryExpression() - // note that here we do not visit the child! - final String name = ((ST_Id) node.jjtGetChild(0)).name; - symtab.put(name, stack[top]); - } - - @Override - public void visit(final ST_OrNode node, Object data) { - // ConditionalAndExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - if (((Boolean) stack[top]).booleanValue()) { - stack[top] = new Boolean(true); - return; - } - - // ConditionalAndExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() || ((Boolean) stack[top + 1]).booleanValue()); - } - - @Override - public void visit(final ST_AndNode node, Object data) { - // InclusiveOrExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - if (!((Boolean) stack[top]).booleanValue()) { - stack[top] = new Boolean(false); - return; - } - - // InclusiveOrExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() && ((Boolean) stack[top + 1]).booleanValue()); - } - - @Override - public void visit(final ST_BitwiseOrNode node, Object data) { - // ExclusiveOrExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // ExclusiveOrExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() | ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() | ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_BitwiseXorNode node, Object data) { - // AndExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // AndExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() ^ ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() ^ ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_BitwiseAndNode node, Object data) { - // EqualityExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // EqualityExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() & ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Integer(((Integer) stack[top]).intValue() & ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_EQNode node, Object data) { - // RelationalExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // RelationalExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() == ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() == ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_NENode node, Object data) { - // RelationalExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // RelationalExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - if (stack[top] instanceof Boolean) - stack[--top] = - new Boolean( - ((Boolean) stack[top]).booleanValue() != ((Boolean) stack[top + 1]).booleanValue()); - else if (stack[top] instanceof Integer) - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() != ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_LTNode node, Object data) { - // AdditiveExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // AdditiveExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() < ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_GTNode node, Object data) { - // AdditiveExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // AdditiveExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() > ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_LENode node, Object data) { - // AdditiveExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // AdditiveExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() <= ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_GENode node, Object data) { - // AdditiveExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // AdditiveExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Boolean(((Integer) stack[top]).intValue() >= ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_AddNode node, Object data) { - // MultiplicativeExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // MultiplicativeExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() + ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_SubtractNode node, Object data) { - // MultiplicativeExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // MultiplicativeExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() - ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_MulNode node, Object data) { - // UnaryExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // UnaryExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() * ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_DivNode node, Object data) { - // UnaryExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // UnaryExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() / ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_ModNode node, Object data) { - // UnaryExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - // UnaryExpression() - node.jjtGetChild(1).jjtAccept(this, data); - - stack[--top] = - new Integer(((Integer) stack[top]).intValue() % ((Integer) stack[top + 1]).intValue()); - } - - @Override - public void visit(final ST_BitwiseComplNode node, Object data) { - // UnaryExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - stack[top] = new Integer(~((Integer) stack[top]).intValue()); - } - - @Override - public void visit(final ST_NotNode node, Object data) { - // UnaryExpression() - node.jjtGetChild(0).jjtAccept(this, data); - - stack[top] = new Boolean(!((Boolean) stack[top]).booleanValue()); - } - - @Override - public void visit(final ST_Id node, Object data) { - stack[++top] = symtab.get(node.name); - } - - @Override - public void visit(final ST_IntConstNode node, Object data) { - stack[++top] = new Integer(node.val); - } - - @Override - public void visit(final ST_TrueNode node, Object data) { - stack[++top] = new Boolean(true); - } - - @Override - public void visit(final ST_FalseNode node, Object data) { - stack[++top] = new Boolean(false); - } - - @Override - public void visit(final ST_Block node, Object data) { - for (Node child : node.children) { - // Statement() - child.jjtAccept(this, data); - } - } - - @Override - public void visit(final ST_StatementExpression node, Object data) { - // Assignment() - node.jjtGetChild(0).jjtAccept(this, data); - - top--; // just throw away the value. - } - - @Override - public void visit(final ST_IfStatement node, Object data) { - // Expression() - node.jjtGetChild(0).jjtAccept(this, data); - - if (((Boolean) stack[top--]).booleanValue()) { - // Statement() - node.jjtGetChild(1).jjtAccept(this, data); - } else if (node.jjtGetNumChildren() == 3) { - // Statement() - node.jjtGetChild(2).jjtAccept(this, data); - } - } - - @Override - public void visit(final ST_WhileStatement node, Object data) { - do { - // Expression() - node.jjtGetChild(0).jjtAccept(this, data); - - if (((Boolean) stack[top--]).booleanValue()) { - // Statement() - node.jjtGetChild(1).jjtAccept(this, data); - } else { - break; - } - } while (true); - } - - @Override - public void visit(final ST_ReadStatement node, Object data) { - final String name = node.name; - final Object o = symtab.get(name); - byte[] b = new byte[64]; - - if (o == null) { - out.flush(); - err.println("Undefined variable : " + name); - err.flush(); - System.exit(1); - } - - try { - out.flush(); - if (o instanceof Boolean) { - out.println("Enter a value for \'" + name + "\' (boolean) : "); - in.read(b); - Boolean bb = new Boolean((new String(b)).trim()); - out.println("Read this value for \'" + name + "\' (boolean) : " + bb); - symtab.put(name, bb); - } else if (o instanceof Integer) { - out.println("Enter a value for \'" + name + "\' (int) : "); - in.read(b); - Integer bi = new Integer((new String(b)).trim()); - out.println("Read this value for \'" + name + "\' (int) : " + bi); - symtab.put(name, bi); - } - } catch (IOException ioe) { - ioe.printStackTrace(); - System.exit(2); - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - System.exit(4); - } catch (Exception e) { - e.printStackTrace(); - System.exit(32); - } - } - - @Override - public void visit(final ST_WriteStatement node, Object data) { - final String name = node.name; - final Object o = symtab.get(name); - - if (o == null) { - out.flush(); - err.println("Undefined variable : " + name); - err.flush(); - System.exit(-1); - } else { - out.println("Value of " + name + " : " + o); - } - } -} diff --git a/examples/Interpreter/src/main/java/vst/SPLMain.java b/examples/Interpreter/src/main/java/vst/SPLMain.java deleted file mode 100644 index 771a2c4..0000000 --- a/examples/Interpreter/src/main/java/vst/SPLMain.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -/** Simple Programming Language parser. */ -public class SPLMain { - - /** Main entry point. */ - public static void main(String args[]) { - InputStream spl = null; - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - - try { - SPLParser parser; - switch (args.length) { - case 1: - output.println( - "Simple Programming Language Interpreter (VST): Reading from file " - + args[0] - + " . . ."); - try { - parser = new SPLParser(new FileInputStream(args[0])); - } catch (FileNotFoundException e) { - error.println( - "Simple Programming Language Interpreter (VST): File " - + args[0] - + " not found."); - return; - } - break; - case 4: - spl = new FileInputStream(args[0]); - prevInput = input; - input = new FileInputStream(args[1]); - System.setIn(input); - prevOutput = output; - output = new PrintStream(args[2]); - System.setOut(output); - prevError = error; - error = new PrintStream(args[3]); - System.setErr(error); - parser = new SPLParser(spl); - break; - default: - output.println("Simple Programming Language Interpreter (VST): Usage :"); - output.println(" java SPLMain spl [in out err]"); - return; - } - parser.CompilationUnit(); - final InterpreterVisitor vis = new InterpreterVisitor(input, output, error); - parser.jjtree.rootNode().jjtAccept(vis, new Object()); - } catch (ParseException e) { - error.println( - "Simple Programming Language Interpreter (VST): Encountered errors during parse."); - e.printStackTrace(); - } catch (Exception e1) { - error.println( - "Simple Programming Language Interpreter (VST): Encountered errors during interpretation/tree building."); - e1.printStackTrace(); - } finally { - try { - input.close(); - output.close(); - error.close(); - } catch (IOException e) { - } - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} diff --git a/examples/Interpreter/src/main/java/vst/ST_Id.java b/examples/Interpreter/src/main/java/vst/ST_Id.java deleted file mode 100644 index ddc4bb7..0000000 --- a/examples/Interpreter/src/main/java/vst/ST_Id.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -public class ST_Id extends Node { - - String name; - - public ST_Id(int id) { - super(id); - } - - public ST_Id(SPLParser p, int id) { - super(p, id); - } - - /** Accept the visitor. */ - public void jjtAccept(SPLParserVisitor visitor, Object data) { - visitor.visit(this, data); - } -} diff --git a/examples/Interpreter/src/main/java/vst/ST_IntConstNode.java b/examples/Interpreter/src/main/java/vst/ST_IntConstNode.java deleted file mode 100644 index a13e25f..0000000 --- a/examples/Interpreter/src/main/java/vst/ST_IntConstNode.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -public class ST_IntConstNode extends Node { - - int val; - - public ST_IntConstNode(int id) { - super(id); - } - - public ST_IntConstNode(SPLParser p, int id) { - super(p, id); - } - - /** Accept the visitor. */ - public void jjtAccept(SPLParserVisitor visitor, Object data) { - visitor.visit(this, data); - } -} diff --git a/examples/Interpreter/src/main/java/vst/ST_ReadStatement.java b/examples/Interpreter/src/main/java/vst/ST_ReadStatement.java deleted file mode 100644 index 8c2c56d..0000000 --- a/examples/Interpreter/src/main/java/vst/ST_ReadStatement.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -class ST_ReadStatement extends Node { - - String name; - - public ST_ReadStatement(int id) { - super(id); - } - - public ST_ReadStatement(SPLParser p, int id) { - super(p, id); - } - - /** Accept the visitor. */ - public void jjtAccept(SPLParserVisitor visitor, Object data) { - visitor.visit(this, data); - } -} diff --git a/examples/Interpreter/src/main/java/vst/ST_VarDeclaration.java b/examples/Interpreter/src/main/java/vst/ST_VarDeclaration.java deleted file mode 100644 index 9fbf2d6..0000000 --- a/examples/Interpreter/src/main/java/vst/ST_VarDeclaration.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -public class ST_VarDeclaration extends Node { - - int type; - String name; - - public ST_VarDeclaration(int id) { - super(id); - } - - public ST_VarDeclaration(SPLParser p, int id) { - super(p, id); - } - - /** Accept the visitor. */ - public void jjtAccept(SPLParserVisitor visitor, Object data) { - visitor.visit(this, data); - } -} diff --git a/examples/Interpreter/src/main/java/vst/ST_WriteStatement.java b/examples/Interpreter/src/main/java/vst/ST_WriteStatement.java deleted file mode 100644 index 610fc06..0000000 --- a/examples/Interpreter/src/main/java/vst/ST_WriteStatement.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package vst; - -class ST_WriteStatement extends Node { - - String name; - - public ST_WriteStatement(int id) { - super(id); - } - - public ST_WriteStatement(SPLParser p, int id) { - super(p, id); - } - - /** Accept the visitor. */ - public void jjtAccept(SPLParserVisitor visitor, Object data) { - visitor.visit(this, data); - } -} diff --git a/examples/Interpreter/src/main/jjtree/AST.jjt b/examples/Interpreter/src/main/jjtree/AST.jjt deleted file mode 100644 index e75c99e..0000000 --- a/examples/Interpreter/src/main/jjtree/AST.jjt +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options { - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; -// NODE_DEFAULT_VOID = false; // (JJTree - default false) - NODE_EXTENDS = "MyNode"; - NODE_PACKAGE = "ast"; - NODE_PREFIX = "ST"; - TRACK_TOKENS = true; -} - -PARSER_BEGIN(SPLParser) -package ast; - -class SPLParser -{ -} - -PARSER_END(SPLParser) - - -SKIP : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -TOKEN : /* Types */ -{ - < INT : "int" > - | - < BOOL : "boolean" > -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL : ()+ > -} - -/** Compilation unit. */ -void CompilationUnit() : -{} -{ - ( - VarDeclaration() ";" - | - Statement() - )* - -} - -/** Variable declaration. */ -void VarDeclaration() : -{ Token t; } -{ - ( - "boolean" - { jjtThis.type = BOOL; } - | - "int" - { jjtThis.type = INT; } - ) - t = - { jjtThis.name = t.image; } -} - -/** Expression. */ -void Expression() #void : -{} -{ - LOOKAHEAD( PrimaryExpression() "=" ) - Assignment() -| - ConditionalOrExpression() -} - -/** Assignment. */ -void Assignment() #Assignment(2) : -{} -{ - PrimaryExpression() "=" Expression() -} - -/** Conditional or expression. */ -void ConditionalOrExpression() #void : -{} -{ - ConditionalAndExpression() - ( "||" ConditionalAndExpression() #OrNode(2) )* -} - -/** Conditional and expression. */ -void ConditionalAndExpression() #void : -{} -{ - InclusiveOrExpression() - ( "&&" InclusiveOrExpression() #AndNode(2) )* -} - -/** Inclusive or expression. */ -void InclusiveOrExpression() #void : -{} -{ - ExclusiveOrExpression() - ( "|" ExclusiveOrExpression() #BitwiseOrNode(2) )* -} - -/** Exclusive or expression. */ -void ExclusiveOrExpression() #void : -{} -{ - AndExpression() - ( "^" AndExpression() #BitwiseXorNode(2) )* -} - -/** And expression. */ -void AndExpression() #void : -{} -{ - EqualityExpression() - ( "&" EqualityExpression() #BitwiseAndNode(2) )* -} - -/** Equality expression. */ -void EqualityExpression() #void : -{} -{ - RelationalExpression() - ( - "==" RelationalExpression() #EQNode(2) - | - "!=" RelationalExpression() #NENode(2) - )* -} - -/** Relational expression. */ -void RelationalExpression() #void : -{} -{ - AdditiveExpression() - ( - "<" AdditiveExpression() #LTNode(2) - | - ">" AdditiveExpression() #GTNode(2) - | - "<=" AdditiveExpression() #LENode(2) - | - ">=" AdditiveExpression() #GENode(2) - )* -} - -/** Additive expression. */ -void AdditiveExpression() #void : -{} -{ - MultiplicativeExpression() - ( - "+" MultiplicativeExpression() #AddNode(2) - | - "-" MultiplicativeExpression() #SubtractNode(2) - )* -} - -/** Multiplicative expression. */ -void MultiplicativeExpression() #void : -{} -{ - UnaryExpression() - ( - "*" UnaryExpression() #MulNode(2) - | - "/" UnaryExpression() #DivNode(2) - | - "%" UnaryExpression() #ModNode(2) - )* -} - -/** Unary expression. */ -void UnaryExpression() #void : -{} -{ - "~" UnaryExpression() #BitwiseComplNode(1) -| - "!" UnaryExpression() #NotNode(1) -| - PrimaryExpression() -} - -/** Primary expression. */ -void PrimaryExpression() #void : -{} -{ - Literal() -| - Id() -| - "(" Expression() ")" -} - -/** An Id. */ -void Id() : -{ Token t; } -{ - t = - { jjtThis.name = t.image; } -} - -/** A literal. */ -void Literal() #void : -{ Token t; } -{ - ( - t = - { jjtThis.val = Integer.parseInt(t.image); } - ) #IntConstNode -| - BooleanLiteral() -} - -/** A boolean literal. */ -void BooleanLiteral() #void : -{} -{ - "true" #TrueNode -| - "false" #FalseNode -} - -/** A statement. */ -void Statement() #void : -{} -{ - ";" -| - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - StatementExpression() -| - IfStatement() -| - WhileStatement() -| - IOStatement() -} - -/** A labeled statement. */ -void LabeledStatement() #void : -{} -{ - ":" Statement() -} - -/** A block. */ -void Block() : -{} -{ - "{" ( Statement() )* "}" -} - -/** A statement expression. */ -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * SPL expansions for StatementExpression. - */ -{} -{ - Assignment() ";" -} - -/** An if statement. */ -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -/** A while statement. */ -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -/** An IO statement. */ -void IOStatement() #void : -{} -{ - ReadStatement() -| - WriteStatement() -} - -/** A read statement. */ -void ReadStatement() : -{ Token t; } -{ - "read" t = - { jjtThis.name = t.image; } -} - -/** A write statement. */ -void WriteStatement() : -{ Token t; } -{ - "write" t = - { jjtThis.name = t.image; } -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER : ( | )* > -| - < #LETTER : [ "a"-"z", "A"-"Z" ] > -| - < #DIGIT : [ "0"-"9"] > -} diff --git a/examples/Interpreter/src/main/jjtree/VST.jjt b/examples/Interpreter/src/main/jjtree/VST.jjt deleted file mode 100644 index 4abca8e..0000000 --- a/examples/Interpreter/src/main/jjtree/VST.jjt +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options { - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; -// NODE_EXTENDS = "MyNode"; - NODE_PACKAGE = "vst"; - TRACK_TOKENS = true; - -// DEBUG_PARSER = true; -// DEBUG_TOKEN_MANAGER = true; -// ERROR_REPORTING = false; - -// NODE_DEFAULT_VOID = false; - NODE_PREFIX = "ST_"; - VISITOR = true; - VISITOR_DATA_TYPE = "Object"; - VISITOR_RETURN_TYPE = "void"; -} - -PARSER_BEGIN(SPLParser) -package vst; - -class SPLParser -{ -} - -PARSER_END(SPLParser) - - -SKIP : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -TOKEN : /* Types */ -{ - < INT : "int" > - | - < BOOL : "boolean" > -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL : ()+ > -} - -/** Compilation unit. */ -void CompilationUnit() : -{} -{ - ( - VarDeclaration() ";" - | - Statement() - )* - -} - -/** Variable declaration. */ -void VarDeclaration() #VarDeclaration : -{ Token t; } -{ - ( - "boolean" - { jjtThis.type = BOOL; } - | - "int" - { jjtThis.type = INT; } - ) - t = - { jjtThis.name = t.image; } -} - -/** Expression. */ -void Expression() #void : -{} -{ - LOOKAHEAD( PrimaryExpression() "=" ) - Assignment() -| - ConditionalOrExpression() -} - -/** Assignment. */ -void Assignment() #Assignment(2) : -{} -{ - PrimaryExpression() "=" Expression() -} - -/** Conditional or expression. */ -void ConditionalOrExpression() #void : -{} -{ - ConditionalAndExpression() - ( "||" ConditionalAndExpression() #OrNode(2) )* -} - -/** Conditional and expression. */ -void ConditionalAndExpression() #void : -{} -{ - InclusiveOrExpression() - ( "&&" InclusiveOrExpression() #AndNode(2) )* -} - -/** Inclusive or expression. */ -void InclusiveOrExpression() #void : -{} -{ - ExclusiveOrExpression() - ( "|" ExclusiveOrExpression() #BitwiseOrNode(2) )* -} - -/** Exclusive or expression. */ -void ExclusiveOrExpression() #void : -{} -{ - AndExpression() - ( "^" AndExpression() #BitwiseXorNode(2) )* -} - -/** And expression. */ -void AndExpression() #void : -{} -{ - EqualityExpression() - ( "&" EqualityExpression() #BitwiseAndNode(2) )* -} - -/** Equality expression. */ -void EqualityExpression() #void : -{} -{ - RelationalExpression() - ( - "==" RelationalExpression() #EQNode(2) - | - "!=" RelationalExpression() #NENode(2) - )* -} - -/** Relational expression. */ -void RelationalExpression() #void : -{} -{ - AdditiveExpression() - ( - "<" AdditiveExpression() #LTNode(2) - | - ">" AdditiveExpression() #GTNode(2) - | - "<=" AdditiveExpression() #LENode(2) - | - ">=" AdditiveExpression() #GENode(2) - )* -} - -/** Additive expression. */ -void AdditiveExpression() #void : -{} -{ - MultiplicativeExpression() - ( - "+" MultiplicativeExpression() #AddNode(2) - - | - "-" MultiplicativeExpression() #SubtractNode(2) - )* -} - -/** Multiplicative expression. */ -void MultiplicativeExpression() #void : -{} -{ - UnaryExpression() - ( - "*" UnaryExpression() #MulNode(2) - | - "/" UnaryExpression() #DivNode(2) - | - "%" UnaryExpression() #ModNode(2) - )* -} - -/** Unary expression. */ -void UnaryExpression() #void : -{} -{ - "~" UnaryExpression() #BitwiseComplNode(1) -| - "!" UnaryExpression() #NotNode(1) -| - PrimaryExpression() -} - -/** Primary expression. */ -void PrimaryExpression() #void : -{} -{ - Literal() -| - Id() -| - "(" Expression() ")" -} - -/** An Id. */ -void Id() : -{ Token t; } -{ - t = - { jjtThis.name = t.image; } -} - -/** A literal. */ -void Literal() #void : -{ Token t; } -{ - ( - t = - { jjtThis.val = Integer.parseInt(t.image); } - ) #IntConstNode -| - BooleanLiteral() -} - -/** A boolean literal. */ -void BooleanLiteral() #void : -{} -{ - "true" #TrueNode -| - "false" #FalseNode -} - -/** A statement. */ -void Statement() #void : -{} -{ - ";" -| - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - StatementExpression() -| - IfStatement() -| - WhileStatement() -| - IOStatement() -} - -/** A labeled statement. */ -void LabeledStatement() #void : -{} -{ - ":" Statement() -} - -/** A block. */ -void Block() : -{} -{ - "{" ( Statement() )* "}" -} - -/** A statement expression. */ -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * SPL expansions for StatementExpression. - */ -{} -{ - Assignment() ";" -} - -/** An if statement. */ -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -/** A while statement. */ -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -/** An IO statement. */ -void IOStatement() #void : -{} -{ - ReadStatement() -| - WriteStatement() -} - -/** A read statement. */ -void ReadStatement() : -{ Token t; } -{ - "read" t = - { jjtThis.name = t.image; } -} - -/** A write statement. */ -void WriteStatement() : -{ Token t; } -{ - "write" t = - { jjtThis.name = t.image; } -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER : ( | )* > -| - < #LETTER : [ "a"-"z", "A"-"Z" ] > -| - < #DIGIT : [ "0"-"9"] > -} diff --git a/examples/JJTree/README b/examples/JJTree/README deleted file mode 100644 index 421a2fd..0000000 --- a/examples/JJTree/README +++ /dev/null @@ -1,196 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -JJTreeExamples - -This directory contains some simple JJTree input files intended to -illustrate some of the basic ideas. All of them are based on a -grammar to recognize arithmetic expressions built out of identifiers -and constants. - -eg1.jjt - -This example is just the JavaCC grammar, with a little extra code in -the parser's main method to call the dump method on the generated -tree. It illustrates how the default behavior of JJTree will produce -a tree of non-terminals. - -eg2.jjt - -This example is the same grammar as eg1.jjt with modifications to -customize the generated tree. It illustrates how unnecessary -intermediate nodes can be suppressed and how actions in the grammar -can attach extra information to the nodes. - -eg3.jjt - -This example is a modification of eg2.jjt with the NODE_DEFAULT_VOID -option set. This instructs JJTree to treat all undecorated -non-terminals as if they were decorated as #void. The default JJTree -behavior is to treat such non-terminals as if they were decorated -with the name of the non-terminal. - -eg4.jjt - -This is a modification of eg3.jjt with the VISITOR option set. This -instructs JJTree to insert a jjtAccept() method into all nodes it -generates, and to produce a visitor class. The visitor is used to -dump the tree. - -Here are some instructions on how to run the examples using the Ant build scripts, -and the output you can expect to see. - -eg1.jjt -------- - -The only bit of JJTree-specific code is an action in the start -production that dumps the constructed parse tree when the parse is -complete. It uses JJTree simple mode. - -The input file is eg1.jjt. - -$ ant eg1 -Buildfile: build.xml - -eg1: - [mkdir] Created dir: /home/tom/javacc/javacc/examples/JJTreeExamples/eg1 - [copy] Copying 1 file to /home/tom/javacc/javacc/examples/JJTreeExamples/eg1 - [jjtree] Java Compiler Compiler Version 3.2 (Tree Builder) - [jjtree] (type "jjtree" with no arguments for help) - [jjtree] Reading from file /home/tom/javacc/javacc/examples/JJTreeExamples/eg1.jjt . . . - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg1/Node.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg1/SimpleNode.java" does not exist. Will create one. - [jjtree] Annotated grammar generated successfully in /home/tom/javacc/javacc/examples/JJTreeExamples/eg1/eg1.jj - [javacc] Java Compiler Compiler Version 3.2 (Parser Generator) - [javacc] (type "javacc" with no arguments for help) - [javacc] Reading from file /home/tom/javacc/javacc/examples/JJTreeExamples/eg1/eg1.jj . . . - [javacc] File "TokenMgrError.java" does not exist. Will create one. - [javacc] File "ParseException.java" does not exist. Will create one. - [javacc] File "Token.java" does not exist. Will create one. - [javacc] File "SimpleCharStream.java" does not exist. Will create one. - [javacc] Parser generated successfully. - [javac] Compiling 11 source files to /home/tom/javacc/javacc/examples/JJTreeExamples/eg1 - [echo] ******* - [echo] ******* Now cd into the eg1 directory and run 'java eg1' ****** - [echo] ******* - -BUILD SUCCESSFUL -Total time: 3 seconds -[tom@hal JJTreeExamples]$ cd eg1 -[tom@hal eg1]$ java eg1 -Reading from standard input... -(a + b) * (c + 1); -Start - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Identifier - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Integer -Thank you. - -eg2.jjt -------- - -This is a modification of the first example to illustrate how the -parse tree can be customized: - -$ ant eg2 -Buildfile: build.xml - -eg2: - [mkdir] Created dir: /home/tom/javacc/javacc/examples/JJTreeExamples/eg2 - [copy] Copying 1 file to /home/tom/javacc/javacc/examples/JJTreeExamples/eg2 - [copy] Copying 1 file to /home/tom/javacc/javacc/examples/JJTreeExamples/eg2 - [jjtree] Java Compiler Compiler Version 3.2 (Tree Builder) - [jjtree] (type "jjtree" with no arguments for help) - [jjtree] Reading from file /home/tom/javacc/javacc/examples/JJTreeExamples/eg2.jjt . . . - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/Node.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/SimpleNode.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/ASTStart.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/ASTAdd.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/ASTMult.java" does not exist. Will create one. - [jjtree] File "/home/tom/javacc/javacc/examples/JJTreeExamples/eg2/ASTInteger.java" does not exist. Will create one. - [jjtree] Annotated grammar generated successfully in /home/tom/javacc/javacc/examples/JJTreeExamples/eg2/eg2.jj - [javacc] Java Compiler Compiler Version 3.2 (Parser Generator) - [javacc] (type "javacc" with no arguments for help) - [javacc] Reading from file /home/tom/javacc/javacc/examples/JJTreeExamples/eg2/eg2.jj . . . - [javacc] File "TokenMgrError.java" does not exist. Will create one. - [javacc] File "ParseException.java" does not exist. Will create one. - [javacc] File "Token.java" does not exist. Will create one. - [javacc] File "SimpleCharStream.java" does not exist. Will create one. - [javacc] Parser generated successfully. - [javac] Compiling 16 source files to /home/tom/javacc/javacc/examples/JJTreeExamples/eg2 - [echo] ******* - [echo] ******* Now cd into the eg2 directory and run 'java eg2' ****** - [echo] ******* - -BUILD SUCCESSFUL -Total time: 3 seconds -[tom@hal JJTreeExamples]$ cd eg2 -[tom@hal eg2]$ java eg2 -Reading from standard input... -(a + b) * (c + 1); -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. - -Look at eg2.jjt to see how node annotations can be used to restructure -the parse tree, and at ASTMyID.java to see how you can write your own -node classes that maintain more information from the input stream. - -eg3.jjt -------- - -This example can be run in the same manner as you ran eg2.jjt. - -eg4.jjt -------- - -This example again can be run in the same manner as you ran eg2.jjt. diff --git a/examples/JJTree/files/eg1.err b/examples/JJTree/files/eg1.err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/JJTree/files/eg1.in b/examples/JJTree/files/eg1.in deleted file mode 100644 index 3490a8c..0000000 --- a/examples/JJTree/files/eg1.in +++ /dev/null @@ -1 +0,0 @@ -(a + b) * (c + 1); \ No newline at end of file diff --git a/examples/JJTree/files/eg1.out b/examples/JJTree/files/eg1.out deleted file mode 100644 index d783c47..0000000 --- a/examples/JJTree/files/eg1.out +++ /dev/null @@ -1,23 +0,0 @@ -Start - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Identifier - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Integer -Thank you. diff --git a/examples/JJTree/files/eg1.ref b/examples/JJTree/files/eg1.ref deleted file mode 100644 index d783c47..0000000 --- a/examples/JJTree/files/eg1.ref +++ /dev/null @@ -1,23 +0,0 @@ -Start - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Identifier - UnaryExpression - Expression - AdditiveExpression - MultiplicativeExpression - UnaryExpression - Identifier - MultiplicativeExpression - UnaryExpression - Integer -Thank you. diff --git a/examples/JJTree/files/eg2.err b/examples/JJTree/files/eg2.err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/JJTree/files/eg2.in b/examples/JJTree/files/eg2.in deleted file mode 100644 index 3490a8c..0000000 --- a/examples/JJTree/files/eg2.in +++ /dev/null @@ -1 +0,0 @@ -(a + b) * (c + 1); \ No newline at end of file diff --git a/examples/JJTree/files/eg2.out b/examples/JJTree/files/eg2.out deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg2.out +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/files/eg2.ref b/examples/JJTree/files/eg2.ref deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg2.ref +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/files/eg3.err b/examples/JJTree/files/eg3.err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/JJTree/files/eg3.in b/examples/JJTree/files/eg3.in deleted file mode 100644 index 3490a8c..0000000 --- a/examples/JJTree/files/eg3.in +++ /dev/null @@ -1 +0,0 @@ -(a + b) * (c + 1); \ No newline at end of file diff --git a/examples/JJTree/files/eg3.out b/examples/JJTree/files/eg3.out deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg3.out +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/files/eg3.ref b/examples/JJTree/files/eg3.ref deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg3.ref +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/files/eg4.err b/examples/JJTree/files/eg4.err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/JJTree/files/eg4.in b/examples/JJTree/files/eg4.in deleted file mode 100644 index 3490a8c..0000000 --- a/examples/JJTree/files/eg4.in +++ /dev/null @@ -1 +0,0 @@ -(a + b) * (c + 1); \ No newline at end of file diff --git a/examples/JJTree/files/eg4.out b/examples/JJTree/files/eg4.out deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg4.out +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/files/eg4.ref b/examples/JJTree/files/eg4.ref deleted file mode 100644 index b174554..0000000 --- a/examples/JJTree/files/eg4.ref +++ /dev/null @@ -1,9 +0,0 @@ -Start - Mult - Add - Identifier: a - Identifier: b - Add - Identifier: c - Integer -Thank you. diff --git a/examples/JJTree/pom.xml b/examples/JJTree/pom.xml deleted file mode 100644 index f5781ad..0000000 --- a/examples/JJTree/pom.xml +++ /dev/null @@ -1,218 +0,0 @@ - - - - 4.0.0 - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - jjtree - jar - - JavaCC Java code generator / examples / JJTree - - - - - - org.codehaus.mojo - exec-maven-plugin - - - run-eg1 - test - - java - - - eg1.Eg1 - - ${project.basedir}/files/eg1.in - ${project.basedir}/files/eg1.out - ${project.basedir}/files/eg1.err - - - - - run-eg2 - test - - java - - - eg2.Eg2 - - ${project.basedir}/files/eg2.in - ${project.basedir}/files/eg2.out - ${project.basedir}/files/eg2.err - - - - - run-eg3 - test - - java - - - eg3.Eg3 - - ${project.basedir}/files/eg3.in - ${project.basedir}/files/eg3.out - ${project.basedir}/files/eg3.err - - - - - run-eg4 - test - - java - - - eg4.Eg4 - - ${project.basedir}/files/eg4.in - ${project.basedir}/files/eg4.out - ${project.basedir}/files/eg4.err - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - compare-eg1 - test - - run - - - - - - - - - - - - - - - - compare-eg2 - test - - run - - - - - - - - - - - - - - - - compare-eg3 - test - - run - - - - - - - - - - - - - - - - compare-eg4 - test - - run - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/JJTree/src/main/java/eg2/ASTMyID.java b/examples/JJTree/src/main/java/eg2/ASTMyID.java deleted file mode 100644 index 9c1f94f..0000000 --- a/examples/JJTree/src/main/java/eg2/ASTMyID.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg2; - -/** An ID. */ -public class ASTMyID extends Node { - private String name; - - /** - * Constructor. - * - * @param id the id - */ - public ASTMyID(int id) { - super(id); - } - - /** - * Set the name. - * - * @param n the name - */ - public void setName(String n) { - name = n; - } - - /** - * {@inheritDoc} - * - * @see org.javacc.examples.jjtree.eg2.SimpleNode#toString() - */ - public String toString() { - return "Identifier: " + name; - } -} diff --git a/examples/JJTree/src/main/java/eg3/ASTMyID.java b/examples/JJTree/src/main/java/eg3/ASTMyID.java deleted file mode 100644 index 69157fc..0000000 --- a/examples/JJTree/src/main/java/eg3/ASTMyID.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg3; - -import eg3.Node; -import eg3.ASTMyID; - -/** An ID. */ -public class ASTMyID extends Node { - private String name; - - /** - * Constructor. - * - * @param id the id - */ - public ASTMyID(int id) { - super(id); - } - - /** - * Set the name. - * - * @param n the name - */ - public void setName(String n) { - name = n; - } - - /** - * {@inheritDoc} - * - * @see org.javacc.examples.jjtree.eg2.Node#toString() - */ - public String toString() { - return "Identifier: " + name; - } -} diff --git a/examples/JJTree/src/main/java/eg4/ASTMyID.java b/examples/JJTree/src/main/java/eg4/ASTMyID.java deleted file mode 100644 index d82f778..0000000 --- a/examples/JJTree/src/main/java/eg4/ASTMyID.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg4; - -import eg4.Node; - -/** An ID. */ -public class ASTMyID extends Node { - private String name; - - /** - * Constructor. - * - * @param id the id - */ - public ASTMyID(int id) { - super(id); - } - - /** - * Set the name. - * - * @param n the name - */ - public void setName(String n) { - name = n; - } - - /** - * {@inheritDoc} - * - * @see org.javacc.examples.jjtree.eg2.Node#toString() - */ - public String toString() { - return "Identifier: " + name; - } -} diff --git a/examples/JJTree/src/main/java/eg4/ASTMyOtherID.java b/examples/JJTree/src/main/java/eg4/ASTMyOtherID.java deleted file mode 100644 index b5ddf34..0000000 --- a/examples/JJTree/src/main/java/eg4/ASTMyOtherID.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg4; - -import eg4.Eg4; -import eg4.Eg4Visitor; -import eg4.Node; - -public class ASTMyOtherID extends Node { - - private String name; - - public ASTMyOtherID(int id) { - super(id); - } - - public ASTMyOtherID(Eg4 p, int id) { - super(p, id); - } - - /** - * Set the name. - * - * @param n the name - */ - public void setName(String n) { - name = n; - } - - /** - * {@inheritDoc} - * - * @see org.javacc.examples.jjtree.eg2.Node#toString() - */ - public String toString() { - return "Identifier: " + name; - } - - /** Accept the visitor. */ - public Object jjtAccept(Eg4Visitor visitor, Object data) { - return visitor.visit(this, data); - } -} diff --git a/examples/JJTree/src/main/java/eg4/Eg4DumpVisitor.java b/examples/JJTree/src/main/java/eg4/Eg4DumpVisitor.java deleted file mode 100644 index b3ca05e..0000000 --- a/examples/JJTree/src/main/java/eg4/Eg4DumpVisitor.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg4; - -import eg4.ASTAdd; -import eg4.ASTInteger; -import eg4.ASTMult; -import eg4.ASTStart; -import eg4.Eg4Visitor; -import eg4.Node; - -/** - * This is an example of how the Visitor pattern might be used to implement the dumping code that - * comes with Node. It's a bit long-winded, but it does illustrate a couple of the main points. - * - *
    - *
  1. the visitor can maintain state between the nodes that it visits (for example the current - * indentation level). - *
  2. if you don't implement a jjtAccept() method for a subclass of Node, then Node's acceptor - * will get called. - *
  3. the utility method childrenAccept() can be useful when implementing preorder or postorder - * tree walks. - *
- */ -public class Eg4DumpVisitor implements Eg4Visitor { - - private int indent = 0; - - private String indentString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < indent; ++i) { - sb.append(' '); - } - return sb.toString(); - } - - public Object visit(Node node, Object data) { - System.out.println(indentString() + node + ": acceptor not unimplemented in subclass?"); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - - public Object visit(ASTStart node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - - public Object visit(ASTAdd node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - - public Object visit(ASTMult node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - - public Object visit(ASTMyOtherID node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - - public Object visit(ASTInteger node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } -} diff --git a/examples/JJTree/src/main/java/eg4/MyVisException.java b/examples/JJTree/src/main/java/eg4/MyVisException.java deleted file mode 100644 index 8940c01..0000000 --- a/examples/JJTree/src/main/java/eg4/MyVisException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package eg4; - -public class MyVisException extends RuntimeException { - - private static final long serialVersionUID = 1L; -} diff --git a/examples/JJTree/src/main/jjtree/eg1.jjt b/examples/JJTree/src/main/jjtree/eg1.jjt deleted file mode 100644 index ed0c479..0000000 --- a/examples/JJTree/src/main/jjtree/eg1.jjt +++ /dev/null @@ -1,809 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - NODE_PACKAGE = "eg1"; -} - -PARSER_BEGIN(Eg1) -package eg1; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** An Arithmetic Grammar. */ -public class Eg1 { - - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; - input = new FileInputStream(args[0]); - prevOutput = output; - output = new PrintStream(args[1]); - prevError = error; - error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - Eg1 t = new Eg1(input); - try { - Node n = Eg1.Start(); - n.dump(""); - output.println("Thank you."); - } catch (Exception e) { - error.println("Oops."); - error.println(e.getMessage()); - e.printStackTrace(); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} - -PARSER_END(Eg1) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| <"//" (~["\n","\r"])* ("\n"|"\r"|"\r\n")> -| <"/*" (~["*"])* "*" (~["/"] (~["*"])* "*")* "/"> -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -} - -TOKEN : /* IDENTIFIERS */ -{ -// < IDENTIFIER: (|)* > - < IDENTIFIER: (|)* > -| - < #LETTER: ["_","a"-"z","A"-"Z"] > -| - < #DIGIT: ["0"-"9"] > -} - -/** Main production. */ -Node Start() : {} -{ - Expression() ";" - { return jjtThis; } -} - -/** An Expression. */ -void Expression() : {} -{ - AdditiveExpression() -} - -/** An Additive Expression. */ -void AdditiveExpression() : {} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -/** A Multiplicative Expression. */ -void MultiplicativeExpression() : {} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -/** A Unary Expression. */ -void UnaryExpression() : {} -{ - "(" Expression() ")" | Identifier() | Integer() -} - -/** An Identifier. */ -void Identifier() : {} -{ - -} - -/** An Integer. */ -void Integer() : {} -{ - -} - -TOKEN : -{ - < IDENTIFIER2 : ()* > -| - < #LETTER2 : - [ // all chars for which Character.isIdentifierStart is true - "$", - "A"-"Z", - "_", - "a"-"z", - "\u00a2"-"\u00a5", - "\u00aa", - "\u00b5", - "\u00ba", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u021f", - "\u0222"-"\u0233", - "\u0250"-"\u02ad", - "\u02b0"-"\u02b8", - "\u02bb"-"\u02c1", - "\u02d0"-"\u02d1", - "\u02e0"-"\u02e4", - "\u02ee", - "\u037a", - "\u0386", - "\u0388"-"\u038a", - "\u038c", - "\u038e"-"\u03a1", - "\u03a3"-"\u03ce", - "\u03d0"-"\u03d7", - "\u03da"-"\u03f3", - "\u0400"-"\u0481", - "\u048c"-"\u04c4", - "\u04c7"-"\u04c8", - "\u04cb"-"\u04cc", - "\u04d0"-"\u04f5", - "\u04f8"-"\u04f9", - "\u0531"-"\u0556", - "\u0559", - "\u0561"-"\u0587", - "\u05d0"-"\u05ea", - "\u05f0"-"\u05f2", - "\u0621"-"\u063a", - "\u0640"-"\u064a", - "\u0671"-"\u06d3", - "\u06d5", - "\u06e5"-"\u06e6", - "\u06fa"-"\u06fc", - "\u0710", - "\u0712"-"\u072c", - "\u0780"-"\u07a5", - "\u0905"-"\u0939", - "\u093d", - "\u0950", - "\u0958"-"\u0961", - "\u0985"-"\u098c", - "\u098f"-"\u0990", - "\u0993"-"\u09a8", - "\u09aa"-"\u09b0", - "\u09b2", - "\u09b6"-"\u09b9", - "\u09dc"-"\u09dd", - "\u09df"-"\u09e1", - "\u09f0"-"\u09f3", - "\u0a05"-"\u0a0a", - "\u0a0f"-"\u0a10", - "\u0a13"-"\u0a28", - "\u0a2a"-"\u0a30", - "\u0a32"-"\u0a33", - "\u0a35"-"\u0a36", - "\u0a38"-"\u0a39", - "\u0a59"-"\u0a5c", - "\u0a5e", - "\u0a72"-"\u0a74", - "\u0a85"-"\u0a8b", - "\u0a8d", - "\u0a8f"-"\u0a91", - "\u0a93"-"\u0aa8", - "\u0aaa"-"\u0ab0", - "\u0ab2"-"\u0ab3", - "\u0ab5"-"\u0ab9", - "\u0abd", - "\u0ad0", - "\u0ae0", - "\u0b05"-"\u0b0c", - "\u0b0f"-"\u0b10", - "\u0b13"-"\u0b28", - "\u0b2a"-"\u0b30", - "\u0b32"-"\u0b33", - "\u0b36"-"\u0b39", - "\u0b3d", - "\u0b5c"-"\u0b5d", - "\u0b5f"-"\u0b61", - "\u0b85"-"\u0b8a", - "\u0b8e"-"\u0b90", - "\u0b92"-"\u0b95", - "\u0b99"-"\u0b9a", - "\u0b9c", - "\u0b9e"-"\u0b9f", - "\u0ba3"-"\u0ba4", - "\u0ba8"-"\u0baa", - "\u0bae"-"\u0bb5", - "\u0bb7"-"\u0bb9", - "\u0c05"-"\u0c0c", - "\u0c0e"-"\u0c10", - "\u0c12"-"\u0c28", - "\u0c2a"-"\u0c33", - "\u0c35"-"\u0c39", - "\u0c60"-"\u0c61", - "\u0c85"-"\u0c8c", - "\u0c8e"-"\u0c90", - "\u0c92"-"\u0ca8", - "\u0caa"-"\u0cb3", - "\u0cb5"-"\u0cb9", - "\u0cde", - "\u0ce0"-"\u0ce1", - "\u0d05"-"\u0d0c", - "\u0d0e"-"\u0d10", - "\u0d12"-"\u0d28", - "\u0d2a"-"\u0d39", - "\u0d60"-"\u0d61", - "\u0d85"-"\u0d96", - "\u0d9a"-"\u0db1", - "\u0db3"-"\u0dbb", - "\u0dbd", - "\u0dc0"-"\u0dc6", - "\u0e01"-"\u0e30", - "\u0e32"-"\u0e33", - "\u0e3f"-"\u0e46", - "\u0e81"-"\u0e82", - "\u0e84", - "\u0e87"-"\u0e88", - "\u0e8a", - "\u0e8d", - "\u0e94"-"\u0e97", - "\u0e99"-"\u0e9f", - "\u0ea1"-"\u0ea3", - "\u0ea5", - "\u0ea7", - "\u0eaa"-"\u0eab", - "\u0ead"-"\u0eb0", - "\u0eb2"-"\u0eb3", - "\u0ebd", - "\u0ec0"-"\u0ec4", - "\u0ec6", - "\u0edc"-"\u0edd", - "\u0f00", - "\u0f40"-"\u0f47", - "\u0f49"-"\u0f6a", - "\u0f88"-"\u0f8b", - "\u1000"-"\u1021", - "\u1023"-"\u1027", - "\u1029"-"\u102a", - "\u1050"-"\u1055", - "\u10a0"-"\u10c5", - "\u10d0"-"\u10f6", - "\u1100"-"\u1159", - "\u115f"-"\u11a2", - "\u11a8"-"\u11f9", - "\u1200"-"\u1206", - "\u1208"-"\u1246", - "\u1248", - "\u124a"-"\u124d", - "\u1250"-"\u1256", - "\u1258", - "\u125a"-"\u125d", - "\u1260"-"\u1286", - "\u1288", - "\u128a"-"\u128d", - "\u1290"-"\u12ae", - "\u12b0", - "\u12b2"-"\u12b5", - "\u12b8"-"\u12be", - "\u12c0", - "\u12c2"-"\u12c5", - "\u12c8"-"\u12ce", - "\u12d0"-"\u12d6", - "\u12d8"-"\u12ee", - "\u12f0"-"\u130e", - "\u1310", - "\u1312"-"\u1315", - "\u1318"-"\u131e", - "\u1320"-"\u1346", - "\u1348"-"\u135a", - "\u13a0"-"\u13f4", - "\u1401"-"\u166c", - "\u166f"-"\u1676", - "\u1681"-"\u169a", - "\u16a0"-"\u16ea", - "\u1780"-"\u17b3", - "\u17db", - "\u1820"-"\u1877", - "\u1880"-"\u18a8", - "\u1e00"-"\u1e9b", - "\u1ea0"-"\u1ef9", - "\u1f00"-"\u1f15", - "\u1f18"-"\u1f1d", - "\u1f20"-"\u1f45", - "\u1f48"-"\u1f4d", - "\u1f50"-"\u1f57", - "\u1f59", - "\u1f5b", - "\u1f5d", - "\u1f5f"-"\u1f7d", - "\u1f80"-"\u1fb4", - "\u1fb6"-"\u1fbc", - "\u1fbe", - "\u1fc2"-"\u1fc4", - "\u1fc6"-"\u1fcc", - "\u1fd0"-"\u1fd3", - "\u1fd6"-"\u1fdb", - "\u1fe0"-"\u1fec", - "\u1ff2"-"\u1ff4", - "\u1ff6"-"\u1ffc", - "\u203f"-"\u2040", - "\u207f", - "\u20a0"-"\u20af", - "\u2102", - "\u2107", - "\u210a"-"\u2113", - "\u2115", - "\u2119"-"\u211d", - "\u2124", - "\u2126", - "\u2128", - "\u212a"-"\u212d", - "\u212f"-"\u2131", - "\u2133"-"\u2139", - "\u2160"-"\u2183", - "\u3005"-"\u3007", - "\u3021"-"\u3029", - "\u3031"-"\u3035", - "\u3038"-"\u303a", - "\u3041"-"\u3094", - "\u309d"-"\u309e", - "\u30a1"-"\u30fe", - "\u3105"-"\u312c", - "\u3131"-"\u318e", - "\u31a0"-"\u31b7", - "\u3400"-"\u4db5", - "\u4e00"-"\u9fa5", - "\ua000"-"\ua48c", - "\uac00"-"\ud7a3", - "\uf900"-"\ufa2d", - "\ufb00"-"\ufb06", - "\ufb13"-"\ufb17", - "\ufb1d", - "\ufb1f"-"\ufb28", - "\ufb2a"-"\ufb36", - "\ufb38"-"\ufb3c", - "\ufb3e", - "\ufb40"-"\ufb41", - "\ufb43"-"\ufb44", - "\ufb46"-"\ufbb1", - "\ufbd3"-"\ufd3d", - "\ufd50"-"\ufd8f", - "\ufd92"-"\ufdc7", - "\ufdf0"-"\ufdfb", - "\ufe33"-"\ufe34", - "\ufe4d"-"\ufe4f", - "\ufe69", - "\ufe70"-"\ufe72", - "\ufe74", - "\ufe76"-"\ufefc", - "\uff04", - "\uff21"-"\uff3a", - "\uff3f", - "\uff41"-"\uff5a", - "\uff65"-"\uffbe", - "\uffc2"-"\uffc7", - "\uffca"-"\uffcf", - "\uffd2"-"\uffd7", - "\uffda"-"\uffdc", - "\uffe0"-"\uffe1", - "\uffe5"-"\uffe6" - ] - > -| - < #PART_LETTER2 : - [ // all chars for which Character.isIdentifierPart is true - "\u0000"-"\u0008", - "\u000e"-"\u001b", - "$", - "0"-"9", - "A"-"Z", - "_", - "a"-"z", - "\u007f"-"\u009f", - "\u00a2"-"\u00a5", - "\u00aa", - "\u00b5", - "\u00ba", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u021f", - "\u0222"-"\u0233", - "\u0250"-"\u02ad", - "\u02b0"-"\u02b8", - "\u02bb"-"\u02c1", - "\u02d0"-"\u02d1", - "\u02e0"-"\u02e4", - "\u02ee", - "\u0300"-"\u034e", - "\u0360"-"\u0362", - "\u037a", - "\u0386", - "\u0388"-"\u038a", - "\u038c", - "\u038e"-"\u03a1", - "\u03a3"-"\u03ce", - "\u03d0"-"\u03d7", - "\u03da"-"\u03f3", - "\u0400"-"\u0481", - "\u0483"-"\u0486", - "\u048c"-"\u04c4", - "\u04c7"-"\u04c8", - "\u04cb"-"\u04cc", - "\u04d0"-"\u04f5", - "\u04f8"-"\u04f9", - "\u0531"-"\u0556", - "\u0559", - "\u0561"-"\u0587", - "\u0591"-"\u05a1", - "\u05a3"-"\u05b9", - "\u05bb"-"\u05bd", - "\u05bf", - "\u05c1"-"\u05c2", - "\u05c4", - "\u05d0"-"\u05ea", - "\u05f0"-"\u05f2", - "\u0621"-"\u063a", - "\u0640"-"\u0655", - "\u0660"-"\u0669", - "\u0670"-"\u06d3", - "\u06d5"-"\u06dc", - "\u06df"-"\u06e8", - "\u06ea"-"\u06ed", - "\u06f0"-"\u06fc", - "\u070f"-"\u072c", - "\u0730"-"\u074a", - "\u0780"-"\u07b0", - "\u0901"-"\u0903", - "\u0905"-"\u0939", - "\u093c"-"\u094d", - "\u0950"-"\u0954", - "\u0958"-"\u0963", - "\u0966"-"\u096f", - "\u0981"-"\u0983", - "\u0985"-"\u098c", - "\u098f"-"\u0990", - "\u0993"-"\u09a8", - "\u09aa"-"\u09b0", - "\u09b2", - "\u09b6"-"\u09b9", - "\u09bc", - "\u09be"-"\u09c4", - "\u09c7"-"\u09c8", - "\u09cb"-"\u09cd", - "\u09d7", - "\u09dc"-"\u09dd", - "\u09df"-"\u09e3", - "\u09e6"-"\u09f3", - "\u0a02", - "\u0a05"-"\u0a0a", - "\u0a0f"-"\u0a10", - "\u0a13"-"\u0a28", - "\u0a2a"-"\u0a30", - "\u0a32"-"\u0a33", - "\u0a35"-"\u0a36", - "\u0a38"-"\u0a39", - "\u0a3c", - "\u0a3e"-"\u0a42", - "\u0a47"-"\u0a48", - "\u0a4b"-"\u0a4d", - "\u0a59"-"\u0a5c", - "\u0a5e", - "\u0a66"-"\u0a74", - "\u0a81"-"\u0a83", - "\u0a85"-"\u0a8b", - "\u0a8d", - "\u0a8f"-"\u0a91", - "\u0a93"-"\u0aa8", - "\u0aaa"-"\u0ab0", - "\u0ab2"-"\u0ab3", - "\u0ab5"-"\u0ab9", - "\u0abc"-"\u0ac5", - "\u0ac7"-"\u0ac9", - "\u0acb"-"\u0acd", - "\u0ad0", - "\u0ae0", - "\u0ae6"-"\u0aef", - "\u0b01"-"\u0b03", - "\u0b05"-"\u0b0c", - "\u0b0f"-"\u0b10", - "\u0b13"-"\u0b28", - "\u0b2a"-"\u0b30", - "\u0b32"-"\u0b33", - "\u0b36"-"\u0b39", - "\u0b3c"-"\u0b43", - "\u0b47"-"\u0b48", - "\u0b4b"-"\u0b4d", - "\u0b56"-"\u0b57", - "\u0b5c"-"\u0b5d", - "\u0b5f"-"\u0b61", - "\u0b66"-"\u0b6f", - "\u0b82"-"\u0b83", - "\u0b85"-"\u0b8a", - "\u0b8e"-"\u0b90", - "\u0b92"-"\u0b95", - "\u0b99"-"\u0b9a", - "\u0b9c", - "\u0b9e"-"\u0b9f", - "\u0ba3"-"\u0ba4", - "\u0ba8"-"\u0baa", - "\u0bae"-"\u0bb5", - "\u0bb7"-"\u0bb9", - "\u0bbe"-"\u0bc2", - "\u0bc6"-"\u0bc8", - "\u0bca"-"\u0bcd", - "\u0bd7", - "\u0be7"-"\u0bef", - "\u0c01"-"\u0c03", - "\u0c05"-"\u0c0c", - "\u0c0e"-"\u0c10", - "\u0c12"-"\u0c28", - "\u0c2a"-"\u0c33", - "\u0c35"-"\u0c39", - "\u0c3e"-"\u0c44", - "\u0c46"-"\u0c48", - "\u0c4a"-"\u0c4d", - "\u0c55"-"\u0c56", - "\u0c60"-"\u0c61", - "\u0c66"-"\u0c6f", - "\u0c82"-"\u0c83", - "\u0c85"-"\u0c8c", - "\u0c8e"-"\u0c90", - "\u0c92"-"\u0ca8", - "\u0caa"-"\u0cb3", - "\u0cb5"-"\u0cb9", - "\u0cbe"-"\u0cc4", - "\u0cc6"-"\u0cc8", - "\u0cca"-"\u0ccd", - "\u0cd5"-"\u0cd6", - "\u0cde", - "\u0ce0"-"\u0ce1", - "\u0ce6"-"\u0cef", - "\u0d02"-"\u0d03", - "\u0d05"-"\u0d0c", - "\u0d0e"-"\u0d10", - "\u0d12"-"\u0d28", - "\u0d2a"-"\u0d39", - "\u0d3e"-"\u0d43", - "\u0d46"-"\u0d48", - "\u0d4a"-"\u0d4d", - "\u0d57", - "\u0d60"-"\u0d61", - "\u0d66"-"\u0d6f", - "\u0d82"-"\u0d83", - "\u0d85"-"\u0d96", - "\u0d9a"-"\u0db1", - "\u0db3"-"\u0dbb", - "\u0dbd", - "\u0dc0"-"\u0dc6", - "\u0dca", - "\u0dcf"-"\u0dd4", - "\u0dd6", - "\u0dd8"-"\u0ddf", - "\u0df2"-"\u0df3", - "\u0e01"-"\u0e3a", - "\u0e3f"-"\u0e4e", - "\u0e50"-"\u0e59", - "\u0e81"-"\u0e82", - "\u0e84", - "\u0e87"-"\u0e88", - "\u0e8a", - "\u0e8d", - "\u0e94"-"\u0e97", - "\u0e99"-"\u0e9f", - "\u0ea1"-"\u0ea3", - "\u0ea5", - "\u0ea7", - "\u0eaa"-"\u0eab", - "\u0ead"-"\u0eb9", - "\u0ebb"-"\u0ebd", - "\u0ec0"-"\u0ec4", - "\u0ec6", - "\u0ec8"-"\u0ecd", - "\u0ed0"-"\u0ed9", - "\u0edc"-"\u0edd", - "\u0f00", - "\u0f18"-"\u0f19", - "\u0f20"-"\u0f29", - "\u0f35", - "\u0f37", - "\u0f39", - "\u0f3e"-"\u0f47", - "\u0f49"-"\u0f6a", - "\u0f71"-"\u0f84", - "\u0f86"-"\u0f8b", - "\u0f90"-"\u0f97", - "\u0f99"-"\u0fbc", - "\u0fc6", - "\u1000"-"\u1021", - "\u1023"-"\u1027", - "\u1029"-"\u102a", - "\u102c"-"\u1032", - "\u1036"-"\u1039", - "\u1040"-"\u1049", - "\u1050"-"\u1059", - "\u10a0"-"\u10c5", - "\u10d0"-"\u10f6", - "\u1100"-"\u1159", - "\u115f"-"\u11a2", - "\u11a8"-"\u11f9", - "\u1200"-"\u1206", - "\u1208"-"\u1246", - "\u1248", - "\u124a"-"\u124d", - "\u1250"-"\u1256", - "\u1258", - "\u125a"-"\u125d", - "\u1260"-"\u1286", - "\u1288", - "\u128a"-"\u128d", - "\u1290"-"\u12ae", - "\u12b0", - "\u12b2"-"\u12b5", - "\u12b8"-"\u12be", - "\u12c0", - "\u12c2"-"\u12c5", - "\u12c8"-"\u12ce", - "\u12d0"-"\u12d6", - "\u12d8"-"\u12ee", - "\u12f0"-"\u130e", - "\u1310", - "\u1312"-"\u1315", - "\u1318"-"\u131e", - "\u1320"-"\u1346", - "\u1348"-"\u135a", - "\u1369"-"\u1371", - "\u13a0"-"\u13f4", - "\u1401"-"\u166c", - "\u166f"-"\u1676", - "\u1681"-"\u169a", - "\u16a0"-"\u16ea", - "\u1780"-"\u17d3", - "\u17db", - "\u17e0"-"\u17e9", - "\u180b"-"\u180e", - "\u1810"-"\u1819", - "\u1820"-"\u1877", - "\u1880"-"\u18a9", - "\u1e00"-"\u1e9b", - "\u1ea0"-"\u1ef9", - "\u1f00"-"\u1f15", - "\u1f18"-"\u1f1d", - "\u1f20"-"\u1f45", - "\u1f48"-"\u1f4d", - "\u1f50"-"\u1f57", - "\u1f59", - "\u1f5b", - "\u1f5d", - "\u1f5f"-"\u1f7d", - "\u1f80"-"\u1fb4", - "\u1fb6"-"\u1fbc", - "\u1fbe", - "\u1fc2"-"\u1fc4", - "\u1fc6"-"\u1fcc", - "\u1fd0"-"\u1fd3", - "\u1fd6"-"\u1fdb", - "\u1fe0"-"\u1fec", - "\u1ff2"-"\u1ff4", - "\u1ff6"-"\u1ffc", - "\u200c"-"\u200f", - "\u202a"-"\u202e", - "\u203f"-"\u2040", - "\u206a"-"\u206f", - "\u207f", - "\u20a0"-"\u20af", - "\u20d0"-"\u20dc", - "\u20e1", - "\u2102", - "\u2107", - "\u210a"-"\u2113", - "\u2115", - "\u2119"-"\u211d", - "\u2124", - "\u2126", - "\u2128", - "\u212a"-"\u212d", - "\u212f"-"\u2131", - "\u2133"-"\u2139", - "\u2160"-"\u2183", - "\u3005"-"\u3007", - "\u3021"-"\u302f", - "\u3031"-"\u3035", - "\u3038"-"\u303a", - "\u3041"-"\u3094", - "\u3099"-"\u309a", - "\u309d"-"\u309e", - "\u30a1"-"\u30fe", - "\u3105"-"\u312c", - "\u3131"-"\u318e", - "\u31a0"-"\u31b7", - "\u3400"-"\u4db5", - "\u4e00"-"\u9fa5", - "\ua000"-"\ua48c", - "\uac00"-"\ud7a3", - "\uf900"-"\ufa2d", - "\ufb00"-"\ufb06", - "\ufb13"-"\ufb17", - "\ufb1d"-"\ufb28", - "\ufb2a"-"\ufb36", - "\ufb38"-"\ufb3c", - "\ufb3e", - "\ufb40"-"\ufb41", - "\ufb43"-"\ufb44", - "\ufb46"-"\ufbb1", - "\ufbd3"-"\ufd3d", - "\ufd50"-"\ufd8f", - "\ufd92"-"\ufdc7", - "\ufdf0"-"\ufdfb", - "\ufe20"-"\ufe23", - "\ufe33"-"\ufe34", - "\ufe4d"-"\ufe4f", - "\ufe69", - "\ufe70"-"\ufe72", - "\ufe74", - "\ufe76"-"\ufefc", - "\ufeff", - "\uff04", - "\uff10"-"\uff19", - "\uff21"-"\uff3a", - "\uff3f", - "\uff41"-"\uff5a", - "\uff65"-"\uffbe", - "\uffc2"-"\uffc7", - "\uffca"-"\uffcf", - "\uffd2"-"\uffd7", - "\uffda"-"\uffdc", - "\uffe0"-"\uffe1", - "\uffe5"-"\uffe6", - "\ufff9"-"\ufffb" - ] - > -} - diff --git a/examples/JJTree/src/main/jjtree/eg2.jjt b/examples/JJTree/src/main/jjtree/eg2.jjt deleted file mode 100644 index 6cc6c39..0000000 --- a/examples/JJTree/src/main/jjtree/eg2.jjt +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - KEEP_LINE_COLUMN = false; - - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; - NODE_PACKAGE = "eg2"; -} - -PARSER_BEGIN(Eg2) -package eg2; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** An Arithmetic Grammar. */ -public class Eg2 { - - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; - input = new FileInputStream(args[0]); - prevOutput = output; - output = new PrintStream(args[1]); - prevError = error; - error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - Eg2 t = new Eg2(input); - try { - ASTStart n = t.Start(); - n.dump(""); - System.out.println("Thank you."); - } catch (Exception e) { - error.println("Oops."); - error.println(e.getMessage()); - e.printStackTrace(); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} - -PARSER_END(Eg2) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| <"//" (~["\n","\r"])* ("\n"|"\r"|"\r\n")> -| <"/*" (~["*"])* "*" (~["/"] (~["*"])* "*")* "/"> -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: ["_","a"-"z","A"-"Z"] > -| - < #DIGIT: ["0"-"9"] > -} - -/** Main production. */ -ASTStart Start() : {} -{ - Expression() ";" - { return jjtThis; } -} - -/** An Expression. */ -void Expression() #void : {} -{ - AdditiveExpression() -} - -/** An Additive Expression. */ -void AdditiveExpression() #void : {} -{ - ( - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* - ) #Add(>1) -} - -/** A Multiplicative Expression. */ -void MultiplicativeExpression() #void : {} -{ - ( - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* - ) #Mult(>1) -} - -/** A Unary Expression. */ -void UnaryExpression() #void : {} -{ - "(" Expression() ")" | MyID() | Integer() -} - -/** An Identifier. */ -void MyID() : -{ - Token t; -} -{ - t= - { - jjtThis.setName(t.image); - } -} - -/** An Integer. */ -void Integer() : {} -{ - -} diff --git a/examples/JJTree/src/main/jjtree/eg3.jjt b/examples/JJTree/src/main/jjtree/eg3.jjt deleted file mode 100644 index b135a54..0000000 --- a/examples/JJTree/src/main/jjtree/eg3.jjt +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; - NODE_DEFAULT_VOID = true; - NODE_PACKAGE = "eg3"; - SINGLE_TREE_FILE = false; -} - -PARSER_BEGIN(Eg3) -package eg3; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** An Arithmetic Grammar. */ -public class Eg3 { - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; - input = new FileInputStream(args[0]); - prevOutput = output; - output = new PrintStream(args[1]); - prevError = error; - error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - Eg3 t = new Eg3(input); - try { - ASTStart n = t.Start(); - n.dump(""); - output.println("Thank you."); - } catch (Exception e) { - error.println("Oops."); - error.println(e.getMessage()); - e.printStackTrace(); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} - -PARSER_END(Eg3) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| <"//" (~["\n","\r"])* ("\n"|"\r"|"\r\n")> -| <"/*" (~["*"])* "*" (~["/"] (~["*"])* "*")* "/"> -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: ["_","a"-"z","A"-"Z"] > -| - < #DIGIT: ["0"-"9"] > -} - -/** Main production. */ -ASTStart Start() #Start : {} -{ - Expression() ";" - { return jjtThis; } -} - -/** An Expression. */ -void Expression() : {} -{ - AdditiveExpression() -} - -/** An Additive Expression. */ -void AdditiveExpression() : {} -{ - ( - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* - ) #Add(>1) -} - -/** A Multiplicative Expression. */ -void MultiplicativeExpression() : {} -{ - ( - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* - ) #Mult(>1) -} - -/** A Unary Expression. */ -void UnaryExpression() : {} -{ - "(" Expression() ")" | Identifier() | Integer() -} - -/** An Identifier. */ -void Identifier() #MyID : -{ - Token t; -} -{ - t= - { - jjtThis.setName(t.image); - } -} - -/** An Integer. */ -void Integer() #Integer : {} -{ - -} diff --git a/examples/JJTree/src/main/jjtree/eg4.jjt b/examples/JJTree/src/main/jjtree/eg4.jjt deleted file mode 100644 index c35dc0d..0000000 --- a/examples/JJTree/src/main/jjtree/eg4.jjt +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options -{ - STATIC = false; - - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; - NODE_DEFAULT_VOID = true; - NODE_PACKAGE = "eg4"; - VISITOR = true; -// VISITOR_EXCEPTION = "MyVisException"; // test -} - -PARSER_BEGIN(Eg4) -package eg4; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** An Arithmetic Grammar. */ -public class Eg4 { - - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; input = new FileInputStream(args[0]); - prevOutput = output; output = new PrintStream(args[1]); - prevError = error; error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - Eg4 t = new Eg4(input); - try { - ASTStart n = t.Start(); - Eg4Visitor v = new Eg4DumpVisitor(); - n.jjtAccept(v, null); - output.println("Thank you."); - } catch (Exception e) { - error.println("Oops."); - error.println(e.getMessage()); - e.printStackTrace(); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } -} - -PARSER_END(Eg4) - - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| <"//" (~["\n","\r"])* ("\n"|"\r"|"\r\n")> -| <"/*" (~["*"])* "*" (~["/"] (~["*"])* "*")* "/"> -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: ["_","a"-"z","A"-"Z"] > -| - < #DIGIT: ["0"-"9"] > -} - -/** Main production. */ -ASTStart Start() #Start : {} -{ - Expression() ";" - { return jjtThis; } -} - - -/** An Expression. */ -void Expression() : {} -{ - AdditiveExpression() -} - -/** An Additive Expression. */ -void AdditiveExpression() : {} -{ - ( - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* - ) #Add(>1) -} - -/** A Multiplicative Expression. */ -void MultiplicativeExpression() : {} -{ - ( - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* - ) #Mult(>1) -} - -/** A Unary Expression. */ -void UnaryExpression() : {} -{ - "(" Expression() ")" | Identifier() | Integer() -} - -/** An Identifier. */ -void Identifier() #MyOtherID : -{ - Token t; -} -{ - t= - { - jjtThis.setName(t.image); - } -} - -/** An Integer. */ -void Integer() #Integer : {} -{ - -} diff --git a/examples/JavaCC/Java1.5.jj b/examples/JavaCC/Java1.5.jj deleted file mode 100644 index 28e40cb..0000000 --- a/examples/JavaCC/Java1.5.jj +++ /dev/null @@ -1,2113 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -options { - JAVA_UNICODE_ESCAPE = true; - ERROR_REPORTING = false; - STATIC = false; - COMMON_TOKEN_ACTION = false; - TOKEN_FACTORY = "MyToken"; - JDK_VERSION = "1.5"; -} - -PARSER_BEGIN(JavaParser) - -import java.io.*; - -/** - * Grammar to parse Java version 1.5 - * @author Sreenivasa Viswanadha - Simplified and enhanced for 1.5 - */ -public class JavaParser -{ - /** - * Class to hold modifiers. - */ - static public final class ModifierSet - { - /* Definitions of the bits in the modifiers field. */ - public static final int PUBLIC = 0x0001; - public static final int PROTECTED = 0x0002; - public static final int PRIVATE = 0x0004; - public static final int ABSTRACT = 0x0008; - public static final int STATIC = 0x0010; - public static final int FINAL = 0x0020; - public static final int SYNCHRONIZED = 0x0040; - public static final int NATIVE = 0x0080; - public static final int TRANSIENT = 0x0100; - public static final int VOLATILE = 0x0200; - public static final int STRICTFP = 0x1000; - - /** A set of accessors that indicate whether the specified modifier - is in the set. */ - - public boolean isPublic(int modifiers) - { - return (modifiers & PUBLIC) != 0; - } - - public boolean isProtected(int modifiers) - { - return (modifiers & PROTECTED) != 0; - } - - public boolean isPrivate(int modifiers) - { - return (modifiers & PRIVATE) != 0; - } - - public boolean isStatic(int modifiers) - { - return (modifiers & STATIC) != 0; - } - - public boolean isAbstract(int modifiers) - { - return (modifiers & ABSTRACT) != 0; - } - - public boolean isFinal(int modifiers) - { - return (modifiers & FINAL) != 0; - } - - public boolean isNative(int modifiers) - { - return (modifiers & NATIVE) != 0; - } - - public boolean isStrictfp(int modifiers) - { - return (modifiers & STRICTFP) != 0; - } - - public boolean isSynchronized(int modifiers) - { - return (modifiers & SYNCHRONIZED) != 0; - } - - public boolean isTransient(int modifiers) - { - return (modifiers & TRANSIENT) != 0; - } - - public boolean isVolatile(int modifiers) - { - return (modifiers & VOLATILE) != 0; - } - - /** - * Removes the given modifier. - */ - static int removeModifier(int modifiers, int mod) - { - return modifiers & ~mod; - } - } - - public JavaParser(String fileName) - { - this(System.in); - try { ReInit(new FileInputStream(new File(fileName))); } - catch(Exception e) { e.printStackTrace(); } - } - - public static void main(String args[]) { - JavaParser parser; - if (args.length == 0) { - System.out.println("Java Parser Version 1.1: Reading from standard input . . ."); - parser = new JavaParser(System.in); - } else if (args.length == 1) { - System.out.println("Java Parser Version 1.1: Reading from file " + args[0] + " . . ."); - try { - parser = new JavaParser(new java.io.FileInputStream(args[0])); - } catch (java.io.FileNotFoundException e) { - System.out.println("Java Parser Version 1.1: File " + args[0] + " not found."); - return; - } - } else { - System.out.println("Java Parser Version 1.1: Usage is one of:"); - System.out.println(" java JavaParser < inputfile"); - System.out.println("OR"); - System.out.println(" java JavaParser inputfile"); - return; - } - try { - parser.CompilationUnit(); - System.out.println("Java Parser Version 1.1: Java program parsed successfully."); - } catch (ParseException e) { - System.out.println(e.getMessage()); - System.out.println("Java Parser Version 1.1: Encountered errors during parse."); - } - } - -} - -PARSER_END(JavaParser) - -/* WHITE SPACE */ - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -/* COMMENTS */ - -MORE : -{ - <"/**" ~["/"]> { input_stream.backup(1); } : IN_FORMAL_COMMENT -| - "/*" : IN_MULTI_LINE_COMMENT -} - -SPECIAL_TOKEN : -{ - -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -MORE : -{ - < ~[] > -} - -/* RESERVED WORDS AND LITERALS */ - -TOKEN : -{ - < ABSTRACT: "abstract" > -| < ASSERT: "assert" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < ENUM: "enum" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < STRICTFP: "strictfp" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -/* LITERALS */ - -TOKEN : -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -| - < FLOATING_POINT_LITERAL: - - | - > -| - < #DECIMAL_FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? (["f","F","d","D"])? - | "." (["0"-"9"])+ ()? (["f","F","d","D"])? - | (["0"-"9"])+ (["f","F","d","D"])? - | (["0"-"9"])+ ()? ["f","F","d","D"] - > -| - < #DECIMAL_EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ > -| - < #HEXADECIMAL_FLOATING_POINT_LITERAL: - "0" ["x", "X"] (["0"-"9","a"-"f","A"-"F"])+ (".")? (["f","F","d","D"])? - | "0" ["x", "X"] (["0"-"9","a"-"f","A"-"F"])* "." (["0"-"9","a"-"f","A"-"F"])+ (["f","F","d","D"])? - > -| - < #HEXADECIMAL_EXPONENT: ["p","P"] (["+","-"])? (["0"-"9"])+ > -| - < CHARACTER_LITERAL: - "'" - ( (~["'","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - ) - "'" - > -| - < STRING_LITERAL: - "\"" - ( (~["\"","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - )* - "\"" - > -} - -/* IDENTIFIERS */ - -TOKEN : -{ - < IDENTIFIER: ()* > -| - < #LETTER: - [ // all chars for which Character.isIdentifierStart is true - "$", - "A"-"Z", - "_", - "a"-"z", - "\u00a2"-"\u00a5", - "\u00aa", - "\u00b5", - "\u00ba", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u021f", - "\u0222"-"\u0233", - "\u0250"-"\u02ad", - "\u02b0"-"\u02b8", - "\u02bb"-"\u02c1", - "\u02d0"-"\u02d1", - "\u02e0"-"\u02e4", - "\u02ee", - "\u037a", - "\u0386", - "\u0388"-"\u038a", - "\u038c", - "\u038e"-"\u03a1", - "\u03a3"-"\u03ce", - "\u03d0"-"\u03d7", - "\u03da"-"\u03f3", - "\u0400"-"\u0481", - "\u048c"-"\u04c4", - "\u04c7"-"\u04c8", - "\u04cb"-"\u04cc", - "\u04d0"-"\u04f5", - "\u04f8"-"\u04f9", - "\u0531"-"\u0556", - "\u0559", - "\u0561"-"\u0587", - "\u05d0"-"\u05ea", - "\u05f0"-"\u05f2", - "\u0621"-"\u063a", - "\u0640"-"\u064a", - "\u0671"-"\u06d3", - "\u06d5", - "\u06e5"-"\u06e6", - "\u06fa"-"\u06fc", - "\u0710", - "\u0712"-"\u072c", - "\u0780"-"\u07a5", - "\u0905"-"\u0939", - "\u093d", - "\u0950", - "\u0958"-"\u0961", - "\u0985"-"\u098c", - "\u098f"-"\u0990", - "\u0993"-"\u09a8", - "\u09aa"-"\u09b0", - "\u09b2", - "\u09b6"-"\u09b9", - "\u09dc"-"\u09dd", - "\u09df"-"\u09e1", - "\u09f0"-"\u09f3", - "\u0a05"-"\u0a0a", - "\u0a0f"-"\u0a10", - "\u0a13"-"\u0a28", - "\u0a2a"-"\u0a30", - "\u0a32"-"\u0a33", - "\u0a35"-"\u0a36", - "\u0a38"-"\u0a39", - "\u0a59"-"\u0a5c", - "\u0a5e", - "\u0a72"-"\u0a74", - "\u0a85"-"\u0a8b", - "\u0a8d", - "\u0a8f"-"\u0a91", - "\u0a93"-"\u0aa8", - "\u0aaa"-"\u0ab0", - "\u0ab2"-"\u0ab3", - "\u0ab5"-"\u0ab9", - "\u0abd", - "\u0ad0", - "\u0ae0", - "\u0b05"-"\u0b0c", - "\u0b0f"-"\u0b10", - "\u0b13"-"\u0b28", - "\u0b2a"-"\u0b30", - "\u0b32"-"\u0b33", - "\u0b36"-"\u0b39", - "\u0b3d", - "\u0b5c"-"\u0b5d", - "\u0b5f"-"\u0b61", - "\u0b85"-"\u0b8a", - "\u0b8e"-"\u0b90", - "\u0b92"-"\u0b95", - "\u0b99"-"\u0b9a", - "\u0b9c", - "\u0b9e"-"\u0b9f", - "\u0ba3"-"\u0ba4", - "\u0ba8"-"\u0baa", - "\u0bae"-"\u0bb5", - "\u0bb7"-"\u0bb9", - "\u0c05"-"\u0c0c", - "\u0c0e"-"\u0c10", - "\u0c12"-"\u0c28", - "\u0c2a"-"\u0c33", - "\u0c35"-"\u0c39", - "\u0c60"-"\u0c61", - "\u0c85"-"\u0c8c", - "\u0c8e"-"\u0c90", - "\u0c92"-"\u0ca8", - "\u0caa"-"\u0cb3", - "\u0cb5"-"\u0cb9", - "\u0cde", - "\u0ce0"-"\u0ce1", - "\u0d05"-"\u0d0c", - "\u0d0e"-"\u0d10", - "\u0d12"-"\u0d28", - "\u0d2a"-"\u0d39", - "\u0d60"-"\u0d61", - "\u0d85"-"\u0d96", - "\u0d9a"-"\u0db1", - "\u0db3"-"\u0dbb", - "\u0dbd", - "\u0dc0"-"\u0dc6", - "\u0e01"-"\u0e30", - "\u0e32"-"\u0e33", - "\u0e3f"-"\u0e46", - "\u0e81"-"\u0e82", - "\u0e84", - "\u0e87"-"\u0e88", - "\u0e8a", - "\u0e8d", - "\u0e94"-"\u0e97", - "\u0e99"-"\u0e9f", - "\u0ea1"-"\u0ea3", - "\u0ea5", - "\u0ea7", - "\u0eaa"-"\u0eab", - "\u0ead"-"\u0eb0", - "\u0eb2"-"\u0eb3", - "\u0ebd", - "\u0ec0"-"\u0ec4", - "\u0ec6", - "\u0edc"-"\u0edd", - "\u0f00", - "\u0f40"-"\u0f47", - "\u0f49"-"\u0f6a", - "\u0f88"-"\u0f8b", - "\u1000"-"\u1021", - "\u1023"-"\u1027", - "\u1029"-"\u102a", - "\u1050"-"\u1055", - "\u10a0"-"\u10c5", - "\u10d0"-"\u10f6", - "\u1100"-"\u1159", - "\u115f"-"\u11a2", - "\u11a8"-"\u11f9", - "\u1200"-"\u1206", - "\u1208"-"\u1246", - "\u1248", - "\u124a"-"\u124d", - "\u1250"-"\u1256", - "\u1258", - "\u125a"-"\u125d", - "\u1260"-"\u1286", - "\u1288", - "\u128a"-"\u128d", - "\u1290"-"\u12ae", - "\u12b0", - "\u12b2"-"\u12b5", - "\u12b8"-"\u12be", - "\u12c0", - "\u12c2"-"\u12c5", - "\u12c8"-"\u12ce", - "\u12d0"-"\u12d6", - "\u12d8"-"\u12ee", - "\u12f0"-"\u130e", - "\u1310", - "\u1312"-"\u1315", - "\u1318"-"\u131e", - "\u1320"-"\u1346", - "\u1348"-"\u135a", - "\u13a0"-"\u13f4", - "\u1401"-"\u166c", - "\u166f"-"\u1676", - "\u1681"-"\u169a", - "\u16a0"-"\u16ea", - "\u1780"-"\u17b3", - "\u17db", - "\u1820"-"\u1877", - "\u1880"-"\u18a8", - "\u1e00"-"\u1e9b", - "\u1ea0"-"\u1ef9", - "\u1f00"-"\u1f15", - "\u1f18"-"\u1f1d", - "\u1f20"-"\u1f45", - "\u1f48"-"\u1f4d", - "\u1f50"-"\u1f57", - "\u1f59", - "\u1f5b", - "\u1f5d", - "\u1f5f"-"\u1f7d", - "\u1f80"-"\u1fb4", - "\u1fb6"-"\u1fbc", - "\u1fbe", - "\u1fc2"-"\u1fc4", - "\u1fc6"-"\u1fcc", - "\u1fd0"-"\u1fd3", - "\u1fd6"-"\u1fdb", - "\u1fe0"-"\u1fec", - "\u1ff2"-"\u1ff4", - "\u1ff6"-"\u1ffc", - "\u203f"-"\u2040", - "\u207f", - "\u20a0"-"\u20af", - "\u2102", - "\u2107", - "\u210a"-"\u2113", - "\u2115", - "\u2119"-"\u211d", - "\u2124", - "\u2126", - "\u2128", - "\u212a"-"\u212d", - "\u212f"-"\u2131", - "\u2133"-"\u2139", - "\u2160"-"\u2183", - "\u3005"-"\u3007", - "\u3021"-"\u3029", - "\u3031"-"\u3035", - "\u3038"-"\u303a", - "\u3041"-"\u3094", - "\u309d"-"\u309e", - "\u30a1"-"\u30fe", - "\u3105"-"\u312c", - "\u3131"-"\u318e", - "\u31a0"-"\u31b7", - "\u3400"-"\u4db5", - "\u4e00"-"\u9fa5", - "\ua000"-"\ua48c", - "\uac00"-"\ud7a3", - "\uf900"-"\ufa2d", - "\ufb00"-"\ufb06", - "\ufb13"-"\ufb17", - "\ufb1d", - "\ufb1f"-"\ufb28", - "\ufb2a"-"\ufb36", - "\ufb38"-"\ufb3c", - "\ufb3e", - "\ufb40"-"\ufb41", - "\ufb43"-"\ufb44", - "\ufb46"-"\ufbb1", - "\ufbd3"-"\ufd3d", - "\ufd50"-"\ufd8f", - "\ufd92"-"\ufdc7", - "\ufdf0"-"\ufdfb", - "\ufe33"-"\ufe34", - "\ufe4d"-"\ufe4f", - "\ufe69", - "\ufe70"-"\ufe72", - "\ufe74", - "\ufe76"-"\ufefc", - "\uff04", - "\uff21"-"\uff3a", - "\uff3f", - "\uff41"-"\uff5a", - "\uff65"-"\uffbe", - "\uffc2"-"\uffc7", - "\uffca"-"\uffcf", - "\uffd2"-"\uffd7", - "\uffda"-"\uffdc", - "\uffe0"-"\uffe1", - "\uffe5"-"\uffe6" - ] - > -| - < #PART_LETTER: - [ // all chars for which Character.isIdentifierPart is true - "\u0000"-"\u0008", - "\u000e"-"\u001b", - "$", - "0"-"9", - "A"-"Z", - "_", - "a"-"z", - "\u007f"-"\u009f", - "\u00a2"-"\u00a5", - "\u00aa", - "\u00b5", - "\u00ba", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u021f", - "\u0222"-"\u0233", - "\u0250"-"\u02ad", - "\u02b0"-"\u02b8", - "\u02bb"-"\u02c1", - "\u02d0"-"\u02d1", - "\u02e0"-"\u02e4", - "\u02ee", - "\u0300"-"\u034e", - "\u0360"-"\u0362", - "\u037a", - "\u0386", - "\u0388"-"\u038a", - "\u038c", - "\u038e"-"\u03a1", - "\u03a3"-"\u03ce", - "\u03d0"-"\u03d7", - "\u03da"-"\u03f3", - "\u0400"-"\u0481", - "\u0483"-"\u0486", - "\u048c"-"\u04c4", - "\u04c7"-"\u04c8", - "\u04cb"-"\u04cc", - "\u04d0"-"\u04f5", - "\u04f8"-"\u04f9", - "\u0531"-"\u0556", - "\u0559", - "\u0561"-"\u0587", - "\u0591"-"\u05a1", - "\u05a3"-"\u05b9", - "\u05bb"-"\u05bd", - "\u05bf", - "\u05c1"-"\u05c2", - "\u05c4", - "\u05d0"-"\u05ea", - "\u05f0"-"\u05f2", - "\u0621"-"\u063a", - "\u0640"-"\u0655", - "\u0660"-"\u0669", - "\u0670"-"\u06d3", - "\u06d5"-"\u06dc", - "\u06df"-"\u06e8", - "\u06ea"-"\u06ed", - "\u06f0"-"\u06fc", - "\u070f"-"\u072c", - "\u0730"-"\u074a", - "\u0780"-"\u07b0", - "\u0901"-"\u0903", - "\u0905"-"\u0939", - "\u093c"-"\u094d", - "\u0950"-"\u0954", - "\u0958"-"\u0963", - "\u0966"-"\u096f", - "\u0981"-"\u0983", - "\u0985"-"\u098c", - "\u098f"-"\u0990", - "\u0993"-"\u09a8", - "\u09aa"-"\u09b0", - "\u09b2", - "\u09b6"-"\u09b9", - "\u09bc", - "\u09be"-"\u09c4", - "\u09c7"-"\u09c8", - "\u09cb"-"\u09cd", - "\u09d7", - "\u09dc"-"\u09dd", - "\u09df"-"\u09e3", - "\u09e6"-"\u09f3", - "\u0a02", - "\u0a05"-"\u0a0a", - "\u0a0f"-"\u0a10", - "\u0a13"-"\u0a28", - "\u0a2a"-"\u0a30", - "\u0a32"-"\u0a33", - "\u0a35"-"\u0a36", - "\u0a38"-"\u0a39", - "\u0a3c", - "\u0a3e"-"\u0a42", - "\u0a47"-"\u0a48", - "\u0a4b"-"\u0a4d", - "\u0a59"-"\u0a5c", - "\u0a5e", - "\u0a66"-"\u0a74", - "\u0a81"-"\u0a83", - "\u0a85"-"\u0a8b", - "\u0a8d", - "\u0a8f"-"\u0a91", - "\u0a93"-"\u0aa8", - "\u0aaa"-"\u0ab0", - "\u0ab2"-"\u0ab3", - "\u0ab5"-"\u0ab9", - "\u0abc"-"\u0ac5", - "\u0ac7"-"\u0ac9", - "\u0acb"-"\u0acd", - "\u0ad0", - "\u0ae0", - "\u0ae6"-"\u0aef", - "\u0b01"-"\u0b03", - "\u0b05"-"\u0b0c", - "\u0b0f"-"\u0b10", - "\u0b13"-"\u0b28", - "\u0b2a"-"\u0b30", - "\u0b32"-"\u0b33", - "\u0b36"-"\u0b39", - "\u0b3c"-"\u0b43", - "\u0b47"-"\u0b48", - "\u0b4b"-"\u0b4d", - "\u0b56"-"\u0b57", - "\u0b5c"-"\u0b5d", - "\u0b5f"-"\u0b61", - "\u0b66"-"\u0b6f", - "\u0b82"-"\u0b83", - "\u0b85"-"\u0b8a", - "\u0b8e"-"\u0b90", - "\u0b92"-"\u0b95", - "\u0b99"-"\u0b9a", - "\u0b9c", - "\u0b9e"-"\u0b9f", - "\u0ba3"-"\u0ba4", - "\u0ba8"-"\u0baa", - "\u0bae"-"\u0bb5", - "\u0bb7"-"\u0bb9", - "\u0bbe"-"\u0bc2", - "\u0bc6"-"\u0bc8", - "\u0bca"-"\u0bcd", - "\u0bd7", - "\u0be7"-"\u0bef", - "\u0c01"-"\u0c03", - "\u0c05"-"\u0c0c", - "\u0c0e"-"\u0c10", - "\u0c12"-"\u0c28", - "\u0c2a"-"\u0c33", - "\u0c35"-"\u0c39", - "\u0c3e"-"\u0c44", - "\u0c46"-"\u0c48", - "\u0c4a"-"\u0c4d", - "\u0c55"-"\u0c56", - "\u0c60"-"\u0c61", - "\u0c66"-"\u0c6f", - "\u0c82"-"\u0c83", - "\u0c85"-"\u0c8c", - "\u0c8e"-"\u0c90", - "\u0c92"-"\u0ca8", - "\u0caa"-"\u0cb3", - "\u0cb5"-"\u0cb9", - "\u0cbe"-"\u0cc4", - "\u0cc6"-"\u0cc8", - "\u0cca"-"\u0ccd", - "\u0cd5"-"\u0cd6", - "\u0cde", - "\u0ce0"-"\u0ce1", - "\u0ce6"-"\u0cef", - "\u0d02"-"\u0d03", - "\u0d05"-"\u0d0c", - "\u0d0e"-"\u0d10", - "\u0d12"-"\u0d28", - "\u0d2a"-"\u0d39", - "\u0d3e"-"\u0d43", - "\u0d46"-"\u0d48", - "\u0d4a"-"\u0d4d", - "\u0d57", - "\u0d60"-"\u0d61", - "\u0d66"-"\u0d6f", - "\u0d82"-"\u0d83", - "\u0d85"-"\u0d96", - "\u0d9a"-"\u0db1", - "\u0db3"-"\u0dbb", - "\u0dbd", - "\u0dc0"-"\u0dc6", - "\u0dca", - "\u0dcf"-"\u0dd4", - "\u0dd6", - "\u0dd8"-"\u0ddf", - "\u0df2"-"\u0df3", - "\u0e01"-"\u0e3a", - "\u0e3f"-"\u0e4e", - "\u0e50"-"\u0e59", - "\u0e81"-"\u0e82", - "\u0e84", - "\u0e87"-"\u0e88", - "\u0e8a", - "\u0e8d", - "\u0e94"-"\u0e97", - "\u0e99"-"\u0e9f", - "\u0ea1"-"\u0ea3", - "\u0ea5", - "\u0ea7", - "\u0eaa"-"\u0eab", - "\u0ead"-"\u0eb9", - "\u0ebb"-"\u0ebd", - "\u0ec0"-"\u0ec4", - "\u0ec6", - "\u0ec8"-"\u0ecd", - "\u0ed0"-"\u0ed9", - "\u0edc"-"\u0edd", - "\u0f00", - "\u0f18"-"\u0f19", - "\u0f20"-"\u0f29", - "\u0f35", - "\u0f37", - "\u0f39", - "\u0f3e"-"\u0f47", - "\u0f49"-"\u0f6a", - "\u0f71"-"\u0f84", - "\u0f86"-"\u0f8b", - "\u0f90"-"\u0f97", - "\u0f99"-"\u0fbc", - "\u0fc6", - "\u1000"-"\u1021", - "\u1023"-"\u1027", - "\u1029"-"\u102a", - "\u102c"-"\u1032", - "\u1036"-"\u1039", - "\u1040"-"\u1049", - "\u1050"-"\u1059", - "\u10a0"-"\u10c5", - "\u10d0"-"\u10f6", - "\u1100"-"\u1159", - "\u115f"-"\u11a2", - "\u11a8"-"\u11f9", - "\u1200"-"\u1206", - "\u1208"-"\u1246", - "\u1248", - "\u124a"-"\u124d", - "\u1250"-"\u1256", - "\u1258", - "\u125a"-"\u125d", - "\u1260"-"\u1286", - "\u1288", - "\u128a"-"\u128d", - "\u1290"-"\u12ae", - "\u12b0", - "\u12b2"-"\u12b5", - "\u12b8"-"\u12be", - "\u12c0", - "\u12c2"-"\u12c5", - "\u12c8"-"\u12ce", - "\u12d0"-"\u12d6", - "\u12d8"-"\u12ee", - "\u12f0"-"\u130e", - "\u1310", - "\u1312"-"\u1315", - "\u1318"-"\u131e", - "\u1320"-"\u1346", - "\u1348"-"\u135a", - "\u1369"-"\u1371", - "\u13a0"-"\u13f4", - "\u1401"-"\u166c", - "\u166f"-"\u1676", - "\u1681"-"\u169a", - "\u16a0"-"\u16ea", - "\u1780"-"\u17d3", - "\u17db", - "\u17e0"-"\u17e9", - "\u180b"-"\u180e", - "\u1810"-"\u1819", - "\u1820"-"\u1877", - "\u1880"-"\u18a9", - "\u1e00"-"\u1e9b", - "\u1ea0"-"\u1ef9", - "\u1f00"-"\u1f15", - "\u1f18"-"\u1f1d", - "\u1f20"-"\u1f45", - "\u1f48"-"\u1f4d", - "\u1f50"-"\u1f57", - "\u1f59", - "\u1f5b", - "\u1f5d", - "\u1f5f"-"\u1f7d", - "\u1f80"-"\u1fb4", - "\u1fb6"-"\u1fbc", - "\u1fbe", - "\u1fc2"-"\u1fc4", - "\u1fc6"-"\u1fcc", - "\u1fd0"-"\u1fd3", - "\u1fd6"-"\u1fdb", - "\u1fe0"-"\u1fec", - "\u1ff2"-"\u1ff4", - "\u1ff6"-"\u1ffc", - "\u200c"-"\u200f", - "\u202a"-"\u202e", - "\u203f"-"\u2040", - "\u206a"-"\u206f", - "\u207f", - "\u20a0"-"\u20af", - "\u20d0"-"\u20dc", - "\u20e1", - "\u2102", - "\u2107", - "\u210a"-"\u2113", - "\u2115", - "\u2119"-"\u211d", - "\u2124", - "\u2126", - "\u2128", - "\u212a"-"\u212d", - "\u212f"-"\u2131", - "\u2133"-"\u2139", - "\u2160"-"\u2183", - "\u3005"-"\u3007", - "\u3021"-"\u302f", - "\u3031"-"\u3035", - "\u3038"-"\u303a", - "\u3041"-"\u3094", - "\u3099"-"\u309a", - "\u309d"-"\u309e", - "\u30a1"-"\u30fe", - "\u3105"-"\u312c", - "\u3131"-"\u318e", - "\u31a0"-"\u31b7", - "\u3400"-"\u4db5", - "\u4e00"-"\u9fa5", - "\ua000"-"\ua48c", - "\uac00"-"\ud7a3", - "\uf900"-"\ufa2d", - "\ufb00"-"\ufb06", - "\ufb13"-"\ufb17", - "\ufb1d"-"\ufb28", - "\ufb2a"-"\ufb36", - "\ufb38"-"\ufb3c", - "\ufb3e", - "\ufb40"-"\ufb41", - "\ufb43"-"\ufb44", - "\ufb46"-"\ufbb1", - "\ufbd3"-"\ufd3d", - "\ufd50"-"\ufd8f", - "\ufd92"-"\ufdc7", - "\ufdf0"-"\ufdfb", - "\ufe20"-"\ufe23", - "\ufe33"-"\ufe34", - "\ufe4d"-"\ufe4f", - "\ufe69", - "\ufe70"-"\ufe72", - "\ufe74", - "\ufe76"-"\ufefc", - "\ufeff", - "\uff04", - "\uff10"-"\uff19", - "\uff21"-"\uff3a", - "\uff3f", - "\uff41"-"\uff5a", - "\uff65"-"\uffbe", - "\uffc2"-"\uffc7", - "\uffca"-"\uffcf", - "\uffd2"-"\uffd7", - "\uffda"-"\uffdc", - "\uffe0"-"\uffe1", - "\uffe5"-"\uffe6", - "\ufff9"-"\ufffb" - ] - > -} - -/* SEPARATORS */ - -TOKEN : -{ - < LPAREN: "(" > -| < RPAREN: ")" > -| < LBRACE: "{" > -| < RBRACE: "}" > -| < LBRACKET: "[" > -| < RBRACKET: "]" > -| < SEMICOLON: ";" > -| < COMMA: "," > -| < DOT: "." > -| < AT: "@" > -} - -/* OPERATORS */ - -TOKEN : -{ - < ASSIGN: "=" > -| < LT: "<" > -| < BANG: "!" > -| < TILDE: "~" > -| < HOOK: "?" > -| < COLON: ":" > -| < EQ: "==" > -| < LE: "<=" > -| < GE: ">=" > -| < NE: "!=" > -| < SC_OR: "||" > -| < SC_AND: "&&" > -| < INCR: "++" > -| < DECR: "--" > -| < PLUS: "+" > -| < MINUS: "-" > -| < STAR: "*" > -| < SLASH: "/" > -| < BIT_AND: "&" > -| < BIT_OR: "|" > -| < XOR: "^" > -| < REM: "%" > -| < LSHIFT: "<<" > -| < PLUSASSIGN: "+=" > -| < MINUSASSIGN: "-=" > -| < STARASSIGN: "*=" > -| < SLASHASSIGN: "/=" > -| < ANDASSIGN: "&=" > -| < ORASSIGN: "|=" > -| < XORASSIGN: "^=" > -| < REMASSIGN: "%=" > -| < LSHIFTASSIGN: "<<=" > -| < RSIGNEDSHIFTASSIGN: ">>=" > -| < RUNSIGNEDSHIFTASSIGN: ">>>=" > -| < ELLIPSIS: "..." > -} - -/* >'s need special attention due to generics syntax. */ -TOKEN : -{ - < RUNSIGNEDSHIFT: ">>>" > - { - matchedToken.kind = GT; - ((MyToken)matchedToken).realKind = RUNSIGNEDSHIFT; - input_stream.backup(2); - matchedToken.image = ">"; - } -| < RSIGNEDSHIFT: ">>" > - { - matchedToken.kind = GT; - ((MyToken)matchedToken).realKind = RSIGNEDSHIFT; - input_stream.backup(1); - matchedToken.image = ">"; - } -| < GT: ">" > -} - - -/***************************************** - * THE JAVA LANGUAGE GRAMMAR STARTS HERE * - *****************************************/ - -/* - * Program structuring syntax follows. - */ - -void CompilationUnit(): -{} -{ - [ LOOKAHEAD( ( Annotation() )* "package" ) PackageDeclaration() ] - ( ImportDeclaration() )* - ( TypeDeclaration() )+ - ( < "\u001a" > )? - ( )? - -} - -void PackageDeclaration(): -{} -{ - Modifiers() "package" Name() ";" -} - -void ImportDeclaration(): -{} -{ - "import" [ "static" ] Name() [ "." "*" ] ";" -} - -/* - * Modifiers. We match all modifiers in a single rule to reduce the chances of - * syntax errors for simple modifier mistakes. It will also enable us to give - * better error messages. - */ - -int Modifiers(): -{ - int modifiers = 0; -} -{ - ( - LOOKAHEAD(2) - ( - "public" { modifiers |= ModifierSet.PUBLIC; } - | - "static" { modifiers |= ModifierSet.STATIC; } - | - "protected" { modifiers |= ModifierSet.PROTECTED; } - | - "private" { modifiers |= ModifierSet.PRIVATE; } - | - "final" { modifiers |= ModifierSet.FINAL; } - | - "abstract" { modifiers |= ModifierSet.ABSTRACT; } - | - "synchronized" { modifiers |= ModifierSet.SYNCHRONIZED; } - | - "native" { modifiers |= ModifierSet.NATIVE; } - | - "transient" { modifiers |= ModifierSet.TRANSIENT; } - | - "volatile" { modifiers |= ModifierSet.VOLATILE; } - | - "strictfp" { modifiers |= ModifierSet.STRICTFP; } - | - Annotation() - ) - )* - - { - return modifiers; - } -} - -/* - * Declaration syntax follows. - */ -void TypeDeclaration(): -{ - int modifiers; -} -{ - ";" -| - modifiers = Modifiers() - ( - ClassOrInterfaceDeclaration(modifiers) - | - EnumDeclaration(modifiers) - | - AnnotationTypeDeclaration(modifiers) - ) -} - - -void ClassOrInterfaceDeclaration(int modifiers): -{ - boolean isInterface = false; -} -{ - ( "class" | "interface" { isInterface = true; } ) - - [ TypeParameters() ] - [ ExtendsList(isInterface) ] - [ ImplementsList(isInterface) ] - ClassOrInterfaceBody(isInterface) -} - -void ExtendsList(boolean isInterface): -{ - boolean extendsMoreThanOne = false; -} -{ - "extends" ClassOrInterfaceType() - ( "," ClassOrInterfaceType() { extendsMoreThanOne = true; } )* - { - if (extendsMoreThanOne && !isInterface) - throw new ParseException("A class cannot extend more than one other class"); - } -} - -void ImplementsList(boolean isInterface): -{} -{ - "implements" ClassOrInterfaceType() - ( "," ClassOrInterfaceType() )* - { - if (isInterface) - throw new ParseException("An interface cannot implement other interfaces"); - } -} - -void EnumDeclaration(int modifiers): -{} -{ - "enum" - [ ImplementsList(false) ] - EnumBody() -} - -void EnumBody(): -{} -{ - "{" - [ EnumConstant() ( LOOKAHEAD(2) "," EnumConstant() )* ] - [ "," ] - [ ";" ( ClassOrInterfaceBodyDeclaration(false) )* ] - "}" -} - -void EnumConstant(): -{} -{ - Modifiers() [ Arguments() ] [ ClassOrInterfaceBody(false) ] -} - -void TypeParameters(): -{} -{ - "<" TypeParameter() ( "," TypeParameter() )* ">" -} - -void TypeParameter(): -{} -{ - [ TypeBound() ] -} - -void TypeBound(): -{} -{ - "extends" ClassOrInterfaceType() ( "&" ClassOrInterfaceType() )* -} - -void ClassOrInterfaceBody(boolean isInterface): -{} -{ - "{" ( ClassOrInterfaceBodyDeclaration(isInterface) )* "}" -} - -void ClassOrInterfaceBodyDeclaration(boolean isInterface): -{ - boolean isNestedInterface = false; - int modifiers; -} -{ - LOOKAHEAD(2) - Initializer() - { - if (isInterface) - throw new ParseException("An interface cannot have initializers"); - } -| - modifiers = Modifiers() // Just get all the modifiers out of the way. If you want to do - // more checks, pass the modifiers down to the member - ( - ClassOrInterfaceDeclaration(modifiers) - | - EnumDeclaration(modifiers) - | - LOOKAHEAD( [ TypeParameters() ] "(" ) - ConstructorDeclaration() - | - LOOKAHEAD( Type() ( "[" "]" )* ( "," | "=" | ";" ) ) - FieldDeclaration(modifiers) - | - MethodDeclaration(modifiers) - | - AnnotationTypeDeclaration(modifiers) - ) -| - ";" -} - -void FieldDeclaration(int modifiers): -{} -{ - // Modifiers are already matched in the caller - Type() VariableDeclarator() ( "," VariableDeclarator() )* ";" -} - -void VariableDeclarator(): -{} -{ - VariableDeclaratorId() [ "=" VariableInitializer() ] -} - -void VariableDeclaratorId(): -{} -{ - ( "[" "]" )* -} - -void VariableInitializer(): -{} -{ - ArrayInitializer() -| - Expression() -} - -void ArrayInitializer(): -{} -{ - "{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}" -} - -void MethodDeclaration(int modifiers): -{} -{ - // Modifiers already matched in the caller! - [ TypeParameters() ] - ResultType() - MethodDeclarator() [ "throws" NameList() ] - ( Block() | ";" ) -} - -void MethodDeclarator(): -{} -{ - FormalParameters() ( "[" "]" )* -} - -void FormalParameters(): -{} -{ - "(" [ FormalParameter() ( "," FormalParameter() )* ] ")" -} - -void FormalParameter(): -{} -{ - // danson, added - // [ "final" | Annotation() ] - // See Java Language Specification, 3rd Edition, section 8.4.1 - Modifiers() [ "final" | Annotation() ] Type() [ "..." ] VariableDeclaratorId() -} - -void ConstructorDeclaration(): -{} -{ - [ TypeParameters() ] - // Modifiers matched in the caller - FormalParameters() [ "throws" NameList() ] - "{" - [ LOOKAHEAD(ExplicitConstructorInvocation()) - ExplicitConstructorInvocation() - ] - ( BlockStatement() )* - "}" -} - -void ExplicitConstructorInvocation(): -{} -{ - ( "." )* [ LOOKAHEAD(2) "this" "." ] - [ TypeArguments() ] ("this"|"super") Arguments() ";" -} - -void Initializer(): -{} -{ - [ "static" ] Block() -} - - -/* - * Type, name and expression syntax follows. - */ - -void Type(): -{} -{ - LOOKAHEAD(2) ReferenceType() - | - PrimitiveType() -} - -void ReferenceType(): -{} -{ - PrimitiveType() ( LOOKAHEAD(2) "[" "]" )+ - | - ( ClassOrInterfaceType() ) ( LOOKAHEAD(2) "[" "]" )* -} - -void ClassOrInterfaceType(): -{} -{ - [ LOOKAHEAD(2) TypeArguments() ] - ( LOOKAHEAD(2) "." [ LOOKAHEAD(2) TypeArguments() ] )* -} - -void TypeArguments(): -{} -{ - "<" TypeArgument() ( "," TypeArgument() )* ">" -} - -void TypeArgument(): -{} -{ - ReferenceType() - | - "?" [ WildcardBounds() ] -} - -void WildcardBounds(): -{} -{ - "extends" ReferenceType() - | - "super" ReferenceType() -} - - -void PrimitiveType(): -{} -{ - "boolean" -| - "char" -| - "byte" -| - "short" -| - "int" -| - "long" -| - "float" -| - "double" -} - -void ResultType(): -{} -{ - "void" -| - Type() -} - -void Name(): -/* - * A lookahead of 2 is required below since "Name" can be followed - * by a ".*" when used in the context of an "ImportDeclaration". - */ -{} -{ - - ( LOOKAHEAD(2) "." - )* -} - -void NameList(): -{} -{ - Name() ( "," Name() )* -} - - -/* - * Expression syntax follows. - */ - -void Expression(): -/* - * This expansion has been written this way instead of: - * Assignment() | ConditionalExpression() - * for performance reasons. - * However, it is a weakening of the grammar for it allows the LHS of - * assignments to be any conditional expression whereas it can only be - * a primary expression. Consider adding a semantic predicate to work - * around this. - */ -{} -{ - ConditionalExpression() - [ - LOOKAHEAD(2) - AssignmentOperator() Expression() - ] -} - -void AssignmentOperator(): -{} -{ - "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | ">>>=" | "&=" | "^=" | "|=" -} - -void ConditionalExpression(): -{} -{ - ConditionalOrExpression() [ "?" Expression() ":" Expression() ] -} - -void ConditionalOrExpression(): -{} -{ - ConditionalAndExpression() ( "||" ConditionalAndExpression() )* -} - -void ConditionalAndExpression(): -{} -{ - InclusiveOrExpression() ( "&&" InclusiveOrExpression() )* -} - -void InclusiveOrExpression(): -{} -{ - ExclusiveOrExpression() ( "|" ExclusiveOrExpression() )* -} - -void ExclusiveOrExpression(): -{} -{ - AndExpression() ( "^" AndExpression() )* -} - -void AndExpression(): -{} -{ - EqualityExpression() ( "&" EqualityExpression() )* -} - -void EqualityExpression(): -{} -{ - InstanceOfExpression() ( ( "==" | "!=" ) InstanceOfExpression() )* -} - -void InstanceOfExpression(): -{} -{ - RelationalExpression() [ "instanceof" Type() ] -} - -void RelationalExpression(): -{} -{ - ShiftExpression() ( ( "<" | ">" | "<=" | ">=" ) ShiftExpression() )* -} - -void ShiftExpression(): -{} -{ - AdditiveExpression() ( ( "<<" | RSIGNEDSHIFT() | RUNSIGNEDSHIFT() ) AdditiveExpression() )* -} - -void AdditiveExpression(): -{} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -void MultiplicativeExpression(): -{} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -void UnaryExpression(): -{} -{ - ( "+" | "-" ) UnaryExpression() -| - PreIncrementExpression() -| - PreDecrementExpression() -| - UnaryExpressionNotPlusMinus() -} - -void PreIncrementExpression(): -{} -{ - "++" PrimaryExpression() -} - -void PreDecrementExpression(): -{} -{ - "--" PrimaryExpression() -} - -void UnaryExpressionNotPlusMinus(): -{} -{ - ( "~" | "!" ) UnaryExpression() -| - LOOKAHEAD( CastLookahead() ) - CastExpression() -| - PostfixExpression() -} - -// This production is to determine lookahead only. The LOOKAHEAD specifications -// below are not used, but they are there just to indicate that we know about -// this. -void CastLookahead(): -{} -{ - LOOKAHEAD(2) - "(" PrimitiveType() -| - LOOKAHEAD("(" Type() "[") - "(" Type() "[" "]" -| - "(" Type() ")" ( "~" | "!" | "(" | | "this" | "super" | "new" | Literal() ) -} - -void PostfixExpression(): -{} -{ - PrimaryExpression() [ "++" | "--" ] -} - -void CastExpression(): -{} -{ - LOOKAHEAD("(" PrimitiveType()) - "(" Type() ")" UnaryExpression() -| - "(" Type() ")" UnaryExpressionNotPlusMinus() -} - -void PrimaryExpression(): -{} -{ - PrimaryPrefix() ( LOOKAHEAD(2) PrimarySuffix() )* -} - -void MemberSelector(): -{} -{ - "." TypeArguments() -} - -void PrimaryPrefix(): -{} -{ - Literal() -| - LOOKAHEAD( ( "." )* "this" ) - ( "." )* - "this" -| - "super" "." -| - // danson, added this part to support a construct like: - // Buffer.super.setDirty(true); - // See Java Language Specification, 3rd edition, section 15.11.2. - LOOKAHEAD( ClassOrInterfaceType() "." "super" "." ) - ClassOrInterfaceType() "." "super" "." -| - "(" Expression() ")" -| - AllocationExpression() -| - LOOKAHEAD( ResultType() "." "class" ) - ResultType() "." "class" -| - Name() -} - -void PrimarySuffix(): -{} -{ - LOOKAHEAD("." "super" ".") - "." "super" -| - LOOKAHEAD("." "this") - "." "this" -| - LOOKAHEAD(2) - "." AllocationExpression() -| - LOOKAHEAD(3) - MemberSelector() -| - "[" Expression() "]" -| - "." -| - Arguments() -} - -void Literal(): -{} -{ - -| - -| - -| - -| - BooleanLiteral() -| - NullLiteral() -} - -void BooleanLiteral(): -{} -{ - "true" -| - "false" -} - -void NullLiteral(): -{} -{ - "null" -} - -void Arguments(): -{} -{ - "(" [ ArgumentList() ] ")" -} - -void ArgumentList(): -{} -{ - Expression() ( "," Expression() )* -} - -void AllocationExpression(): -{} -{ - LOOKAHEAD(2) - "new" PrimitiveType() ArrayDimsAndInits() -| - "new" ClassOrInterfaceType() [ TypeArguments() ] - ( - ArrayDimsAndInits() - | - Arguments() [ ClassOrInterfaceBody(false) ] - ) -} - -/* - * The third LOOKAHEAD specification below is to parse to PrimarySuffix - * if there is an expression between the "[...]". - */ -void ArrayDimsAndInits(): -{} -{ - LOOKAHEAD(2) - ( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )* -| - ( "[" "]" )+ ArrayInitializer() -} - - -/* - * Statement syntax follows. - */ - -void Statement(): -{} -{ - LOOKAHEAD(2) - LabeledStatement() -| - AssertStatement() -| - Block() -| - EmptyStatement() -| - StatementExpression() ";" -| - SwitchStatement() -| - IfStatement() -| - WhileStatement() -| - DoStatement() -| - ForStatement() -| - BreakStatement() -| - ContinueStatement() -| - ReturnStatement() -| - ThrowStatement() -| - SynchronizedStatement() -| - TryStatement() -} - -void AssertStatement(): -{} -{ - "assert" Expression() [ ":" Expression() ] ";" -} - -void LabeledStatement(): -{} -{ - ":" Statement() -} - -void Block(): -{} -{ - "{" ( BlockStatement() )* "}" -} - -void BlockStatement(): -{} -{ - LOOKAHEAD( Modifiers() Type() ) - LocalVariableDeclaration() ";" -| - Statement() -| - ClassOrInterfaceDeclaration(0) -} - -void LocalVariableDeclaration(): -{} -{ - Modifiers() Type() VariableDeclarator() ( "," VariableDeclarator() )* -} - -void EmptyStatement(): -{} -{ - ";" -} - -void StatementExpression(): -/* - * The last expansion of this production accepts more than the legal - * Java expansions for StatementExpression. This expansion does not - * use PostfixExpression for performance reasons. - */ -{} -{ - PreIncrementExpression() -| - PreDecrementExpression() -| - PrimaryExpression() - [ - "++" - | - "--" - | - AssignmentOperator() Expression() - ] -} - -void SwitchStatement(): -{} -{ - "switch" "(" Expression() ")" "{" - ( SwitchLabel() ( BlockStatement() )* )* - "}" -} - -void SwitchLabel(): -{} -{ - "case" Expression() ":" -| - "default" ":" -} - -void IfStatement(): -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -void WhileStatement(): -{} -{ - "while" "(" Expression() ")" Statement() -} - -void DoStatement(): -{} -{ - "do" Statement() "while" "(" Expression() ")" ";" -} - -void ForStatement(): -{} -{ - "for" "(" - - ( - LOOKAHEAD(Modifiers() Type() ":") - Modifiers() Type() ":" Expression() - | - [ ForInit() ] ";" [ Expression() ] ";" [ ForUpdate() ] - ) - - ")" Statement() -} - -void ForInit(): -{} -{ - LOOKAHEAD( Modifiers() Type() ) - LocalVariableDeclaration() -| - StatementExpressionList() -} - -void StatementExpressionList(): -{} -{ - StatementExpression() ( "," StatementExpression() )* -} - -void ForUpdate(): -{} -{ - StatementExpressionList() -} - -void BreakStatement(): -{} -{ - "break" [ ] ";" -} - -void ContinueStatement(): -{} -{ - "continue" [ ] ";" -} - -void ReturnStatement(): -{} -{ - "return" [ Expression() ] ";" -} - -void ThrowStatement(): -{} -{ - "throw" Expression() ";" -} - -void SynchronizedStatement(): -{} -{ - "synchronized" "(" Expression() ")" Block() -} - -void TryStatement(): -/* - * Semantic check required here to make sure that at least one - * finally/catch is present. - */ -{} -{ - "try" Block() - ( "catch" "(" FormalParameter() ")" Block() )* - [ "finally" Block() ] -} - -/* We use productions to match >>>, >> and > so that we can keep the - * type declaration syntax with generics clean - */ - -void RUNSIGNEDSHIFT(): -{} -{ - ( LOOKAHEAD({ getToken(1).kind == GT && - ((MyToken)getToken(1)).realKind == RUNSIGNEDSHIFT} ) - ">" ">" ">" - ) -} - -void RSIGNEDSHIFT(): -{} -{ - ( LOOKAHEAD({ getToken(1).kind == GT && - ((MyToken)getToken(1)).realKind == RSIGNEDSHIFT} ) - ">" ">" - ) -} - -/* Annotation syntax follows. */ - -void Annotation(): -{} -{ - LOOKAHEAD( "@" Name() "(" ( "=" | ")" )) - NormalAnnotation() - | - LOOKAHEAD( "@" Name() "(" ) - SingleMemberAnnotation() - | - MarkerAnnotation() -} - -void NormalAnnotation(): -{} -{ - "@" Name() "(" [ MemberValuePairs() ] ")" -} - -void MarkerAnnotation(): -{} -{ - "@" Name() -} - -void SingleMemberAnnotation(): -{} -{ - "@" Name() "(" MemberValue() ")" -} - -void MemberValuePairs(): -{} -{ - MemberValuePair() ( "," MemberValuePair() )* -} - -void MemberValuePair(): -{} -{ - "=" MemberValue() -} - -void MemberValue(): -{} -{ - Annotation() - | - MemberValueArrayInitializer() - | - ConditionalExpression() -} - -void MemberValueArrayInitializer(): -{} -{ - "{" (MemberValue() ( LOOKAHEAD(2) "," MemberValue() )* [ "," ])? "}" -} - - -/* Annotation Types. */ - -void AnnotationTypeDeclaration(int modifiers): -{} -{ - "@" "interface" AnnotationTypeBody() -} - -void AnnotationTypeBody(): -{} -{ - "{" ( AnnotationTypeMemberDeclaration() )* "}" -} - -void AnnotationTypeMemberDeclaration(): -{ - int modifiers; -} -{ - modifiers = Modifiers() - ( - LOOKAHEAD(Type() "(") - Type() "(" ")" [ DefaultValue() ] ";" - | - ClassOrInterfaceDeclaration(modifiers) - | - EnumDeclaration(modifiers) - | - AnnotationTypeDeclaration(modifiers) - | - FieldDeclaration(modifiers) - ) - | - ( ";" ) -} - -void DefaultValue(): -{} -{ - "default" MemberValue() -} diff --git a/examples/JavaCC/checkstyle-suppress.xml b/examples/JavaCC/checkstyle-suppress.xml deleted file mode 100644 index dd40b08..0000000 --- a/examples/JavaCC/checkstyle-suppress.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/JavaCC/pom.xml b/examples/JavaCC/pom.xml deleted file mode 100644 index 448c052..0000000 --- a/examples/JavaCC/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - javacc - jar - - JavaCC Java code generator / examples / JavaCC - - - - - - org.codehaus.mojo - exec-maven-plugin - - - test - - java - - - - - JavaCCParser - - ${project.basedir}/Java1.5.jj - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.6.0 - - google_checks.xml - true - true - UTF-8 - target/generated-sources/java - checkstyle.suppressions.file - checkstyle-suppress.xml - error - - - - validate - generate-sources - - check - - - - - - - - \ No newline at end of file diff --git a/examples/JavaCC/src/main/javacc/JavaCC.jj b/examples/JavaCC/src/main/javacc/JavaCC.jj deleted file mode 100644 index a638bd5..0000000 --- a/examples/JavaCC/src/main/javacc/JavaCC.jj +++ /dev/null @@ -1,1517 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - JAVA_UNICODE_ESCAPE = true; -} - -PARSER_BEGIN(JavaCCParser) - -/** - * Parser for JavaCC grammar. - */ -public class JavaCCParser { - - public static void main(String[] args) { - JavaCCParser parser; - if (args.length == 0) { - System.out.println("JavaCC Parser: Reading from standard input . . ."); - parser = new JavaCCParser(System.in); - } else if (args.length == 1) { - System.out.println("JavaCC Parser: Reading from file " + args[0] + " . . ."); - try { - parser = new JavaCCParser(new java.io.FileInputStream(args[0])); - } catch (java.io.FileNotFoundException e) { - System.out.println("JavaCC Parser: File " + args[0] + " not found."); - return; - } - } else { - System.out.println("JavaCC Parser: Usage is one of:"); - System.out.println(" java JavaCCParser < inputfile"); - System.out.println("OR"); - System.out.println(" java JavaCCParser inputfile"); - return; - } - try { - JavaCCParser.javacc_input(); - System.out.println("JavaCC Parser: Java program parsed successfully."); - } catch (ParseException e) { - System.out.println(e.getMessage()); - System.out.println("JavaCC Parser: Encountered errors during parse."); - return; - } - } - - /* - * Returns true if the next token is not in the FOLLOW list of "expansion". - * It is used to decide when the end of an "expansion" has been reached. - */ - private static boolean notTailOfExpansionUnit() { - Token t; - t = getToken(1); - return !(t.kind == BIT_OR || t.kind == COMMA || t.kind == RPAREN - || t.kind == RBRACE || t.kind == RBRACKET); - } - -} - -PARSER_END(JavaCCParser) - - -/*-------------------------------------------- - * THE JAVACC TOKEN SPECIFICATION STARTS HERE - *-------------------------------------------*/ - -/* JAVACC RESERVED WORDS: These are the only tokens in JavaCC but not in Java */ - -TOKEN : -{ - < _OPTIONS: "options" > -| < _LOOKAHEAD: "LOOKAHEAD" > -| < _IGNORE_CASE: "IGNORE_CASE" > -| < _PARSER_BEGIN: "PARSER_BEGIN" > -| < _PARSER_END: "PARSER_END" > -| < _JAVACODE: "JAVACODE" > -| < _TOKEN: "TOKEN" > -| < _SPECIAL_TOKEN: "SPECIAL_TOKEN" > -| < _MORE: "MORE" > -| < _SKIP: "SKIP" > -| < _TOKEN_MGR_DECLS: "TOKEN_MGR_DECLS" > -| < _EOF: "EOF" > -} - -/* - * The remainder of the tokens are exactly (except for the removal of tokens - * containing ">>" and "<<") as in the Java grammar and must be diff equivalent - * (again with the exceptions above) to it. - */ - -/* WHITE SPACE */ - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -/* COMMENTS */ - -MORE : -{ - "//" : IN_SINGLE_LINE_COMMENT -| - <"/**" ~["/"]> { input_stream.backup(1); } : IN_FORMAL_COMMENT -| - "/*" : IN_MULTI_LINE_COMMENT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -MORE : -{ - < ~[] > -} - -/* JAVA RESERVED WORDS AND LITERALS */ - -TOKEN : -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -/* JAVA LITERALS */ - -TOKEN : -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -| - < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? (["f","F","d","D"])? - | "." (["0"-"9"])+ ()? (["f","F","d","D"])? - | (["0"-"9"])+ (["f","F","d","D"])? - | (["0"-"9"])+ ()? ["f","F","d","D"] - > -| - < #EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ > -| - < CHARACTER_LITERAL: - "'" - ( (~["'","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - ) - "'" - > -| - < STRING_LITERAL: - "\"" - ( (~["\"","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - )* - "\"" - > -} - -/* IDENTIFIERS */ - -TOKEN : -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} - -/* SEPARATORS */ - -TOKEN : -{ - < LPAREN: "(" > -| < RPAREN: ")" > -| < LBRACE: "{" > -| < RBRACE: "}" > -| < LBRACKET: "[" > -| < RBRACKET: "]" > -| < SEMICOLON: ";" > -| < COMMA: "," > -| < DOT: "." > -} - -/* OPERATORS */ - -TOKEN : -{ - < ASSIGN: "=" > -| < GT: ">" > -| < LT: "<" > -| < BANG: "!" > -| < TILDE: "~" > -| < HOOK: "?" > -| < COLON: ":" > -| < EQ: "==" > -| < LE: "<=" > -| < GE: ">=" > -| < NE: "!=" > -| < SC_OR: "||" > -| < SC_AND: "&&" > -| < INCR: "++" > -| < DECR: "--" > -| < PLUS: "+" > -| < MINUS: "-" > -| < STAR: "*" > -| < SLASH: "/" > -| < BIT_AND: "&" > -| < BIT_OR: "|" > -| < XOR: "^" > -| < REM: "%" > -// | < LSHIFT: "<<" > -// | < RSIGNEDSHIFT: ">>" > -// | < RUNSIGNEDSHIFT: ">>>" > -| < PLUSASSIGN: "+=" > -| < MINUSASSIGN: "-=" > -| < STARASSIGN: "*=" > -| < SLASHASSIGN: "/=" > -| < ANDASSIGN: "&=" > -| < ORASSIGN: "|=" > -| < XORASSIGN: "^=" > -| < REMASSIGN: "%=" > -// | < LSHIFTASSIGN: "<<=" > -// | < RSIGNEDSHIFTASSIGN: ">>=" > -// | < RUNSIGNEDSHIFTASSIGN: ">>>=" > -} - - -/*----------------------------------------------- - * THE JAVACC GRAMMAR SPECIFICATION STARTS HERE - *----------------------------------------------*/ - -void javacc_input() : -{} -{ - javacc_options() - "PARSER_BEGIN" "(" identifier() ")" - CompilationUnit() - "PARSER_END" "(" identifier() ")" - ( production() )+ - -} - -void javacc_options() : -{} -{ - [ "options" "{" ( option_binding() )+ "}" ] -} - -void option_binding() : -{} -{ - ( | "LOOKAHEAD" | "IGNORE_CASE" | "static" ) - "=" - ( IntegerLiteral() | BooleanLiteral() | StringLiteral() ) - ";" -} - -void production() : -{} -{ - LOOKAHEAD(1) - /* - * Since JAVACODE is both a JavaCC reserved word and a Java identifier, - * we need to give preference to "javacode_production" over - * "bnf_production". - */ - javacode_production() -| - LOOKAHEAD(1) - /* - * Since SKIP, TOKEN, etc. are both JavaCC reserved words and Java - * identifiers, we need to give preference to "regular_expression_production" - * over "bnf_production". - */ - regular_expr_production() -| - LOOKAHEAD(1) - /* - * Since TOKEN_MGR_DECLS is both a JavaCC reserved word and a Java identifier, - * we need to give preference to "token_manager_decls" over - * "bnf_production". - */ - token_manager_decls() -| - bnf_production() -} - -void javacode_production() : -{} -{ - "JAVACODE" - ResultType() identifier() FormalParameters() - [ "throws" Name() ( "," Name() )* ] - [ node_descriptor() ] - Block() -} - -void bnf_production() : -{} -{ - ResultType() identifier() FormalParameters() - [ "throws" Name() ( "," Name() )* ] - [ node_descriptor() ] - ":" - Block() - "{" expansion_choices() "}" -} - -void regular_expr_production() : -{} -{ - [ - LOOKAHEAD(2) "<" "*" ">" - | - "<" ( "," )* ">" - ] - regexpr_kind() [ "[" "IGNORE_CASE" "]" ] ":" - "{" regexpr_spec() ( "|" regexpr_spec() )* "}" -} - -void token_manager_decls() : -{} -{ - "TOKEN_MGR_DECLS" ":" ClassBody() -} - -void regexpr_kind() : -{} -{ - "TOKEN" -| - "SPECIAL_TOKEN" -| - "SKIP" -| - "MORE" -} - -void regexpr_spec() : -{} -{ - regular_expression() [ Block() ] [ ":" ] -} - -void expansion_choices() : -{} -{ - expansion() ( "|" expansion() )* -} - -void expansion() : -{} -{ - ( LOOKAHEAD(1) - "LOOKAHEAD" "(" local_lookahead() ")" - )? - ( LOOKAHEAD(0, { notTailOfExpansionUnit() } ) - expansion_unit() - [ node_descriptor() ] - )+ -} - -void local_lookahead() : - { - boolean commaAtEnd = false, emptyLA = true; - } -{ - [ - /* - * The lookahead of 1 is to turn off the warning message that lets - * us know that an expansion choice can also start with an integer - * literal because a primary expression can do the same. But we - * know that this is what we want. - */ - LOOKAHEAD(1) - IntegerLiteral() - { - emptyLA = false; - } - ] - [ LOOKAHEAD(0, { !emptyLA && (getToken(1).kind != RPAREN) } ) - "," - { - commaAtEnd = true; - } - ] - [ LOOKAHEAD(0, { getToken(1).kind != RPAREN && getToken(1).kind != LBRACE } ) - expansion_choices() - { - emptyLA = false; - commaAtEnd = false; - } - ] - [ LOOKAHEAD(0, { !emptyLA && !commaAtEnd && (getToken(1).kind != RPAREN) } ) - "," - { - commaAtEnd = true; - } - ] - [ LOOKAHEAD(0, { emptyLA || commaAtEnd } ) - "{" Expression() "}" - ] -} - -void expansion_unit() : -{} -{ - LOOKAHEAD(1) - /* - * We give this priority over primary expressions which use LOOKAHEAD as the - * name of its identifier. - */ - "LOOKAHEAD" "(" local_lookahead() ")" -| - Block() -| - "[" expansion_choices() "]" -| - "try" "{" expansion_choices() "}" - ( "catch" "(" Name() ")" Block() )* - [ "finally" Block() ] -| - LOOKAHEAD( identifier() | StringLiteral() | "<" | PrimaryExpression() "=" ) - [ - LOOKAHEAD(PrimaryExpression() "=") - PrimaryExpression() "=" - ] - ( regular_expression() | identifier() Arguments() ) -| - "(" expansion_choices() ")" ( "+" | "*" | "?" )? -} - -void regular_expression() : -{} -{ - StringLiteral() -| - LOOKAHEAD(3) - "<" [ [ "#" ] identifier() ":" ] complex_regular_expression_choices() ">" -| - LOOKAHEAD(2) - "<" identifier() ">" -| - "<" "EOF" ">" -} - -void complex_regular_expression_choices() : -{} -{ - complex_regular_expression() ( "|" complex_regular_expression() )* -} - -void complex_regular_expression() : -{} -{ - ( complex_regular_expression_unit() )+ -} - -void complex_regular_expression_unit() : -{} -{ - StringLiteral() -| - "<" identifier() ">" -| - character_list() -| - "(" complex_regular_expression_choices() ")" ( "+" | "*" | "?" )? -} - -void character_list() : -{} -{ - [ "~" ] "[" [ character_descriptor() ( "," character_descriptor() )* ] "]" -} - -void character_descriptor() : -{} -{ - StringLiteral() [ "-" StringLiteral() ] -} - -void identifier() : -{} -{ - -} - - -/*----------------------------------- - * THE JJTREE PRODUCTIONS START HERE - *-----------------------------------*/ - -void node_descriptor() : -{} -{ - "#" ( | ) - [ - LOOKAHEAD(1) - "(" [ ">" ] node_descriptor_expression() ")" - ] -} - - -JAVACODE -void node_descriptor_expression() -{ - Token tok; - int nesting = 1; - while (true) { - tok = getToken(1); - if (tok.kind == 0) { - throw new ParseException(); - } - if (tok.kind == LPAREN) { - nesting++; - } else if (tok.kind == RPAREN) { - nesting--; - if (nesting == 0) { - break; - } - } - tok = getNextToken(); - } -} - - -/*-------------------------------------------- - * THE JAVA GRAMMAR SPECIFICATION STARTS HERE - *--------------------------------------------*/ - -/* - * The Java grammar is modified to use sequences of tokens - * for the missing tokens - those that include "<<" and ">>". - */ - -/* - * The following production defines Java identifiers - it - * includes the reserved words of JavaCC also. - */ - -void JavaIdentifier() : -{} -{ - -| "options" -| "LOOKAHEAD" -| "IGNORE_CASE" -| "PARSER_BEGIN" -| "PARSER_END" -| "JAVACODE" -| "TOKEN" -| "SPECIAL_TOKEN" -| "MORE" -| "SKIP" -| "TOKEN_MGR_DECLS" -| "EOF" -} - -/* - * The productions for the missing code follows. Obviously - * these productions accept more than what is legal in Java, - * but that is OK for our purposes. - */ - -void ShiftOps() : -{} -{ - "<" "<" -| - ">" ">" [ ">" ] -} - -void OtherAssignmentOps() : -{} -{ - "<" "<=" -| - ">" [ ">" ] ">=" -} - -/* - * Program structuring syntax follows. - */ - -void CompilationUnit() : -/* - * The is deleted since the compilation unit is embedded - * within grammar code. To parse to CompilationUnit, we use - * a special production JavaCompilationUnit below. - */ -{} -{ - [ PackageDeclaration() ] - ( ImportDeclaration() )* - ( TypeDeclaration() )* -} - -void JavaCompilationUnit() : -/* - * Use this to parse a Java compilation unit. - */ -{} -{ - CompilationUnit() -} - -void PackageDeclaration() : -{} -{ - "package" Name() ";" -} - -void ImportDeclaration() : -{} -{ - "import" Name() [ "." "*" ] ";" -} - -void TypeDeclaration() : -{} -{ - LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() -| - InterfaceDeclaration() -| - ";" -} - - -/* - * Declaration syntax follows. - */ - -void ClassDeclaration() : -{} -{ - ( "abstract" | "final" | "public" )* - UnmodifiedClassDeclaration() -} - -void UnmodifiedClassDeclaration() : -{} -{ - "class" JavaIdentifier() [ "extends" Name() ] [ "implements" NameList() ] - ClassBody() -} - -void ClassBody() : -{} -{ - "{" ( ClassBodyDeclaration() )* "}" -} - -void NestedClassDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedClassDeclaration() -} - -void ClassBodyDeclaration() : -{} -{ - LOOKAHEAD(2) - Initializer() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( [ "public" | "protected" | "private" ] Name() "(" ) - ConstructorDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -// This production is to determine lookahead only. -void MethodDeclarationLookahead() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() JavaIdentifier() "(" -} - -void InterfaceDeclaration() : -{} -{ - ( "abstract" | "public" )* - UnmodifiedInterfaceDeclaration() -} - -void NestedInterfaceDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedInterfaceDeclaration() -} - -void UnmodifiedInterfaceDeclaration() : -{} -{ - "interface" JavaIdentifier() [ "extends" NameList() ] - "{" ( InterfaceMemberDeclaration() )* "}" -} - -void InterfaceMemberDeclaration() : -{} -{ - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -void FieldDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "final" | "transient" | "volatile" )* - Type() VariableDeclarator() ( "," VariableDeclarator() )* ";" -} - -void VariableDeclarator() : -{} -{ - VariableDeclaratorId() [ "=" VariableInitializer() ] -} - -void VariableDeclaratorId() : -{} -{ - JavaIdentifier() ( "[" "]" )* -} - -void VariableInitializer() : -{} -{ - ArrayInitializer() -| - Expression() -} - -void ArrayInitializer() : -{} -{ - "{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}" -} - -void MethodDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() MethodDeclarator() [ "throws" NameList() ] - ( Block() | ";" ) -} - -void MethodDeclarator() : -{} -{ - JavaIdentifier() FormalParameters() ( "[" "]" )* -} - -void FormalParameters() : -{} -{ - "(" [ FormalParameter() ( "," FormalParameter() )* ] ")" -} - -void FormalParameter() : -{} -{ - [ "final" ] Type() VariableDeclaratorId() -} - -void ConstructorDeclaration() : -{} -{ - [ "public" | "protected" | "private" ] - JavaIdentifier() FormalParameters() [ "throws" NameList() ] - "{" - [ LOOKAHEAD(ExplicitConstructorInvocation()) ExplicitConstructorInvocation() ] - ( BlockStatement() )* - "}" -} - -void ExplicitConstructorInvocation() : -{} -{ - LOOKAHEAD("this" Arguments() ";") - "this" Arguments() ";" -| - [ LOOKAHEAD(2) PrimaryExpression() "." ] "super" Arguments() ";" -} - -void Initializer() : -{} -{ - [ "static" ] Block() -} - - -/* - * Type, name and expression syntax follows. - */ - -void Type() : -{} -{ - ( PrimitiveType() | Name() ) ( "[" "]" )* -} - -void PrimitiveType() : -{} -{ - "boolean" -| - "char" -| - "byte" -| - "short" -| - "int" -| - "long" -| - "float" -| - "double" -} - -void ResultType() : -{} -{ - "void" -| - Type() -} - -void Name() : -/* - * A lookahead of 2 is required below since "Name" can be followed - * by a ".*" when used in the context of an "ImportDeclaration". - */ -{} -{ - JavaIdentifier() - ( LOOKAHEAD(2) "." JavaIdentifier() )* -} - -void NameList() : -{} -{ - Name() ( "," Name() )* -} - - -/* - * Expression syntax follows. - */ - -void Expression() : -/* - * This expansion has been written this way instead of: - * Assignment() | ConditionalExpression() - * for performance reasons. - * However, it is a weakening of the grammar for it allows the LHS of - * assignments to be any conditional expression whereas it can only be - * a primary expression. Consider adding a semantic predicate to work - * around this. - */ -{} -{ - ConditionalExpression() [ AssignmentOperator() Expression() ] -} - -void AssignmentOperator() : -{} -{ - "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "&=" | "^=" | "|=" -| - OtherAssignmentOps() -} - -void ConditionalExpression() : -{} -{ - ConditionalOrExpression() [ "?" Expression() ":" ConditionalExpression() ] -} - -void ConditionalOrExpression() : -{} -{ - ConditionalAndExpression() ( "||" ConditionalAndExpression() )* -} - -void ConditionalAndExpression() : -{} -{ - InclusiveOrExpression() ( "&&" InclusiveOrExpression() )* -} - -void InclusiveOrExpression() : -{} -{ - ExclusiveOrExpression() ( "|" ExclusiveOrExpression() )* -} - -void ExclusiveOrExpression() : -{} -{ - AndExpression() ( "^" AndExpression() )* -} - -void AndExpression() : -{} -{ - EqualityExpression() ( "&" EqualityExpression() )* -} - -void EqualityExpression() : -{} -{ - InstanceOfExpression() ( ( "==" | "!=" ) InstanceOfExpression() )* -} - -void InstanceOfExpression() : -{} -{ - RelationalExpression() [ "instanceof" Type() ] -} - -void RelationalExpression() : -{} -{ - /* - * The lookahead of 2 below is due to the fact that we have split - * the shift and shift assignment operator into multiple tokens that - * now clash with these tokens. - */ - ShiftExpression() ( LOOKAHEAD(2) ( "<" | ">" | "<=" | ">=" ) ShiftExpression() )* -} - -void ShiftExpression() : -{} -{ - /* - * The lookahead of 3 below is due to the fact that we have split - * the shift and shift assignment operator into multiple tokens that - * now clash with these tokens and the relational operators. - */ - AdditiveExpression() ( LOOKAHEAD(3) ( ShiftOps() ) AdditiveExpression() )* -} - -void AdditiveExpression() : -{} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -void MultiplicativeExpression() : -{} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -void UnaryExpression() : -{} -{ - ( "+" | "-" ) UnaryExpression() -| - PreIncrementExpression() -| - PreDecrementExpression() -| - UnaryExpressionNotPlusMinus() -} - -void PreIncrementExpression() : -{} -{ - "++" PrimaryExpression() -} - -void PreDecrementExpression() : -{} -{ - "--" PrimaryExpression() -} - -void UnaryExpressionNotPlusMinus() : -{} -{ - ( "~" | "!" ) UnaryExpression() -| - LOOKAHEAD( CastLookahead() ) - CastExpression() -| - PostfixExpression() -} - -// This production is to determine lookahead only. The LOOKAHEAD specifications -// below are not used, but they are there just to indicate that we know about -// this. -void CastLookahead() : -{} -{ - LOOKAHEAD(2) - "(" PrimitiveType() -| - LOOKAHEAD("(" Name() "[") - "(" Name() "[" "]" -| - "(" Name() ")" ( "~" | "!" | "(" | JavaIdentifier() | "this" | "super" | "new" | Literal() ) -} - -void PostfixExpression() : -{} -{ - PrimaryExpression() [ "++" | "--" ] -} - -void CastExpression() : -{} -{ - LOOKAHEAD("(" PrimitiveType()) - "(" Type() ")" UnaryExpression() -| - LOOKAHEAD("(" Name()) - "(" Type() ")" UnaryExpressionNotPlusMinus() -} - -void PrimaryExpression() : -{} -{ - PrimaryPrefix() ( LOOKAHEAD(2) PrimarySuffix() )* -} - -void PrimaryPrefix() : -{} -{ - Literal() -| - "this" -| - "super" "." JavaIdentifier() -| - "(" Expression() ")" -| - AllocationExpression() -| - LOOKAHEAD( ResultType() "." "class" ) - ResultType() "." "class" -| - Name() -} - -void PrimarySuffix() : -{} -{ - LOOKAHEAD(2) - "." "this" -| - LOOKAHEAD(2) - "." AllocationExpression() -| - "[" Expression() "]" -| - "." JavaIdentifier() -| - Arguments() -} - -void Literal() : -{} -{ - -| - -| - -| - -| - BooleanLiteral() -| - NullLiteral() -} - -void IntegerLiteral() : -{} -{ - -} - -void BooleanLiteral() : -{} -{ - "true" -| - "false" -} - -void StringLiteral() : -{} -{ - -} - -void NullLiteral() : -{} -{ - "null" -} - -void Arguments() : -{} -{ - "(" [ ArgumentList() ] ")" -} - -void ArgumentList() : -{} -{ - Expression() ( "," Expression() )* -} - -void AllocationExpression() : -{} -{ - LOOKAHEAD(2) - "new" PrimitiveType() ArrayDimsAndInits() -| - "new" Name() - ( - ArrayDimsAndInits() - | - Arguments() [ ClassBody() ] - ) -} - -/* - * The second LOOKAHEAD specification below is to parse to PrimarySuffix - * if there is an expression between the "[...]". - */ -void ArrayDimsAndInits() : -{} -{ - LOOKAHEAD(2) - ( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )* -| - ( "[" "]" )+ ArrayInitializer() -} - - -/* - * Statement syntax follows. - */ - -void Statement() : -{} -{ - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - EmptyStatement() -| - StatementExpression() ";" -| - SwitchStatement() -| - IfStatement() -| - WhileStatement() -| - DoStatement() -| - ForStatement() -| - BreakStatement() -| - ContinueStatement() -| - ReturnStatement() -| - ThrowStatement() -| - SynchronizedStatement() -| - TryStatement() -} - -void LabeledStatement() : -{} -{ - JavaIdentifier() ":" Statement() -} - -void Block() : -{} -{ - "{" ( BlockStatement() )* "}" -} - -void BlockStatement() : -{} -{ - LOOKAHEAD([ "final" ] Type() JavaIdentifier()) - LocalVariableDeclaration() ";" -| - Statement() -| - UnmodifiedClassDeclaration() -| - UnmodifiedInterfaceDeclaration() -} - -void LocalVariableDeclaration() : -{} -{ - [ "final" ] Type() VariableDeclarator() ( "," VariableDeclarator() )* -} - -void EmptyStatement() : -{} -{ - ";" -} - -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * Java expansions for StatementExpression. This expansion does not - * use PostfixExpression for performance reasons. - */ -{} -{ - PreIncrementExpression() -| - PreDecrementExpression() -| - PrimaryExpression() - [ - "++" - | - "--" - | - AssignmentOperator() Expression() - ] -} - -void SwitchStatement() : -{} -{ - "switch" "(" Expression() ")" "{" - ( SwitchLabel() ( BlockStatement() )* )* - "}" -} - -void SwitchLabel() : -{} -{ - "case" Expression() ":" -| - "default" ":" -} - -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -void DoStatement() : -{} -{ - "do" Statement() "while" "(" Expression() ")" ";" -} - -void ForStatement() : -{} -{ - "for" "(" [ ForInit() ] ";" [ Expression() ] ";" [ ForUpdate() ] ")" Statement() -} - -void ForInit() : -{} -{ - LOOKAHEAD( [ "final" ] Type() JavaIdentifier() ) - LocalVariableDeclaration() -| - StatementExpressionList() -} - -void StatementExpressionList() : -{} -{ - StatementExpression() ( "," StatementExpression() )* -} - -void ForUpdate() : -{} -{ - StatementExpressionList() -} - -void BreakStatement() : -{} -{ - "break" [ JavaIdentifier() ] ";" -} - -void ContinueStatement() : -{} -{ - "continue" [ JavaIdentifier() ] ";" -} - -void ReturnStatement() : -{} -{ - "return" [ Expression() ] ";" -} - -void ThrowStatement() : -{} -{ - "throw" Expression() ";" -} - -void SynchronizedStatement() : -{} -{ - "synchronized" "(" Expression() ")" Block() -} - -void TryStatement() : -/* - * Semantic check required here to make sure that at least one - * finally/catch is present. - */ -{} -{ - "try" Block() - ( "catch" "(" FormalParameter() ")" Block() )* - [ "finally" Block() ] -} diff --git a/examples/Lookahead/README b/examples/Lookahead/README deleted file mode 100644 index 7f40be0..0000000 --- a/examples/Lookahead/README +++ /dev/null @@ -1,823 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This directory contains the tutorial on LOOKAHEAD along with all -examples used in the tutorial. - -We assume that you have already taken a look at some of the simple -examples provided in the release before you read this section. - -1. WHAT IS LOOKAHEAD? - -The job of a parser is to read an input stream and determine whether -or not the input stream conforms to the grammar. - -This determination in its most general form can be quite time -consuming. Consider the following example (file Example1.jj): - ----------------------------------------------------------------- - - void Input() : - {} - { - "a" BC() "c" - } - - void BC() : - {} - { - "b" [ "c" ] - } - -In this simple example, it is quite clear that there are exactly two -strings that match the above grammar, namely: - - abc - abcc - -The general way to perform this match is to walk through the grammar -based on the string as follows. Here, we use "abc" as the input -string: - -Step 1. There is only one choice here - the first input character -must be 'a' - and since that is indeed the case, we are OK. - -Step 2. We now proceed on to non-terminal BC. Here again, there is -only one choice for the next input character - it must be 'b'. The -input matches this one too, so we are still OK. - -Step 3. We now come to a "choice point" in the grammar. We can either -go inside the [...] and match it, or ignore it altogether. We decide -to go inside. So the next input character must be a 'c'. We are -again OK. - -Step 4. Now we have completed with non-terminal BC and go back to -non-terminal Input. Now the grammar says the next character must be -yet another 'c'. But there are no more input characters. So we have -a problem. - -Step 5. When we have such a problem in the general case, we conclude -that we may have made a bad choice somewhere. In this case, we made -the bad choice in Step 3. So we retrace our steps back to step 3 and -make another choice and try that. This process is called -"backtracking". - -Step 6. We have now backtracked and made the other choice we could -have made at Step 3 - namely, ignore the [...]. Now we have completed -with non-terminal BC and go back to non-terminal Input. Now the -grammar says the next character must be yet another 'c'. The next -input character is a 'c', so we are OK now. - -Step 7. We realize we have reached the end of the grammar (end of -non-terminal Input) successfully. This means we have successfully -matched the string "abc" to the grammar. - ----------------------------------------------------------------- - -As the above example indicates, the general problem of matching an -input with a grammar may result in large amounts of backtracking and -making new choices and this can consume a lot of time. The amount of -time taken can also be a function of how the grammar is written. Note -that many grammars can be written to cover the same set of inputs - or -the same language (i.e., there can be multiple equivalent grammars for -the same input language). - ----------------------------------------------------------------- - -For example, the following grammar would speed up the parsing of the -same language as compared to the previous grammar: - - void Input() : - {} - { - "a" "b" "c" [ "c" ] - } - -while the following grammar slows it down even more since the parser -has to backtrack all the way to the beginning: - - void Input() : - {} - { - "a" "b" "c" "c" - | - "a" "b" "c" - } - -One can even have a grammar that looks like the following: - - void Input() : - {} - { - "a" ( BC1() | BC2() ) - } - - void BC1() : - {} - { - "b" "c" "c" - } - - void BC2() : - {} - { - "b" "c" [ "c" ] - } - -This grammar can match "abcc" in two ways, and is therefore considered -"ambiguous". - ----------------------------------------------------------------- - -The performance hit from such backtracking is unacceptable for most -systems that include a parser. Hence most parsers do not backtrack in -this general manner (or do not backtrack at all), rather they make -decisions at choice points based on limited information and then -commit to it. - -Parsers generated by Java Compiler Compiler make decisions at choice -points based on some exploration of tokens further ahead in the input -stream, and once they make such a decision, they commit to it. i.e., -No backtracking is performed once a decision is made. - -The process of exploring tokens further in the input stream is termed -"looking ahead" into the input stream - hence our use of the term -"LOOKAHEAD". - -Since some of these decisions may be made with less than perfect -information (JavaCC will warn you in these situations, so you don't -have to worry), you need to know something about LOOKAHEAD to make -your grammar work correctly. - -The two ways in which you make the choice decisions work properly are: - -. Modify the grammar to make it simpler. - -. Insert hints at the more complicated choice points to help the - parser make the right choices. - ----------------------------------------------------------------- - -2. CHOICE POINTS IN JAVACC GRAMMARS - -There are 4 different kinds of choice points in JavaCC: - -. An expansion of the form: ( exp1 | exp2 | ... ). In this case, the - generated parser has to somehow determine which of exp1, exp2, etc. - to select to continue parsing. - -. An expansion of the form: ( exp )?. In this case, the generated parser - must somehow determine whether to choose exp or to continue beyond - the ( exp )? without choosing exp. Note: ( exp )? may also be written - as [ exp ]. - -. An expansion of the form ( exp )*. In this case, the generated parser - must do the same thing as in the previous case, and furthermore, after - each time a successful match of exp (if exp was chosen) is completed, - this choice determination must be made again. - -. An expansion of the form ( exp )+. This is essentially similar to - the previous case with a mandatory first match to exp. - -Remember that token specifications that occur within angular -brackets <...> also have choice points. But these choices are made -in different ways and are the subject of a different tutorial. - ----------------------------------------------------------------- - -3. THE DEFAULT CHOICE DETERMINATION ALGORITHM - -The default choice determination algorithm looks ahead 1 token in the -input stream and uses this to help make its choice at choice points. - -The following examples will describe the default algorithm fully: - ----------------------------------------------------------------- - -Consider the following grammar (file Example2.jj): - - void basic_expr() : - {} - { - "(" expr() ")" // Choice 1 - | - "(" expr() ")" // Choice 2 - | - "new" // Choice 3 - } - -The choice determination algorithm works as follows: - - if (next token is ) { - choose Choice 1 - } else if (next token is "(") { - choose Choice 2 - } else if (next token is "new") { - choose Choice 3 - } else { - produce an error message - } - ----------------------------------------------------------------- - -In the above example, the grammar has been written such that the -default choice determination algorithm does the right thing. Another -thing to note is that the choice determination algorithm works in a -top to bottom order - if Choice 1 was selected, the other choices are -not even considered. While this is not an issue in this example -(except for performance), it will become important later below when -local ambiguities require the insertion of LOOKAHEAD hints. - -Suppose the above grammar was modified to (file Example3.jj): - - void basic_expr() : - {} - { - "(" expr() ")" // Choice 1 - | - "(" expr() ")" // Choice 2 - | - "new" // Choice 3 - | - "." // Choice 4 - } - -Then the default algorithm will always choose Choice 1 when the next -input token is and never choose Choice 4 even if the token -following is a ".". More on this later. - -You can try running the parser generated from Example3.jj on the input -"id1.id2". It will complain that it encountered a "." when it was -expecting a "(". Note - when you built the parser, it would have -given you the following warning message: - -Warning: Choice conflict involving two expansions at - line 25, column 3 and line 31, column 3 respectively. - A common prefix is: - Consider using a lookahead of 2 for earlier expansion. - -Essentially, JavaCC is saying it has detected a situation in your -grammar which may cause the default lookahead algorithm to do strange -things. The generated parser will still work using the default -lookahead algorithm - except that it may not do what you expect of it. - ----------------------------------------------------------------- - -Now consider the following example (file Example 4.jj): - - void identifier_list() : - {} - { - ( "," )* - } - -Suppose the first has already been matched and that the parser -has reached the choice point (the (...)* construct). Here's how the -choice determination algorithm works: - - while (next token is ",") { - choose the nested expansion (i.e., go into the (...)* construct) - consume the "," token - if (next token is ) consume it, otherwise report error - } - ----------------------------------------------------------------- - -In the above example, note that the choice determination algorithm -does not look beyond the (...)* construct to make its decision. -Suppose there was another production in that same grammar as follows -(file Example5.jj): - - void funny_list() : - {} - { - identifier_list() "," - } - -When the default algorithm is making a choice at ( "," )*, it -will always go into the (...)* construct if the next token is a ",". -It will do this even when identifier_list was called from funny_list -and the token after the "," is an . Intuitively, the right thing -to do in this situation is to skip the (...)* construct and return to -funny_list. More on this later. - -As a concrete example, suppose your input was "id1, id2, 5", the -parser will complain that it encountered a 5 when it was expecting an -. Note - when you built the parser, it would have given you the -following warning message: - -Warning: Choice conflict in (...)* construct at line 25, column 8. - Expansion nested within construct and expansion following construct - have common prefixes, one of which is: "," - Consider using a lookahead of 2 or more for nested expansion. - -Essentially, JavaCC is saying it has detected a situation in your -grammar which may cause the default lookahead algorithm to do strange -things. The generated parser will still work using the default -lookahead algorithm - except that it may not do what you expect of it. - ----------------------------------------------------------------- - -We have shown you examples of two kinds of choice points in the -examples above - "exp1 | exp2 | ...", and "(exp)*". The other two -kinds of choice points - "(exp)+" and "(exp)?" - behave similarly to -(exp)* and we will not be providing examples of their use here. - ----------------------------------------------------------------- - -4. MULTIPLE TOKEN LOOKAHEAD SPECIFICATIONS - -So far, we have described the default lookahead algorithm of the -generated parsers. In the majority of situations, the default -algorithm works just fine. In situations where it does not work -well, Java Compiler Compiler provides you with warning messages like -the ones shown above. If you have a grammar that goes through -Java Compiler Compiler without producing any warnings, then the -grammar is a LL(1) grammar. Essentially, LL(1) grammars are those -that can be handled by top-down parsers (such as those generated -by Java Compiler Compiler) using at most one token of LOOKAHEAD. - -When you get these warning messages, you can do one of two things. - ----------------------------------------------------------------- - -Option 1 - -You can modify your grammar so that the warning messages go away. -That is, you can attempt to make your grammar LL(1) by making some -changes to it. - -The following (file Example6.jj) shows how you may change Example3.jj -to make it LL(1): - - void basic_expr() : - {} - { - ( "(" expr() ")" | "." ) - | - "(" expr() ")" - | - "new" - } - -What we have done here is to factor the fourth choice into the first -choice. Note how we have placed their common first token outside -the parentheses, and then within the parentheses, we have yet another -choice which can now be performed by looking at only one token in the -input stream and comparing it with "(" and ".". This process of -modifying grammars to make them LL(1) is called "left factoring". - -The following (file Example7.jj) shows how Example5.jj may be changed -to make it LL(1): - - void funny_list() : - {} - { - "," ( "," )* - } - -Note that this change is somewhat more drastic. - ----------------------------------------------------------------- - -Option 2 - -You can provide the generated parser with some hints to help it out -in the non-LL(1) situations that the warning messages bring to your -attention. - -All such hints are specified using either setting the global LOOKAHEAD -value to a larger value (see below) or by using the LOOKAHEAD(...) -construct to provide a local hint. - -A design decision must be made to determine if Option 1 or Option 2 is -the right one to take. The only advantage of choosing Option 1 is -that it makes your grammar perform better. JavaCC generated parsers -can handle LL(1) constructs much faster than other constructs. -However, the advantage of choosing Option 2 is that you have a simpler -grammar - one that is easier to develop and maintain - one that -focuses on human-friendliness and not machine-friendliness. - -Sometimes Option 2 is the only choice - especially in the presence of -user actions. Suppose Example3.jj contained actions as shown below: - - void basic_expr() : - {} - { - { initMethodTables(); } "(" expr() ")" - | - "(" expr() ")" - | - "new" - | - { initObjectTables(); } "." - } - -Since the actions are different, left-factoring cannot be performed. - ----------------------------------------------------------------- - -4.1. SETTING A GLOBAL LOOKAHEAD SPECIFICATION - -You can set a global LOOKAHEAD specification by using the option -"LOOKAHEAD" either from the command line, or at the beginning of the -grammar file in the options section. The value of this option is an -integer which is the number of tokens to look ahead when making choice -decisions. As you may have guessed, the default value of this option -is 1 - which derives the default LOOKAHEAD algorithm described above. - -Suppose you set the value of this option to 2. Then the LOOKAHEAD -algorithm derived from this looks at two tokens (instead of just one -token) before making a choice decision. Hence, in Example3.jj, choice -1 will be taken only if the next two tokens are and "(", while -choice 4 will be taken only if the next two tokens are and ".". -Hence, the parser will now work properly for Example3.jj. Similarly, -the problem with Example5.jj also goes away since the parser goes into -the (...)* construct only when the next two tokens are "," and . - -By setting the global LOOKAHEAD to 2, the parsing algorithm -essentially becomes LL(2). Since you can set the global LOOKAHEAD to -any value, parsers generated by Java Compiler Compiler are called -LL(k) parsers. - ----------------------------------------------------------------- - -4.2. SETTING A LOCAL LOOKAHEAD SPECIFICATION - -You can also set a local LOOKAHEAD specification that affects only a -specific choice point. This way, the majority of the grammar can -remain LL(1) and hence perform better, while at the same time one gets -the flexibility of LL(k) grammars. Here's how Example3.jj is modified -with local LOOKAHEAD to fix the choice ambiguity problem (file -Example8.jj): - - void basic_expr() : - {} - { - LOOKAHEAD(2) - "(" expr() ")" // Choice 1 - | - "(" expr() ")" // Choice 2 - | - "new" // Choice 3 - | - "." // Choice 4 - } - -Only the first choice (the first condition in the translation below) -is affected by the LOOKAHEAD specification. All others continue to -use a single token of LOOKAHEAD: - - if (next 2 tokens are and "(" ) { - choose Choice 1 - } else if (next token is "(") { - choose Choice 2 - } else if (next token is "new") { - choose Choice 3 - } else if (next token is ) { - choose Choice 4 - } else { - produce an error message - } - -Similarly, Example5.jj can be modified as shown below (file -Example9.jj): - - void identifier_list() : - {} - { - ( LOOKAHEAD(2) "," )* - } - -Note, the LOOKAHEAD specification has to occur inside the (...)* which -is the choice is being made. The translation for this construct is -shown below (after the first has been consumed): - - while (next 2 tokens are "," and ) { - choose the nested expansion (i.e., go into the (...)* construct) - consume the "," token - consume the token - } - ----------------------------------------------------------------- - -We strongly discourage you from modifying the global LOOKAHEAD -default. Most grammars are predominantly LL(1), hence you will be -unnecessarily degrading performance by converting the entire grammar -to LL(k) to facilitate just some portions of the grammar that are not -LL(1). If your grammar and input files being parsed are very small, -then this is okay. - -You should also keep in mind that the warning messages JavaCC prints -when it detects ambiguities at choice points (such as the two messages -shown earlier) simply tells you that the specified choice points are -not LL(1). JavaCC does not verify the correctness of your local -LOOKAHEAD specification - it assumes you know what you are doing, in -fact, it really cannot verify the correctness of local LOOKAHEAD's as -the following example of if statements illustrates (file -Example10.jj): - - void IfStm() : - {} - { - "if" C() S() [ "else" S() ] - } - - void S() : - {} - { - ... - | - IfStm() - } - -This example is the famous "dangling else" problem. If you have a -program that looks like: - - "if C1 if C2 S1 else S2" - -The "else S2" can be bound to either of the two if statements. The -standard interpretation is that it is bound to the inner if statement -(the one closest to it). The default choice determination algorithm -happens to do the right thing, but it still prints the following -warning message: - -Warning: Choice conflict in [...] construct at line 25, column 15. - Expansion nested within construct and expansion following construct - have common prefixes, one of which is: "else" - Consider using a lookahead of 2 or more for nested expansion. - -To suppress the warning message, you could simply tell JavaCC that -you know what you are doing as follows: - - void IfStm() : - {} - { - "if" C() S() [ LOOKAHEAD(1) "else" S() ] - } - -To force lookahead ambiguity checking in such instances, set the option -FORCE_LA_CHECK to true. - ----------------------------------------------------------------- - -5. SYNTACTIC LOOKAHEAD - -Consider the following production taken from the Java grammar: - - void TypeDeclaration() : - {} - { - ClassDeclaration() - | - InterfaceDeclaration() - } - -At the syntactic level, ClassDeclaration can start with any number of -"abstract"s, "final"s, and "public"s. While a subsequent semantic -check will produce error messages for multiple uses of the same -modifier, this does not happen until parsing is completely over. -Similarly, InterfaceDeclaration can start with any number of -"abstract"s and "public"s. - -What if the next tokens in the input stream are a very large number of -"abstract"s (say 100 of them) followed by "interface"? It is clear -that a fixed amount of LOOKAHEAD (such as LOOKAHEAD(100) for example) -will not suffice. One can argue that this is such a weird situation -that it does not warrant any reasonable error message and that it is -okay to make the wrong choice in some pathological situations. But -suppose one wanted to be precise about this. - -The solution here is to set the LOOKAHEAD to infinity - that is set no -bounds on the number of tokens to look ahead. One way to do this is -to use a very large integer value (such as the largest possible -integer) as follows: - - void TypeDeclaration() : - {} - { - LOOKAHEAD(2147483647) - ClassDeclaration() - | - InterfaceDeclaration() - } - -One can also achieve the same effect with "syntactic LOOKAHEAD". In -syntactic LOOKAHEAD, you specify an expansion to try out and it that -succeeds, then the following choice is taken. The above example is -rewritten using syntactic LOOKAHEAD below: - - void TypeDeclaration() : - {} - { - LOOKAHEAD(ClassDeclaration()) - ClassDeclaration() - | - InterfaceDeclaration() - } - -Essentially, what this is saying is: - - if (the tokens from the input stream match ClassDeclaration) { - choose ClassDeclaration() - } else if (next token matches InterfaceDeclaration) { - choose InterfaceDeclaration() - } else { - produce an error message - } - -The problem with the above syntactic LOOKAHEAD specification is that -the LOOKAHEAD calculation takes too much time and does a lot of -unnecessary checking. In this case, the LOOKAHEAD calculation can -stop as soon as the token "class" is encountered, but the -specification forces the calculation to continue until the end of the -class declaration has been reached - which is rather time consuming. -This problem can be solved by placing a shorter expansion to try out -in the syntactic LOOKAHEAD specification as in the following example: - - void TypeDeclaration() : - {} - { - LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() - | - InterfaceDeclaration() - } - -Essentially, what this is saying is: - - if (the nest set of tokens from the input stream are a sequence of - "abstract"s, "final"s, and "public"s followed by a "class") { - choose ClassDeclaration() - } else if (next token matches InterfaceDeclaration) { - choose InterfaceDeclaration() - } else { - produce an error message - } - -By doing this, you make the choice determination algorithm stop as -soon as it sees "class" - i.e., make its decision at the earliest -possible time. - -You can place a bound on the number of tokens to consume during -syntactic lookahead as follows: - - void TypeDeclaration() : - {} - { - LOOKAHEAD(10, ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() - | - InterfaceDeclaration() - } - -In this case, the LOOKAHEAD determination is not permitted to go beyond -10 tokens. If it reaches this limit and is still successfully matching -( "abstract" | "final" | "public" )* "class", then ClassDeclaration is -selected. - -Actually, when such a limit is not specified, it defaults to the largest -integer value (2147483647). - ----------------------------------------------------------------- - -6. SEMANTIC LOOKAHEAD - -Let us go back to Example1.jj: - - void Input() : - {} - { - "a" BC() "c" - } - - void BC() : - {} - { - "b" [ "c" ] - } - -Let us suppose that there is a good reason for writing a grammar this -way (maybe the way actions are embedded). As noted earlier, this -grammar recognizes two string "abc" and "abcc". The problem here is -that the default LL(1) algorithm will choose the [ "c" ] every time -it sees a "c" and therefore "abc" will never be matched. We need to -specify that this choice must be made only when the next token is a -"c", and the token following that is not a "c". This is a negative -statement - one that cannot be made using syntactic LOOKAHEAD. - -We can use semantic LOOKAHEAD for this purpose. With semantic -LOOKAHEAD, you can specify any arbitrary boolean expression whose -evaluation determines which choice to take at a choice point. The -above example can be instrumented with semantic LOOKAHEAD as follows: - - void BC() : - {} - { - "b" - [ LOOKAHEAD( { getToken(1).kind == C && getToken(2).kind != C } ) - - ] - } - -First we give the token "c" a label C so that we can refer to it from -the semantic LOOKAHEAD. The boolean expression essentially states the -desired property. The choice determination decision is therefore: - - if (next token is "c" and following token is not "c") { - choose the nested expansion (i.e., go into the [...] construct) - } else { - go beyond the [...] construct without entering it. - } - -This example can be rewritten to combine both syntactic and semantic -LOOKAHEAD as follows (recognize the first "c" using syntactic -LOOKAHEAD and the absence of the second using semantic LOOKAHEAD): - - void BC() : - {} - { - "b" - [ LOOKAHEAD( "c", { getToken(2).kind != C } ) - - ] - } - ----------------------------------------------------------------- - -7. GENERAL STRUCTURE OF LOOKAHEAD - -We've pretty much covered the various aspects of LOOKAHEAD in the -previous sections. A couple of advanced topics follow. However, -we shall now present a formal language reference for LOOKAHEAD in -Java Compiler Compiler: - -The general structure of a LOOKAHEAD specification is: - - LOOKAHEAD( amount, - expansion, - { boolean_expression } - ) - -"amount" specifies the number of tokens to LOOKAHEAD,"expansion" -specifies the expansion to use to perform syntactic LOOKAHEAD, and -"boolean_expression" is the expression to use for semantic -LOOKAHEAD. - -At least one of the three entries must be present. If more than -one are present, they are separated by commas. The default values -for each of these entities is defined below: - -"amount": - - if "expansion is present, this defaults to 2147483647. - - otherwise ("boolean_expression" must be present then) this - defaults to 0. - -Note: When "amount" is 0, no syntactic LOOKAHEAD is performed. Also, -"amount" does not affect the semantic LOOKAHEAD. - -"expansion": -- defaults to the expansion being considered. - -"boolean_expression": - -- defaults to true. - ----------------------------------------------------------------- - -8. NESTED EVALUATION OF SEMANTIC LOOKAHEAD - -TBD - ----------------------------------------------------------------- - -9. JAVACODE PRODUCTIONS - -TBD - ----------------------------------------------------------------- diff --git a/examples/Lookahead/pom.xml b/examples/Lookahead/pom.xml deleted file mode 100644 index ba57246..0000000 --- a/examples/Lookahead/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - lookahead - jar - - JavaCC Java code generator / examples / Lookahead - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - exec-rldt8 - test - - java - - - ${skip.test.java.examples.lookahead} - rldt8.ReadingLookaheadDebugTrace_Example8 - - - - - - - - \ No newline at end of file diff --git a/examples/Lookahead/src/main/javacc/Example1.jj b/examples/Lookahead/src/main/javacc/Example1.jj deleted file mode 100644 index 3cc4c18..0000000 --- a/examples/Lookahead/src/main/javacc/Example1.jj +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex1; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.Input(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void Input() : -{} -{ - "a" BC() "c" -} - -void BC() : -{} -{ - "b" - [ - LOOKAHEAD(2) - "c" - ] -} diff --git a/examples/Lookahead/src/main/javacc/Example10.jj b/examples/Lookahead/src/main/javacc/Example10.jj deleted file mode 100644 index 279d4fb..0000000 --- a/examples/Lookahead/src/main/javacc/Example10.jj +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex10; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.IfStm(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void IfStm() : -{} -{ - "if" C() S() - [ - LOOKAHEAD(2) - "else" S() - ] -} - -void C() : -{} -{ - "TBD" -} - -void S() : -{} -{ - "TBD" -| - IfStm() -} diff --git a/examples/Lookahead/src/main/javacc/Example2.jj b/examples/Lookahead/src/main/javacc/Example2.jj deleted file mode 100644 index 19732fb..0000000 --- a/examples/Lookahead/src/main/javacc/Example2.jj +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex2; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.basic_expr(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void basic_expr() : -{} -{ - "(" expr() ")" -| - "(" expr() ")" -| - "new" -} - -void expr() : -{} -{ - "TBD" -} - -TOKEN [IGNORE_CASE] : -{ - < ID : (["a"-"z"])+ > -} diff --git a/examples/Lookahead/src/main/javacc/Example3.jj b/examples/Lookahead/src/main/javacc/Example3.jj deleted file mode 100644 index f7c6400..0000000 --- a/examples/Lookahead/src/main/javacc/Example3.jj +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex3; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.basic_expr(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void basic_expr() : -{} -{ - LOOKAHEAD(2) - "(" expr() ")" -| - "(" expr() ")" -| - "new" -| - "." -} - -void expr() : -{} -{ - "TBD" -} - -TOKEN [IGNORE_CASE] : -{ - -} diff --git a/examples/Lookahead/src/main/javacc/Example4.jj b/examples/Lookahead/src/main/javacc/Example4.jj deleted file mode 100644 index f3a8d6f..0000000 --- a/examples/Lookahead/src/main/javacc/Example4.jj +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex4; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.identifier_list(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void identifier_list() : -{} -{ - ( "," )* -} - -TOKEN [IGNORE_CASE] : -{ - -} diff --git a/examples/Lookahead/src/main/javacc/Example5.jj b/examples/Lookahead/src/main/javacc/Example5.jj deleted file mode 100644 index e053456..0000000 --- a/examples/Lookahead/src/main/javacc/Example5.jj +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex5; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.funny_list(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void identifier_list() : -{} -{ - - ( - LOOKAHEAD(2) - "," - )* -} - -void funny_list() : -{} -{ - identifier_list() "," -} - -TOKEN [IGNORE_CASE] : -{ - -| - -} diff --git a/examples/Lookahead/src/main/javacc/Example6.jj b/examples/Lookahead/src/main/javacc/Example6.jj deleted file mode 100644 index 8fb0592..0000000 --- a/examples/Lookahead/src/main/javacc/Example6.jj +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex6; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.basic_expr(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void basic_expr() : -{} -{ - ( "(" expr() ")" | "." ) -| - "(" expr() ")" -| - "new" -} - -void expr() : -{} -{ - "TBD" -} - -TOKEN [IGNORE_CASE] : -{ - -} diff --git a/examples/Lookahead/src/main/javacc/Example7.jj b/examples/Lookahead/src/main/javacc/Example7.jj deleted file mode 100644 index a396237..0000000 --- a/examples/Lookahead/src/main/javacc/Example7.jj +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex7; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.funny_list(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void funny_list() : -{} -{ - "," ( "," )* -} - -TOKEN [IGNORE_CASE] : -{ - -| - -} diff --git a/examples/Lookahead/src/main/javacc/Example8.jj b/examples/Lookahead/src/main/javacc/Example8.jj deleted file mode 100644 index cb04018..0000000 --- a/examples/Lookahead/src/main/javacc/Example8.jj +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex8; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.basic_expr(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void basic_expr() : -{} -{ - LOOKAHEAD(2) - "(" expr() ")" -| - "(" expr() ")" -| - "new" -| - "." -} - -void expr() : -{} -{ - "TBD" -} - -TOKEN [IGNORE_CASE] : -{ - -} diff --git a/examples/Lookahead/src/main/javacc/Example9.jj b/examples/Lookahead/src/main/javacc/Example9.jj deleted file mode 100644 index 33570d5..0000000 --- a/examples/Lookahead/src/main/javacc/Example9.jj +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -PARSER_BEGIN(Example) -package ex9; - -public class Example { - - public static void main(String args[]) throws ParseException { - Example parser = new Example(System.in); - parser.funny_list(); - } - -} - -PARSER_END(Example) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -void identifier_list() : -{} -{ - ( LOOKAHEAD(2) "," )* -} - -void funny_list() : -{} -{ - identifier_list() "," -} - -TOKEN [IGNORE_CASE] : -{ - -| - -} diff --git a/examples/Lookahead/src/main/javacc/NestedLookaheadGrammar_Example11.jj b/examples/Lookahead/src/main/javacc/NestedLookaheadGrammar_Example11.jj deleted file mode 100644 index dcb6f7c..0000000 --- a/examples/Lookahead/src/main/javacc/NestedLookaheadGrammar_Example11.jj +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Small grammar to investigate nested lookaheads generation. - */ -options -{ - static = false; - FORCE_LA_CHECK = true; // (JavaCC - default false) - ERROR_REPORTING = true; - OUTPUT_DIRECTORY = "nlg11"; -} - -PARSER_BEGIN(NestedLookaheadGrammar_Example11) -package nlg11; - -import java.io.StringReader; - -public class NestedLookaheadGrammar_Example11 -{ - static String input [] = new String [] { "to-be-defined" }; - - public static void main(String args []) throws ParseException - { - NestedLookaheadGrammar_Example11 parser = null; - for (int i = 0; i < input.length; i++) - { - parser = new NestedLookaheadGrammar_Example11(new StringReader(input[i])); - parser.A(); - } - } - - /* for semantic lookaheads conditions, which can be employed outside the productions' methods */ - boolean a5 = true, a9 = true, a10 = true, a11 = true, a12 = true, a13 = true, a14 = true, a15 = true; - boolean b5 = true, b9 = true, b10 = true, b11 = true, b12 = true, b13 = true, b14 = true, b15 = true; - -} -PARSER_END(NestedLookaheadGrammar_Example11) - -SKIP : -{ - " " -| "\r" -| "\t" -| "\n" -} - -TOKEN : /* OPERATORS, DELIMITERS, KEYWORDS */ -{ - < V_1 : "v_1" > -| < V_2 : "v_2" > -| < V_3 : "v_3" > -| < V_4 : "v_4" > -| < V_5 : "v_5" > -| < V_6 : "v_6" > -| < V_7 : "v_7" > -| < V_8 : "v_8" > -| < V_9 : "v_9" > -| < V_10 : "v_10" > -| < V_11 : "v_11" > -| < V_12 : "v_12" > -| < V_13 : "v_13" > -| < V_14 : "v_14" > -| < V_15 : "v_15" > -| < X_1 : "x_1" > -| < X_2 : "x_2" > -| < X_3 : "x_3" > -| < X_4 : "x_4" > -| < X_5 : "x_5" > -| < X_6 : "x_6" > -| < X_7 : "x_7" > -| < X_8 : "x_8" > -| < X_9 : "x_9" > -| < X_10 : "x_10" > -| < X_11 : "x_11" > -| < X_12 : "x_12" > -| < X_13 : "x_13" > -| < X_14 : "x_14" > -| < X_15 : "x_15" > -| < T_ : "_t" > -| < W_ : "_w" > -| < Y_ : "_y" > -| < Z_ : "_z" > -} - -void A() : {} -{ - // (if uncommented) A() has no lookahead and is truncated (no choices after) -// LOOKAHEAD(0) -// B() "v_1" -//| - LOOKAHEAD(1) // jj_2_1, jj_3_1, jj_3R_B_170_3_1 - B() "v_2" -| - LOOKAHEAD(2) // jj_2_2, jj_3_2, jj_3R_B_170_3_1 - B() "v_3" -| - LOOKAHEAD(B()) // jj_2_3, jj_3_3, jj_3R_B_170_3_1 - B() "v_4" -| - LOOKAHEAD({ a5 }) // a5 - B() "v_5" -| - // (if uncommented) A() has no lookahead and is truncated (no choices after) -// LOOKAHEAD(0, B()) -// B() "v_6" -//| - LOOKAHEAD(1, B()) // jj_2_4, jj_3_4, jj_3R_B_170_3_1 - B() "v_7" -| - LOOKAHEAD(2, B()) // jj_2_5, jj_3_5, jj_3R_B_170_3_1 - B() "v_8" -| - LOOKAHEAD(B(), { a9 }) // jj_2_6 && a9, jj_3_6, jj_3R_B_170_3_1 - B() "v_9" -| - LOOKAHEAD(0, { a10 }) // a10 - B() "v_10" -| - LOOKAHEAD(1, { a11 }) // jj_2_7 && a11, jj_3_7, jj_3R_B_170_3_1 - B() "v_11" -| - LOOKAHEAD(2, { a12 }) // jj_2_8 && a12, jj_3_8, jj_3R_B_170_3_1 - B() "v_12" -| - LOOKAHEAD(0, B(), { a13 }) // b13 - B() "v_13" -| - LOOKAHEAD(1, B(), { a14 }) // jj_2_9 && a14, jj_3_9, jj_3R_B_170_3_1 - B() "v_14" -| - LOOKAHEAD(2, B(), { a15 }) // jj_2_10 && a15, jj_3_10, jj_3R_B_170_3_1 - B() "v_15" -| - C() "_w" -} - -void B() : {} -{ - // (if uncommented) B() has no lookahead and is truncated (no choices after) (but this does not affect A-lookahead) -// LOOKAHEAD(0) -// C() "x_1" // jj_3R_B_138_3_2 -//| - LOOKAHEAD(1) - C() "x_2" // (la jj_3R_B_170_3_1 ->) jj_3R_B_170_3_3, jj_3R_C_218_3_2 -| - LOOKAHEAD(2) - C() "x_3" // (la jj_3R_B_170_3_1 ->) jj_3_11, jj_3R_C_218_3_2 -| - LOOKAHEAD(C()) - C() "x_4" // (la jj_3R_B_170_3_1 ->) jj_3R_B_176_3_4, jj_3R_C_218_3_2 -| - LOOKAHEAD({ b5 }) - C() "x_5" // (la jj_3R_B_170_3_1 ->) b5 && jj_3R_B_179_3_5, jj_3R_C_218_3_2 -| - // (if uncommented) B() has no lookahead and is truncated (no choices after) (but this does not affect A-lookahead) -// LOOKAHEAD(0, C()) -// C() "x_6" // jj_3R_B_189_3_7 -//| - LOOKAHEAD(1, C() "x_7" ) - C() "x_7" // (la jj_3R_B_170_3_1 ->) jj_3R_B_186_3_6, jj_3R_C_218_3_2 -| - LOOKAHEAD(2, C()) - C() "x_8" // (la jj_3R_B_170_3_1 ->) jj_3R_B_189_3_7, jj_3R_C_218_3_2 -| - LOOKAHEAD(C(), { b9 }) - C() "x_9" // (la jj_3R_B_170_3_1 ->) b9 && jj_3R_B_192_3_8, jj_3R_C_218_3_2 -| - LOOKAHEAD(0, { b10 }) - C() "x_10" // (la jj_3R_B_170_3_1 ->) b10 && jj_3R_B_195_3_9, jj_3R_C_218_3_2 -| - LOOKAHEAD(1, { b11 }) - C() "x_11" // (la jj_3R_B_170_3_1 ->) b11 && jj_3_15 (why not a 3R as in v7?), jj_3R_C_218_3_2 -| - LOOKAHEAD(2, { b12 }) - C() "x_12" // (la jj_3R_B_170_3_1 ->) b12 && jj_3_16 (why not a 3R as in v7?), jj_3R_C_218_3_2 -| - LOOKAHEAD(0, C(), { b13 }) - C() "x_13" // (la jj_3R_B_170_3_1 ->) b13 && jj_3R_B_204_3_10, jj_3R_C_218_3_2 -| - LOOKAHEAD(1, C(), { b14 }) - C() "x_14" // (la jj_3R_B_170_3_1 ->) b14 && jj_3R_B_207_3_11, jj_3R_C_218_3_2 -| - LOOKAHEAD(2, C(), { b15 }) - C() "x_15" // (la jj_3R_B_170_3_1 ->) b15 && jj_3R_B_210_3_12, jj_3R_C_218_3_2 -| - "_t" "_y" // (la jj_3R_B_170_3_1 ->) jj_3R_B_213_3_13, jj_3R_C_218_3_2 -} - -void C() : {} -{ - "_t" "_z" // jj_3R_C_218_3_18 in jj_3R_B_lll_ccc_n and some jj_3_n -} - diff --git a/examples/Lookahead/src/main/javacc/NonChoiceLookaheadGrammar_Example12.jj b/examples/Lookahead/src/main/javacc/NonChoiceLookaheadGrammar_Example12.jj deleted file mode 100644 index 189d336..0000000 --- a/examples/Lookahead/src/main/javacc/NonChoiceLookaheadGrammar_Example12.jj +++ /dev/null @@ -1,1419 +0,0 @@ -/* - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Small grammar to investigate lookaheads at non choice points. - */ -options -{ - static = false; -// FORCE_LA_CHECK = true; // (JavaCC - default false) - ERROR_REPORTING = true; - OUTPUT_DIRECTORY = "nclg12"; -} - -PARSER_BEGIN(NonChoiceLookaheadGrammar_Example12) -package nclg12; - -import java.io.StringReader; - -public class NonChoiceLookaheadGrammar_Example12 -{ - static String inputA [] = new String [] // - { // - "v0 x0 end", // ok - "v1 x1 end", // ok - "v2 x2 end", // pe, reads "x2" expects eof - "v2", // pe, reads eof expects "x2" - "v3 x3 end", // pe, just throws pe - "v3", // pe, reads eof expects "x3" - "v4 x4 end", // pe, just throws pe - "v4", // pe, reads eof expects "x4" - "v5 x5 end", // ok (sem la true) - "x5 v5 end", // pe, just throws pe (sem la false) - "v6 x6 end", // ok - "v7 x7 end", // pe, reads "x7" expects eof - "v7", // pe, reads eof expects "x7" - "v8 x8 end", // pe, just throws pe - "v8", // pe, reads eof expects "x8" - "v9 x9 end", // pe, just throws pe - "v9", // pe, reads eof expects "x9" - "x9 v9 end", // pe, just throws pe - "x9", // pe, just throws pe - "v10 x10 end", // ok - "x10 v10 end", // pe, just throws pe - "v11 x11 end", // pe, just throws pe - "v11", // pe, reads eof expects "x11" - "x11 v11 end", // pe, just throws pe - "x11", // pe, just throws pe - "v12 x12 end", // pe, just throws pe - "v12", // pe, reads eof expects "x12" - "x12 v12 end", // pe, just throws pe - "x12", // pe, just throws pe - "v13 x13 end", // ok - "v13", // pe, reads eof expects "x13" - "x13 v13 end", // pe, just throws pe - "x13", // pe, just throws pe - "v14 x14 end", // pe, just throws pe - "v14", // pe, reads eof expects "x14" - "x14 v14 end", // pe, just throws pe - "v15 x15 end", // pe, just throws pe - "v15", // pe, reads eof expects "x15" - "x15 v15 end", // pe, just throws pe - }; - - static String inputE [] = new String [] // - { // - "v0 x0 end", // ok -// "v1 x1 end", // compiler error - "v2 x2 end", // ok - "v2", // pe, reads eof expects "x2" or "end" - "v3 x3 end", // ok - "v3", // pe, reads eof expects "end" - "v4 x4 end", // ok - "v4", // pe, reads eof expects "end" - "v5 x5 end", // pe, reads "end" expects "x5" - "x5 v5 end", // pe, reads "v5" expects "end" -// "v6 x6 end", // compiler error - "v7 x7 end", // ok - "v7", // pe, reads eof expects "x7" - "v8 x8 end", // ok - "v8", // pe, reads eof expects "end" - "v9 x9 end", // ok - "v9", // pe, reads eof expects "end" - "x9 v9 end", // ok - "x9", // pe, reads eof expects "end" - "v10 x10 end", // pe, reads "end" expects "x10" - "x10 v10 end", // pe, reads "v10" expects "end" - "v11 x11 end", // ok - "v11", // pe, reads eof expects "end" - "x11 v11 end", // pe, reads "v11" expects "end" - "x11", // pe, reads eof expects "end" - "v12 x12 end", // ok - "v12", // pe, reads eof expects "end" - "x12 v12 end", // pe, reads "v12" expects "end" - "x12", // pe, reads eof expects "end" - "v13 x13 end", // pe, reads "end" expects "x13" - "v13", // pe, reads eof expects "x13" - "x13 v13 end", // pe, reads "v13" expects "end" - "x13", // pe, reads eof expects "end" - "v14 x14 end", // ok - "v14", // pe, reads eof expects "end" - "x14 v14 end", // pe, reads "v14" expects "end" - "v15 x15 end", // ok - "v15", // pe, reads eof expects "end" - "x15 v15 end", // pe, reads "v15" expects "end" - }; - - /** standard main running on internal input */ - public static void main(String args []) throws ParseException - { - NonChoiceLookaheadGrammar_Example12 parser = null; - // A() - System.out.println("****************************"); - System.out.println("*** Running input on A() ***"); - System.out.println("****************************"); - for (int i = 0; i < inputA.length; i++) - { - System.out.println("input " + i+ " : " + inputA[i]); - parser = new NonChoiceLookaheadGrammar_Example12(new StringReader(inputA[i])); - try { parser.A(); } - // catch PE & TMR for running all the test suite - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - } - // E() - System.out.println("****************************"); - System.out.println("*** Running input on E() ***"); - System.out.println("****************************"); - for (int i = 0; i < inputE.length; i++) - { - System.out.println("input " + i+ " : " + inputE[i]); - parser = new NonChoiceLookaheadGrammar_Example12(new StringReader(inputE[i])); - try { parser.E(); } - // catch PE & TMR for running all the test suite - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - } - } - - /** report problem with version info */ - void report(final String aStr) - { - System.out.println(prod_name + " swallowed " + aStr); - } - - /** the current production name, for reporting */ - String prod_name = null; - - /* for semantic lookaheads conditions, which can be employed outside the productions' methods */ - boolean a5 = true, a9 = true, a10 = true, a11 = true, a12 = true, a13 = true, a14 = true, a15 = true; - boolean d = true; - -} -PARSER_END(NonChoiceLookaheadGrammar_Example12) - -SKIP : -{ - " " -| "\r" -| "\t" -| "\n" -} - -TOKEN : -{ - < V0 : "v0" > -| < V1 : "v1" > -| < V2 : "v2" > -| < V3 : "v3" > -| < V4 : "v4" > -| < V5 : "v5" > -| < V6 : "v6" > -| < V7 : "v7" > -| < V8 : "v8" > -| < V9 : "v9" > -| < V10 : "v10" > -| < V11 : "v11" > -| < V12 : "v12" > -| < V13 : "v13" > -| < V14 : "v14" > -| < V15 : "v15" > -| < X0 : "x0" > -| < X1 : "x1" > -| < X2 : "x2" > -| < X3 : "x3" > -| < X4 : "x4" > -| < X5 : "x5" > -| < X6 : "x6" > -| < X7 : "x7" > -| < X8 : "x8" > -| < X9 : "x9" > -| < X10 : "x10" > -| < X11 : "x11" > -| < X12 : "x12" > -| < X13 : "x13" > -| < X14 : "x14" > -| < X15 : "x15" > -| < END : "end" > -| < D : "d" > -} - -/* non conflicting choices, and inside each choice a LOOKAHEAD at a non choice location, - and not in [], ()?, ()*, ()+ */ -void A() : {} -{ - { prod_name = "A"; } - ( - "v0" - "x0" "end" - | - "v1" - // no warning but indeed IGNORED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(0) // nothing - "x1" "end" - | - "v2" - // "at non choice location; ignored" but somewhat WRONG: - // anything else than EOF throws a ParseException, and EOF will continue parsing on next tokens - // reads "x2" but expects if "x2" is in the input, and if not reads but expects "x2" - // so NOT A MEANINGFUL behavior - LOOKAHEAD(1) // switch jj_ntk case EOF - "x2" "end" - | - "v3" - // "at non choice location; ignored" but somewhat WRONG: - // anything else than EOF throws a ParseException, and EOF will continue parsing on next tokens - // reads "" but expects nothing if "x3" is in the input, and if not reads but expects "x3" - // so NOT A MEANINGFUL behavior - LOOKAHEAD(2) // jj_2_1 - "x3" "end" - | - "v4" - // "at non choice location; ignored" but somewhat WRONG: - // anything else than EOF throws a ParseException, and EOF will continue parsing on next tokens - // reads "" but expects nothing if "x4" is in the input, and if not reads but expects "x4" - // so NOT A MEANINGFUL behavior - LOOKAHEAD("x4") // jj_2_2 - "x4" "end" - | - "v5" - // no warning but indeed CONSIDERED - // a5 false gives a ParseException (amount 0), and a5 true continues parsing on next tokens - // so SOME CORNER CASES MEANINGFUL behavior - LOOKAHEAD({ a5 }) // a5 - "x5" "end" - | - "x5" - // no warning but indeed CONSIDERED - // (opposite of previous) - // !a5 false gives a ParseException (amount 0), and !a5 true continues parsing on next tokens - // so NOT A VERY MEANINGFUL behavior - LOOKAHEAD({ !a5 }) // !a5 - "v5" "end" - | - "v6" - // no warning but indeed IGNORED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(0, "x6") // nothing - "x6" "end" - | - "v7" - // "at non choice location; ignored" but somewhat WRONG: - // anything else than EOF throws a ParseException, and EOF will continue parsing on next tokens - // reads "x7" but expects if "x7" is in the input, and if not reads but expects "x7" - // so NOT A MEANINGFUL behavior - LOOKAHEAD(1, "x7") // switch jj_ntk case EOF - "x7" "end" - | - "v8" - // "at non choice location; ignored" but somewhat WRONG: - // anything else than EOF throws a ParseException, and EOF will continue parsing on next tokens - // reads "" but expects nothing if "x8" is in the input, and if not reads but expects "x8" - // so NOT A MEANINGFUL behavior - LOOKAHEAD(2, "x8") // jj_2_3 - "x8" "end" - | - "v9" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a9: - // a9 false gives a ParseException, and a9 true continues parsing on next tokens - // so NOT A MEANINGFUL behavior - LOOKAHEAD("x9", { a9 }) // jj_2_4 && a9 - "x9" "end" - | - "x9" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // (opposite of previous) - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a9: - // !a9 false gives a ParseException, and !a9 true continues parsing on next tokens - // so NOT A MEANINGFUL behavior - LOOKAHEAD("v9", { !a9 }) // jj_2_5 && !a9 - "v9" "end" - | - "v10" - // no warning but indeed CONSIDERED - // a10 false gives a ParseException, and a10 true continues parsing on next tokens - // so SOME CORNER CASES MEANINGFUL behavior - LOOKAHEAD(0, { a10 }) // a10 - "x10" "end" - | - "x10" - // no warning but indeed CONSIDERED - // (opposite of previous) - // !a10 false gives a ParseException (amount 0), and !a10 true continues parsing on next tokens - // so SOME CORNER CASES MEANINGFUL behavior - LOOKAHEAD(0, { !a10 }) // a10 - "v10" "end" - | - "v11" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a11: - // a11 false gives a ParseException, and a11 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(1, { a11 }) // jj_2_6 && a11 - "x11" "end" - | - "x11" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // (opposite of previous) - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a11: - // !a11 false gives a ParseException, and !a11 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(1, { !a11 }) // jj_2_7 && a11 - "v11" "end" - | - "v12" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a12: - // a12 false gives a ParseException, and a12 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(2, { a12 }) // jj_2_8 && a12 - "x12" "end" - | - "x12" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // (opposite of previous) - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a12: - // !a12 false gives a ParseException, and !a12 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(2, { !a12 }) // jj_2_8 && a12 - "v12" "end" - | - "v13" - // no warning but indeed CONSIDERED - // a13 false gives a ParseException, and a13 true continues parsing on next tokens - // so SOME CORNER CASES MEANINGFUL behavior - LOOKAHEAD(0, "x13", { a13 }) // a13 - "x13" "end" - | - "x13" - // no warning but indeed CONSIDERED - // (opposite of previous) - // !a13 false gives a ParseException, and !a13 true continues parsing on next tokens - // so SOME CORNER CASES MEANINGFUL behavior - LOOKAHEAD(0, "v13", { !a13 }) // a13 - "v13" "end" - | - "v14" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a14: - // a14 false gives a ParseException, and a14 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(1, "x14", { a14 }) // jj_2_9 && a14 - "x14" "end" - | - "x14" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // (opposite of previous) - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a14: - // !a14 false gives a ParseException, and !a14 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(1, "v14", { !a14 }) // jj_2_10 && a14 - "v14" "end" - | - "v15" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a15: - // a15 false gives a ParseException, and a15 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(2, "x15", { a15 }) // jj_2_11 && a15 - "x15" "end" - | - "x15" - // "at non choice location; only semantic lookahead considered": almost RIGHT: - // (opposite of previous) - // anything else than EOF throws a ParseException, and EOF will continue on evaluating a15: - // !a15 false gives a ParseException, and !a15 true continues parsing on next tokens - // so OF NO USEFUL MEANING - LOOKAHEAD(2, "v15", { !a15 }) // jj_2_12 && a15 - "v15" "end" - ) - { System.out.println("End A"); } -} - -// same as A() but with terminals "x_nn" "end" replaced by non-terminal X0_END(), and opposite cases dropped: -// the generated method structure is the same -void B() : -{} -{ - { prod_name = "B"; } - ( - "v0" - X0_END() - | - "v1" - LOOKAHEAD(0) - X0_END() - | - "v2" - LOOKAHEAD(1) - X0_END() - | - "v3" - LOOKAHEAD(2) - X0_END() - | - "v4" - LOOKAHEAD(X0_END()) - X0_END() - | - "v5" - LOOKAHEAD({ a5 }) - X0_END() - | - "v6" - LOOKAHEAD(0, X0_END()) - X0_END() - | - "v7" - LOOKAHEAD(1, X0_END()) - X0_END() - | - "v8" - LOOKAHEAD(2, X0_END()) - X0_END() - | - "v9" - LOOKAHEAD(X0_END(), { a9 }) - X0_END() - | - "v10" - LOOKAHEAD(0, { a10 }) - X0_END() - | - "v11" - LOOKAHEAD(1, { a11 }) - X0_END() - | - "v12" - LOOKAHEAD(2, { a12 }) - X0_END() - | - "v13" - LOOKAHEAD(0, X0_END(), { a13 }) - X0_END() - | - "v14" - LOOKAHEAD(1, X0_END(), { a14 }) - X0_END() - | - "v15" - LOOKAHEAD(2, X0_END(), { a15 }) - X0_END() - ) - { System.out.println("End B"); } -} - -void X0_END() : {} -{ - "x0" "end" -} - -// same as B() with non-terminal X0_END() replaced by empty non-terminal Epsilon(): -// the generated method structure is still the same -void C() : {} -{ - "x0" - Epsilon() -| - "x1" - LOOKAHEAD(0) - Epsilon() -| - "x2" - LOOKAHEAD(1) - Epsilon() -| - "x3" - LOOKAHEAD(2) - Epsilon() -| - "x4" - LOOKAHEAD(Epsilon()) - Epsilon() -| - "x5" - LOOKAHEAD({ a5 }) - Epsilon() -| - "x6" - LOOKAHEAD(0, Epsilon()) - Epsilon() -| - "x7" - LOOKAHEAD(1, Epsilon()) - Epsilon() -| - "x8" - LOOKAHEAD(2, Epsilon()) - Epsilon() -| - "x9" - LOOKAHEAD(Epsilon(), { a9 }) - Epsilon() -| - "x10" - LOOKAHEAD(0, { a5 }) - Epsilon() -| - "x11" - LOOKAHEAD(1, { a5 }) - Epsilon() -| - "x12" - LOOKAHEAD(2, { a5 }) - Epsilon() -| - "x13" - LOOKAHEAD(0, Epsilon(), { a5 }) - Epsilon() -| - "x14" - LOOKAHEAD(1, Epsilon(), { a5 }) - Epsilon() -| - "x15" - LOOKAHEAD(2, Epsilon(), { a5 }) - Epsilon() -} - -// EMPTY generated method!!! -void Epsilon() : {} -{ - {} -} - -// same as A() with only empty production ({}), expansions in LOOKAHEADs being "" or "d" and expressions d -// EMPTY generated method!!! -void D() : {} -{ - // choice can expand to empty token sequence always taken in favor of choices appearing later -// {} -//| - LOOKAHEAD(0) - {} -| - LOOKAHEAD(1) - {} -| - LOOKAHEAD(2) - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD("") -// {} -//| - LOOKAHEAD("d") - {} -| - LOOKAHEAD({ d }) - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(0, "") -// {} -//| - LOOKAHEAD(0, "d") - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(1, "") -// {} -//| - LOOKAHEAD(1, "d") - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(2, "") -// {} -//| - LOOKAHEAD(2, "d") - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD("", { a9 }) -// {} -//| - LOOKAHEAD("d", { d }) - {} -| - LOOKAHEAD(0, { d }) - {} -| - LOOKAHEAD(1, { d }) - {} -| - LOOKAHEAD(2, { d }) - {} -//| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(0, "", { a5 }) -// {} -//| - // "at non choice location; only semantic lookahead considered": WRONG: nothing generated - LOOKAHEAD(1, "d", { d }) - {} -| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(1, "", { a5 }) -// {} -//| -// Regular expression can be matched by empty string. can result in an endless loop of empty string matches -// LOOKAHEAD(2, "", { a5 }) -// {} - LOOKAHEAD(2, "d", { d }) - {} -} - -// same as A() but "x_nn" being in optional construct ()* -void E() : {} -{ - { prod_name = "E"; } - ( - "v0" - ("x0")* // label_1 while, switch X0 default - "end" -// | -// "v1" -// ( -// // no warning but indeed CONSIDERED -// // endless loop on consume X1, unreachable code, compiler error -// // so of NO USE -// LOOKAHEAD(0) // label_2 while, no switch endless loop X1 -// "x1" -// )* -// "end" - | - "v2" - ( - // no warning but indeed IGNORED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(1) // label_2 while, switch X2 default scans 1 token - "x2" - )* - "end" - | - "v3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // label_3, while jj_2_31 scans 1 token - "x3" - )* - "end" - | - "x3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // label_4, while jj_2_32 scans 2 tokens - "v3" "x0" - )* - "end" - | - "v4" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD("x4") // label_5, while jj_2_33 scans 1 token - "x4" - )* - "end" - | - "v5" - ( - // no warning but indeed CONSIDERED - // makes "x5" mandatory for each evaluation of a5 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD({ a5 }) // label_6, while a5 consumes 1 token - "x5" - )* - "end" - | - "x5" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD({ !a5 }) // label_7, while !a5 consumes 1 token - "v5" - )* - "end" -// | -// "v6" -// ( -// // no warning but indeed CONSIDERED -// // endless loop on consume X6, unreachable code, compiler error -// // so of NO USE -// LOOKAHEAD(0, "x6") // label_8 while, no switch endless loop X6 -// "x6" -// )* -// "end" - | - "v7" - ( - // no warning but indeed IGNORED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(1, "x7") // label_8 while, switch X7 default scans 1 token - "x7" - )* - "end" - | - "v8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "x8") // label_9, while jj_2_34 scans 1 token - "x8" - )* - "end" - | - "x8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "v8") // label_10, while jj_2_35 scans 1 token (not 2 tokens) - "v8" "x0" - )* - "end" - | - "v9" - ( - // no warning but indeed CONSIDERED - // scans for "x9" then evaluates a9 - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD("x9", { a9 }) // label_11, while jj_2_36 && a9 scans 1 token - "x9" - )* - "end" - | - "x9" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // scans for "v9" then evaluates !a9 - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD("v9", { !a9 }) // label_12, while jj_2_37 && !a9 scans 1 token - "v9" - )* - "end" - | - "v10" - ( - // no warning but indeed CONSIDERED - // makes "x10" mandatory for each evaluation of a10 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD(0, { a10 }) // label_13, while a10 consumes 1 token - "x10" - )* - "end" - | - "x10" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v10" mandatory for each evaluation of !a10 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD(0, { !a10 }) // label_14, while !a10 consumes 1 token - "v10" - )* - "end" - | - "v11" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD(1, { a11 }) // label_15, while jj_2_38 && a11 scans 1 token - "x11" - )* - "end" - | - "x11" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD(1, { !a11 }) // label_16, while jj_2_39 && a11 scans 1 token - "v11" - )* - "end" - | - "v12" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD(2, { a12 }) // label_17, while jj_2_40 && a12 scans 1 token - "x12" - )* - "end" - | - "x12" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()*) - LOOKAHEAD(2, { !a12 }) // label_18, while jj_2_41 && a12 scans 2 tokens - "v12" "x0" - )* - "end" - | - "v13" - ( - // no warning but indeed CONSIDERED - // makes "x13" mandatory for each evaluation of a13 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD(0, "x13", { a13 }) // label_19, while a13 consumes 1 token - "x13" - )* - "end" - | - "x13" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v13" mandatory for each evaluation of !a13 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()*) - LOOKAHEAD(0, "v13", { !a13 }) // label_20, while !a13 consumes 1 token - "v13" - )* - "end" - | - "v14" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()*) - LOOKAHEAD(1, "x14", { a14 }) // label_21, while jj_2_42 && a14 scans 1 token - "x14" - )* - "end" - | - "x14" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()*) - LOOKAHEAD(1, "v14", { !a14 }) // label_22, while jj_2_43 && !a14 scans 1 token - "v14" - )* - "end" - | - "v15" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()*) - LOOKAHEAD(2, "x15", { a15 }) // label_23, while jj_2_44 && !a15 scans 1 token - "x15" - )* - "end" - | - "x15" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()*) - LOOKAHEAD(2, "v15" "x0", { !a15 }) // label_24, while jj_2_45 && !a15 scans 2 tokens - "v15" "x0" - )* - "end" - ) - { System.out.println("End E"); } -} - -// same as E() but with optional construct ()+ instead of ()* -// the generated method structure is the same, -// with the Xnn token being consumed at the beginning of the while loop instead of at the end -void F() : {} -{ - { prod_name = "F"; } - ( - "v0" - ("x0")+ // label_25 while, switch X0 default - "end" -// | -// "v1" -// ( -// // no warning but indeed CONSIDERED -// // endless loop on consume X1, unreachable code, compiler error -// // so of NO USE -// LOOKAHEAD(0) // label_26 while, no switch endless loop X1 -// "x1" -// )+ -// "end" - | - "v2" - ( - // no warning but indeed IGNORED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(1) // label_26 while, switch X2 default scans 1 token - "x2" - )+ - "end" - | - "v3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // label_27, while jj_2_46 scans 1 token - "x3" - )+ - "end" - | - "x3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // label_28, while jj_2_47 scans 2 tokens - "v3" "x0" - )+ - "end" - | - "v4" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD("x4") // label_29, while jj_2_48 scans 1 token - "x4" - )+ - "end" - | - "v5" - ( - // no warning but indeed CONSIDERED - // makes "x5" mandatory for each evaluation of a5 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD({ a5 }) // label_30, while a5 consumes 1 token - "x5" - )+ - "end" - | - "x5" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD({ !a5 }) // label_31, while !a5 consumes 1 token - "v5" - )+ - "end" -// | -// "v6" -// ( -// // no warning but indeed CONSIDERED -// // endless loop on consume X6, unreachable code, compiler error -// // so of NO USE -// LOOKAHEAD(0, "x6") // label_32 while, no switch endless loop X6 -// "x6" -// )+ -// "end" - | - "v7" - ( - // no warning but indeed IGNORED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(1, "x7") // label_32 while, switch X7 default scans 1 token - "x7" - )+ - "end" - | - "v8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "x8") // label_33, while jj_2_49 scans 1 token - "x8" - )+ - "end" - | - "x8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "v8") // label_34, while jj_2_50 scans 1 token (not 2 tokens) - "v8" "x0" - )+ - "end" - | - "v9" - ( - // no warning but indeed CONSIDERED - // scans for "x9" then evaluates a9 - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD("x9", { a9 }) // label_35, while jj_2_51 && a9 scans 1 token - "x9" - )+ - "end" - | - "x9" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // scans for "v9" then evaluates !a9 - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD("v9", { !a9 }) // label_36, while jj_2_52 && !a9 scans 1 token - "v9" - )+ - "end" - | - "v10" - ( - // no warning but indeed CONSIDERED - // makes "x10" mandatory for each evaluation of a10 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD(0, { a10 }) // label_37, while a10 consumes 1 token - "x10" - )+ - "end" - | - "x10" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v10" mandatory for each evaluation of !a10 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD(0, { !a10 }) // label_38, while !a10 consumes 1 token - "v10" - )+ - "end" - | - "v11" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD(1, { a11 }) // label_39, while jj_2_53 && a11 scans 1 token - "x11" - )+ - "end" - | - "x11" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD(1, { !a11 }) // label_40, while jj_2_54 && !a11 scans 1 token - "v11" - )+ - "end" - | - "v12" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD(2, { a12 }) // label_41, while jj_2_55 && a12 scans 1 token - "x12" - )+ - "end" - | - "x12" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control on the occurrences of ()+) - LOOKAHEAD(2, { !a12 }) // label_42, while jj_2_56 && !a12 scans 2 tokens - "v12" "x0" - )+ - "end" - | - "v13" - ( - // no warning but indeed CONSIDERED - // makes "x13" mandatory for each evaluation of a13 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD(0, "x13", { a13 }) // label_43, while a13 consumes 1 token - "x13" - )+ - "end" - | - "x13" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v13" mandatory for each evaluation of !a13 to true - // so of some MEANINGFUL USE (dynamic control of the number of occurrences of ()+) - LOOKAHEAD(0, "v13", { !a13 }) // label_44, while !a13 consumes 1 token - "v13" - )+ - "end" - | - "v14" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()+) - LOOKAHEAD(1, "x14", { a14 }) // label_45, while jj_2_57 && a14 scans 1 token - "x14" - )+ - "end" - | - "x14" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()+) - LOOKAHEAD(1, "v14", { !a14 }) // label_46, while jj_2_58 && !a14 scans 1 token - "v14" - )+ - "end" - | - "v15" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()+) - LOOKAHEAD(2, "x15", { a15 }) // label_47, while jj_2_59 && a15 scans 1 token - "x15" - )+ - "end" - | - "x15" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()+) - LOOKAHEAD(2, "v15" "x0", { !a15 }) // label_48, while jj_2_60 && !a15 scans 2 tokens - "v15" "x0" - )+ - "end" - ) - { System.out.println("End F"); } -} - -// same as E() but with optional construct ()? instead of ()* -// -void G() : {} -{ - { prod_name = "G"; } - ( - "v0" - ("x0")? // switch X0 default scans 1 token - "end" - | - "v1" - ( - // no warning but indeed CONSIDERED - // makes "x1" mandatory (i.e. it removes its optional aspect) - // so OF NO SENSIBLE USE - LOOKAHEAD(0) // no switch - "x1" - )? - "end" - | - "v2" - ( - // no warning but indeed IGNORED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(1) // switch X2 default scans 1 token - "x2" - )? - "end" - | - "v3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // jj_2_61 scans 1 token - "x3" - )? - "end" - | - "x3" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD(2) // jj_2_62 scans 2 tokens - "v3" "x0" - )? - "end" - | - "v4" - ( - // no warning but indeed CONSIDERED - // so OF NO MEANINGFUL USE although it does not harm - LOOKAHEAD("x4") // jj_2_63 scans 1 token - "x4" - )? - "end" - | - "v5" - ( - // no warning but indeed CONSIDERED - // makes "x5" mandatory for single evaluation of a5 to true - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD({ a5 }) // a5 consumes 1 token - "x5" - )? - "end" - | - "x5" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD({ !a5 }) // !a5 consumes 1 token - "v5" - )? - "end" - | - "v6" - ( - // no warning but indeed CONSIDERED - // makes "x6" mandatory (i.e. it removes its optional aspect) - // so OF NO SENSIBLE USE - LOOKAHEAD(0, "x6") // no switch - "x6" - )? - "end" - | - "v7" - ( - // no warning but indeed IGNORED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(1, "x7") // switch X7 default scans 1 token - "x7" - )? - "end" - | - "v8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "x8") // jj_2_64 scans 1 token - "x8" - )? - "end" - | - "x8" - ( - // no warning but indeed CONSIDERED - // so OF NO REAL USE although it does not harm - LOOKAHEAD(2, "v8") // jj_2_65 scans 1 token (not 2 tokens) - "v8" "x0" - )? - "end" - | - "v9" - ( - // no warning but indeed CONSIDERED - // scans for "x9" then evaluates a9 - // so OF REAL USE (additional semantic validation - like dynamic control on one occurrence of ()?) - LOOKAHEAD("x9", { a9 }) // jj_2_66 && a9 scans 1 token - "x9" - )? - "end" - | - "x9" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // scans for "v9" then evaluates !a9 - // so OF REAL USE (additional semantic validation - like dynamic control on one occurrence of ()?) - LOOKAHEAD("v9", { !a9 }) // jj_2_67 && !a9 scans 1 token - "v9" - )? - "end" - | - "v10" - ( - // no warning but indeed CONSIDERED - // makes "x10" mandatory for one evaluation of a10 to true - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD(0, { a10 }) // a10 consumes 1 token - "x10" - )? - "end" - | - "x10" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v10" mandatory for one evaluation of !a10 to true - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD(0, { !a10 }) // !a10 consumes 1 token - "v10" - )? - "end" - | - "v11" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(1, { a11 }) // jj_2_68 && a11 scans 1 token - "x11" - )? - "end" - | - "x11" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(1, { !a11 }) // jj_2_69 && !a11 scans 1 token - "v11" - )? - "end" - | - "v12" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(2, { a12 }) // jj_2_70 && a12 scans 1 token - "x12" - )? - "end" - | - "x12" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(2, { !a12 }) // jj_2_71 && !a12 scans 2 tokens - "v12" "x0" - )? - "end" - | - "v13" - ( - // no warning but indeed CONSIDERED - // makes "x13" mandatory for one evaluation of a13 to true - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD(0, "x13", { a13 }) // a13 consumes 1 token - "x13" - )? - "end" - | - "x13" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // makes "v13" mandatory for one evaluation of !a13 to true - // so of some MEANINGFUL USE (dynamic control of one occurrence of ()?) - LOOKAHEAD(0, "v13", { !a13 }) // !a13 consumes 1 token - "v13" - )? - "end" - | - "v14" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(1, "x14", { a14 }) // jj_2_73 && a14 scans 1 token - "x14" - )? - "end" - | - "x14" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of one occurrence of ()?) - LOOKAHEAD(1, "v14", { !a14 }) // jj_2_74 && !a14 scans 1 token - "v14" - )? - "end" - | - "v15" - ( - // no warning but indeed CONSIDERED - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()?) - LOOKAHEAD(2, "x15", { a15 }) // jj_2_75 && a15 scans 1 token - "x15" - )? - "end" - | - "x15" - ( - // no warning but indeed CONSIDERED - // (opposite of previous) - // so OF REAL USE (additional semantic validation - like dynamic control of the # of occurrences of ()?) - LOOKAHEAD(2, "v15" "x0", { !a15 }) // jj_2_76 && !a15 scans 2 tokens - "v15" "x0" - )? - "end" - ) - { System.out.println("End G"); } -} - diff --git a/examples/Lookahead/src/main/javacc/ReadingLookahedDebugTrace_Example8.jj b/examples/Lookahead/src/main/javacc/ReadingLookahedDebugTrace_Example8.jj deleted file mode 100644 index 8fd0a4a..0000000 --- a/examples/Lookahead/src/main/javacc/ReadingLookahedDebugTrace_Example8.jj +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Small grammar to produce a lookahead debug trace. - */ -options -{ - static = false; - FORCE_LA_CHECK = true; // (JavaCC - default false) - DEBUG_PARSER = true; // (JavaCC - default false) - DEBUG_LOOKAHEAD = true; // (JavaCC - default false) - OUTPUT_DIRECTORY = "rldt8"; -} - -PARSER_BEGIN(ReadingLookaheadDebugTrace_Example8) -package rldt8; - -import java.io.StringReader; - -public class ReadingLookaheadDebugTrace_Example8 { - - public static void main(final String args[]) throws ParseException { - ReadingLookaheadDebugTrace_Example8 parser = null; - for (int i = 0; i < input.length; i++) - { - System.out.println("input " + i+ " : " + input[i]); - parser = new ReadingLookaheadDebugTrace_Example8(new StringReader(input[i])); - try { parser.basic_expr(); } - // catch PE & TMR for running all the test suite - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - finally { System.out.println(); } - } - } - - void report(final String aStr) { System.out.println("Main swallowing a " + aStr); } - - static String input [] = new String [] { // - "new cd", // -> choice 3 - "( EXPR )", // -> choice 2 - "e.f", // -> choice 4 - "ab ( EXPR )", // -> choices 1 / 1 - "ba ( )", // -> choices 1 / 2 - "new .cd", // -> ParseException - }; - -} - -PARSER_END(ReadingLookaheadDebugTrace_Example8) - -SKIP : { " " } - -TOKEN : { < LP: "(" > | < RP: ")" > | < DOT: "." > | < NEW: "new" > | < EXPR: "EXPR" > } - -TOKEN [IGNORE_CASE] : { } - -void basic_expr() : {} -{ - LOOKAHEAD(2) // choice 1 - args() -| // choice 2 - "(" expr() ")" -| // choice 3 - "new" -| // choice 4 - "." -} - -void expr() : {} { "EXPR" } - -void args() : {} -{ - LOOKAHEAD(2) - "(" expr() ")" -| - "(" ")" -} diff --git a/examples/Lookahead/src/main/javacc/RewrittenGrammar_Example14.jj b/examples/Lookahead/src/main/javacc/RewrittenGrammar_Example14.jj deleted file mode 100644 index 6aa0ab8..0000000 --- a/examples/Lookahead/src/main/javacc/RewrittenGrammar_Example14.jj +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Small grammar to show a rewriting technique. - */ -options -{ - static = false; - FORCE_LA_CHECK = true; // (JavaCC - default false) - DEBUG_LOOKAHEAD = true; // (JavaCC - default false) - OUTPUT_DIRECTORY = "rwg14"; -} - -PARSER_BEGIN(RewrittenGrammar_Example14) -package rwg14; - -import java.io.StringReader; - -public class RewrittenGrammar_Example14 { - - public static void main(final String args[]) throws ParseException { - RewrittenGrammar_Example14 parser = null; - for (int i = 0; i < input.length; i++) - { - System.out.println("pfx() on input " + i+ " : " + input[i]); - parser = new RewrittenGrammar_Example14(new StringReader(input[i])); - try { parser.pfx(); } - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - finally { System.out.println(); } - } - for (int i = 0; i < input.length; i++) - { - System.out.println("pfx_rw4() on input " + i+ " : " + input[i]); - parser = new RewrittenGrammar_Example14(new StringReader(input[i])); - try { parser.pfx_rw4(); } - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - finally { System.out.println(); } - } - for (int i = 0; i < input.length; i++) - { - System.out.println("pfx_synla() on input " + i+ " : " + input[i]); - parser = new RewrittenGrammar_Example14(new StringReader(input[i])); - try { parser.pfx_synla(); } - catch (ParseException pe) { parser.report("ParseException: " + pe.getMessage()); } - catch (TokenMgrError tme) { parser.report("TokenMgrError: " + tme.getMessage()); } - finally { System.out.println(); } - } - } - - String prod = null; - - void report(final String aStr) { System.out.println(prod + " swallowed " + aStr); } - - static String input [] = new String [] { // - "x x a b d", // - "x x a c d", // - "x x a e", // - "x x a b e", // - "x b e", // - }; - - boolean b = false, c = false, d = false, e = false, x = false; - -} -PARSER_END(RewrittenGrammar_Example14) - -SKIP : { " " } - -TOKEN : { < A: "a" > | < B: "b" > | < C: "c" > | < D: "d" > | < E: "e" > | < X: "x" > } - -/** to show how difficult it is for javacc to find the real common prefix */ -void pfx() : -{} -{ - { prod = "pfx"; } - ( - // javacc says common prefix is "x" "x" therefore a lookahead of 3 or more, - // but it should be "x" "x" "a" "b"+ and a lookahead of 5+ - LOOKAHEAD(3) - "x" // 1- - "x" "a" - ( "b" | "c" )+ // 2- - "d" - | - "x" // 1- - ( "x" "a" | "b" )+ // 3- - "e" - ) -} - -/** pfx rewritten by factorizing / distributing */ -void pfx_rw0() : -{} -{ - { prod = "pfx_rw0"; } - ( - // 1- factorized "x" between choices 1 & 2 - "x" - ( - // javacc says common prefix is "x" "a" therefore a lookahead of 3 or more, - // so we'll try to factorize "x" "a" - LOOKAHEAD(3) - - // 2- distributed one choice of "b" and "c" from ( "b" | "c" )+ - "x" "a" - ( - "b" ( "b" | "c" )* "d" - | "c" ( "b" | "c" )* "d" - ) // 4- - | - // 3- distributed one choice of "x" "a" and "b" from ( "x" "a" | "b" )+ - "x" "a" ( "x" "a" | "b" )* "e" // 4- - | "b" ( "x" "a" | "b" )* "e" - ) - ) -} - -/** pfx_rw0 rewritten by factorizing */ -void pfx_rw1() : -{} -{ - { prod = "pfx_rw1"; } - ( - "x" - ( - // 4- factorized "x" "a" between choices 1 & 2 - "x" "a" - ( - // javacc says common prefix is "b" "b" therefore a lookahead of 3 or more, - // so we'll try to factorize "b" - "b" ( "b" | "c" )* "d" - | "c" ( "b" | "c" )* "d" - | ( "x" "a" | "b" )* "e" // 5- - ) - | "b" ( "x" "a" | "b" )* "e" - ) - ) -} - -/** pfx_rw1 rewritten by distributing */ -void pfx_rw2() : -{} -{ - { prod = "pfx_rw2"; } - ( - "x" - ( - "x" "a" - ( - // javacc says common prefix is "b" "b" therefore a lookahead of 3 or more, - // so we'll try to factorize "b" - LOOKAHEAD(3) - - "b" ( "b" | "c" )* "d" // 6- - | "c" ( "b" | "c" )* "d" - | - // 5- distributed "b" and "x" "a" from ( "x" "a" | "b" )* - "b" ( "x" "a" | "b" )* "e" // 6- - | "x" "a" ( "x" "a" | "b" )* "e" - | "e" - ) - | "b" ( "x" "a" | "b" )* "e" - ) - ) -} - -/** pfx_rw2 rewritten by factorizing */ -void pfx_rw3() : -{} -{ - { prod = "pfx_rw3"; } - ( - "x" - ( - "x" "a" - ( - // 6- factorized "b" between choices 1 & 3 - "b" - // javacc says again common prefix is "b" "b" therefore a lookahead of 3 or more, - // so we'll try to factorize "b", but we have to take another technique - - // on next step 7- we'll combine the 2 next choices in ("b" | "c" | "x" "a")* ("d" | "e") - // by combining the 2 first ()* (which both include the offending "b") between them - // and the 2 last "" in a choice, and adding actions to exclude invalid combinations - ( ( "b" | "c" )* "d" - | ( "x" "a" | "b" )* "e" - ) - | "c" ( "b" | "c" )* "d" - | "x" "a" ( "x" "a" | "b" )* "e" - | "e" - ) - | "b" ( "x" "a" | "b" )* "e" - ) - ) -} - -/** pfx_rw3 rewritten by combining / adding actions & semantic LOOKAHEADs */ -void pfx_rw4() : -{} -{ - { prod = "pfx_rw4"; } - ( - "x" - ( - "x" "a" - ( - "b" - // 7- start - { c = x = false; } // initialise flags - ( - ( "b" - | "c" { c = true; } // set flag - | "x" "a" { x = true;} // set flag - )* - ( - LOOKAHEAD( 1, { !x } ) // 1 is needed! - exclude unwanted combination with flag - { String sd = "LOOKAHEAD( 1, { !x } ) before \"d\""; } // just as a tag in the generated code - "d" - | LOOKAHEAD( 1, { !c } ) // 1 is needed! - exclude unwanted combination with flag - { String se = "LOOKAHEAD( 1, { !c } ) before \"e\""; } // just as a tag in the generated code - "e" - ) - ) - // 7- end - | "c" ( "b" | "c" )* "d" - | "x" "a" ( "x" "a" | "b" )+ "e" - | "e" - ) - | "b" ( "x" "a" | "b" )* "e" - ) - ) -} - -/** pfx with syntactic LOOKAHEAD */ -void pfx_synla() : -{} -{ - { prod = "pfx_synla"; } - ( - // full syntactic lookahead - LOOKAHEAD("x" "x" "a" ( "b" | "c" )+ "d") - { String sy = "LOOKAHEAD(\"x\" \"x\" \"a\" ( \"b\" | \"c\" )+ \"d\")"; } // just as a tag in the generated code - "x" - "x" - "a" - ( "b" | "c" )+ - "d" - | - "x" - ( "x" "a" | "b" )+ - "e" - ) -} - diff --git a/examples/Lookahead/src/main/javacc/VersionAwareGrammar_Example13.jj b/examples/Lookahead/src/main/javacc/VersionAwareGrammar_Example13.jj deleted file mode 100644 index 0f01d0d..0000000 --- a/examples/Lookahead/src/main/javacc/VersionAwareGrammar_Example13.jj +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the names of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * Small grammar to show use of semantic lookaheads at choice and non choice points for managing grammar versions. - */ -options -{ - static = false; - FORCE_LA_CHECK = true; // (JavaCC - default false) - ERROR_REPORTING = true; - OUTPUT_DIRECTORY = "vag13"; -} - -PARSER_BEGIN(VersionAwareGrammar_Example13) -package vag13; - -import java.io.StringReader; - -/** - * This example uses a simple syntax for the Java try statement in version 1, and a more elaborated - * one in version 2: - *
    - *
  • Try1() and Block1() define version 1 only syntax
  • - *
  • Try2() and Block2() define version 2 syntax (which is a superset of version 1 - * syntax)
  • - *
  • Try1or2() and Block1or2() define version 1 and version 2 syntaxes that the user - * can choose between (therefore the or) through an expression isCV2orMore() that is - * used in some semantic lookaheads at a choice or non choice point, which act like a grammar condition
  • - *
- * These syntaxes tag each feature (sub part of the syntax) with a version number {@link #feature_version} - * telling the version the grammar syntax it is part of. - *

- * In the input data, the user sets: - *

    - *
  1. through the first token:
  2. - *
      - *
    • the productions he wants the parser to use:
    • - *
        - *
      • 1 -> Xyz1()
      • - *
      • 2 -> Xyz2()
      • - *
      • 1in2 -> Xyz2()
      • - *
      • 1or2 -> Xyz1or2()
      • - *
      - *
    • and the version level {@link #checked_version} he expects the (next) statement to be checked against:
    • - *
        - *
      • 1 -> 1
      • - *
      • 2 -> 2
      • - *
      • 1in2 -> 1
      • - *
      • 1or2 -> 2
      • - *
      - *
    - *
  3. and the statement (which can comply or not with the given syntax version).
  4. - *
- *

- * The parsing outcome can be: - *
    - *
  • no problem: a single End <production_name>() message
  • - *
  • one or more warnings: <production_name>() warning encountered a feature of version 2 greater - * than the given checked version 1 message(s), followed by the previous end message: - * this happens when the user specified a 1in2 input with a statement with version 2 features
  • - *
  • a ParseException or a TokenMgrError: <production_name>() swallowed <ParseException or - * TokenMgrError> while checking a grammar in version <1 or 2> message: when the statement has - * invalid or unknown tokens or when it has version 2 features against a required version 1 syntax
  • - *
- *

- * The Xyz1or2() productions use semantic lookaheads (at choice and non choice points) which make - * the parser behave exactly like in Xyz1() or Xyz2() productions (depending on the - * expression value) with respect their respective strict syntaxes: it produces a ParseException if the user - * gives a statement with version 2 features against a version 1 level syntax.
- * The Xyz2() productions use just parser actions that implement a tolerant checked level - * parsing: it produces a warning and not a ParseException if the user gives a statement with version 2 - * features against a version 1 level syntax. - *

- */ -public class VersionAwareGrammar_Example13 -{ - /** test data, see Input() for first tokens meanings */ - static String input [] = new String [] // - { // v1 - "1 . try { ; } .", // - "2 . try { ; } .", // - "1in2 . try { ; } .", // - "1or2 . try { ; } .", // - "1 . try { ; } catch ( mod type var ) .", // - "2 . try { ; } catch ( mod type var ) .", // - "1in2 . try { ; } catch ( mod type var ) .", // - "1or2 . try { ; } catch ( mod type var ) .", // - "1 . try { ; } finally { ; } .", // - "2 . try { ; } finally { ; } .", // - "1in2 . try { ; } finally { ; } .", // - "1or2 . try { ; } finally { ; } .", // - "1 . try { ; } catch ( mod type var ) finally { ; } .", // - "2 . try { ; } catch ( mod type var ) finally { ; } .", // - "1in2 . try { ; } catch ( mod type var ) finally { ; } .", // - "1or2 . try { ; } catch ( mod type var ) finally { ; } .", // - // v2 : v1 + ( res ) - "1 . try ( res ) { ; } .", // - "2 . try ( res ) { ; } .", // - "1in2 . try ( res ) { ; } .", // - "1or2 . try ( res ) { ; } .", // - "1 . try ( res ) { ; } catch ( mod type var ) .", // - "2 . try ( res ) { ; } catch ( mod type var ) .", // - "1in2 . try ( res ) { ; } catch ( mod type var ) .", // - "1or2 . try ( res ) { ; } catch ( mod type var ) .", // - "1 . try ( res ) { ; } finally { ; } .", // - "2 . try ( res ) { ; } finally { ; } .", // - "1in2 . try ( res ) { ; } finally { ; } .", // - "1or2 . try ( res ) { ; } finally { ; } .", // - "1 . try ( res ) { ; } catch ( mod type var ) finally { ; } .", // - "2 . try ( res ) { ; } catch ( mod type var ) finally { ; } .", // - "1in2 . try ( res ) { ; } catch ( mod type var ) finally { ; } .", // - "1or2 . try ( res ) { ; } catch ( mod type var ) finally { ; } .", // - // v2 : v1 + | ann - "1 . try { ; } catch ( mod type | ann var ) .", // - "2 . try { ; } catch ( mod type | ann var ) .", // - "1in2 . try { ; } catch ( mod type | ann var ) .", // - "1or2 . try { ; } catch ( mod type | ann var ) .", // - "1 . try { ; } catch ( mod type | ann var ) finally { ; } .", // - "2 . try { ; } catch ( mod type | ann var ) finally { ; } .", // - "1in2 . try { ; } catch ( mod type | ann var ) finally { ; } .", // - "1or2 . try { ; } catch ( mod type | ann var ) finally { ; } .", // - // v2 : v1 + @a; - "1 . try { @a; } .", // - "2 . try { @a; } .", // - "1in2 . try { @a; } .", // - "1or2 . try { @a; } .", // - "1 . try { @a; } catch ( mod type var ) .", // - "2 . try { @a; } catch ( mod type var ) .", // - "1in2 . try { @a; } catch ( mod type var ) .", // - "1or2 . try { @a; } catch ( mod type var ) .", // - "1 . try { @a; } finally { @a; } .", // - "2 . try { @a; } finally { @a; } .", // - "1in2 . try { @a; } finally { @a; } .", // - "1or2 . try { @a; } finally { @a; } .", // - "1 . try { @a; } catch ( mod type var ) finally { @a; } .", // - "2 . try { @a; } catch ( mod type var ) finally { @a; } .", // - "1in2 . try { @a; } catch ( mod type var ) finally { @a; } .", // - "1or2 . try { @a; } catch ( mod type var ) finally { @a; } .", // - // v2 : v1 + @b; - "1 . try { @b; } .", // - "2 . try { @b; } .", // - "1in2 . try { @b; } .", // - "1or2 . try { @b; } .", // - "1 . try { @b; } catch ( mod type var ) .", // - "2 . try { @b; } catch ( mod type var ) .", // - "1in2 . try { @b; } catch ( mod type var ) .", // - "1or2 . try { @b; } catch ( mod type var ) .", // - "1 . try { @b; } finally { @b; } .", // - "2 . try { @b; } finally { @b; } .", // - "1in2 . try { @b; } finally { @b; } .", // - "1or2 . try { @b; } finally { @b; } .", // - "1 . try { @b; } catch ( mod type var ) finally { @b; } .", // - "2 . try { @b; } catch ( mod type var ) finally { @b; } .", // - "1in2 . try { @b; } catch ( mod type var ) finally { @b; } .", // - "1or2 . try { @b; } catch ( mod type var ) finally { @b; } .", // - // v2 : v1 + @c; (gives TokenMgrError) or @d; (gives ParseException) - "1 . try { @c; } .", // - "2 . try { @c; } .", // - "1in2 . try { @c; } .", // - "1or2 . try { @c; } .", // - "1 . try { @d; } catch ( mod type var ) .", // - "2 . try { @d; } catch ( mod type var ) .", // - "1in2 . try { @d; } catch ( mod type var ) .", // - "1or2 . try { @d; } catch ( mod type var ) .", // - "1 . try { @d; } finally { @c; } .", // - "2 . try { @d; } finally { @c; } .", // - "1in2 . try { @d; } finally { @c; } .", // - "1or2 . try { @d; } finally { @c; } .", // - "1 . try { @c; } catch ( mod type var ) finally { @d; } .", // - "2 . try { @c; } catch ( mod type var ) finally { @d; } .", // - "1in2 . try { @c; } catch ( mod type var ) finally { @d; } .", // - "1or2 . try { @c; } catch ( mod type var ) finally { @d; } .", // - }; - - /** standard main running on internal input */ - public static void main(final String args []) throws ParseException - { - VersionAwareGrammar_Example13 parser = null; - for (int i = 0; i < input.length; i++) - { - System.out.println("input " + i+ " : " + input[i]); - parser = new VersionAwareGrammar_Example13(new StringReader(input[i])); - try { parser.Input(); } - // catch PE & TMR for running all the test suite - catch (ParseException pe) { parser.report("ParseException"); } - catch (TokenMgrError tme) { parser.report("TokenMgrError"); } - } - } - - /** report problem with version info */ - void report(final String aStr) - { - System.out.println(prod_name + " swallowed " + aStr + " while checking a grammar in version " + checked_version); - } - - /** the current production name, for reporting */ - String prod_name = null; - - /** the grammar version to check the input against, set through the input data first token for convenience */ - int checked_version = 0; - /* methods used in semantic lookaheads */ - boolean isCV1() { return checked_version == 1; } - boolean isCV2() { return checked_version == 2; } - boolean isCV1orMore() { return checked_version >= 1; } - boolean isCV2orMore() { return checked_version >= 2; } - - /** the current feature version, set during parsing, telling in which grammar syntax version the current feature is */ - int feature_version = 0; - /** more than a setter; used in parser actions */ - void setFeature_version(final int aVer) - { - feature_version = aVer; - if (feature_version > checked_version) - System.out.println(prod_name + " warning encountered a feature of version " + feature_version + - " greater than the given checked version " + checked_version); - } - -} -PARSER_END(VersionAwareGrammar_Example13) - -SKIP : -{ - " " -| "\r" -| "\t" -| "\n" -} - -TOKEN : -{ - < DOT : "." > -| < LBRA : "{" > -| < RBRA : "}" > -| < LPAR : "(" > -| < RPAR : ")" > -| < OR : "|" > -| < SEMICOLON : ";" > - -| < ANN : "ann" > -| < CATCH : "catch" > -| < FINALLY : "finally" > -| < MOD : "mod" > -| < RES : "res" > -| < TRY : "try" > -| < TYPE : "type" > -| < VAR : "var" > -| < ATASC : "@a;" > -| < ATBSC : "@b;" > -//| < ATCSC : "@c;" > // not used in the grammar, used in the input data to produce a lexical error -| < ATDSC : "@d;" > // defined but not used in the grammar, used in the input data to produce a parse exception - -| < ONE : "1" > -| < TWO : "2" > -| < ONEORTWO : "1or2" > -} - -/* switch to different syntaxes based on input data: . try <...> . */ -void Input() : -{} -{ - // strict grammar version 1 syntax (Try1), checking input with only version 1 features - "1" { checked_version = 1; } "." Try1() < EOF > -| - // tolerant grammar version 2 syntax (Try2), checking input with both versions 1 & 2 features - "2" { checked_version = 2; } "." Try2() < EOF > -| - // tolerant grammar version 2 syntax (Try2), warning on input with version 2 features - // (intended to check that the grammar complies with version 1 syntax) - "1in2" { checked_version = 1; } "." Try2() < EOF > -| - // strict grammar versions 1 or 2 syntaxes (Try1or2), checking input with both versions 1 & 2 features - "1or2" { checked_version = 2; } "." Try1or2() < EOF > -} - -/* strictly accepts grammar syntax in version 1 */ -void Try1() : -{} -{ - { prod_name = "Try1"; } - { setFeature_version(1); } - "try" - Block1() - ( - "catch" "(" "mod" "type" - "var" ")" - )* - [ - "finally" Block1() - ] - "." - { System.out.println("End Try1"); } -} - -/* tolerantly accepts grammar syntax in version 1 or 2, - a version 2 feature in a version 1 grammar will cause a warning, not a ParseException */ -void Try2() : -{} -{ - { prod_name = "Try2"; } - { setFeature_version(1); } - "try" - [ - { setFeature_version(2); } - "(" "res" ")" - { setFeature_version(1); } - ] - Block2() - ( - "catch" "(" ("mod")* "type" - ( - { setFeature_version(2); } - "|" "ann" - { setFeature_version(1); } - )* - "var" ")" - )* - [ - "finally" Block2() - ] - "." - { System.out.println("End Try2"); } -} - -/* strictly accepts grammar syntax in version 1 (isCV2orMore() == false) or 2 (isCV2orMore() == true), - depending on an external flag (isCV2orMore()): - a version 2 feature in a version 1 grammar will cause a ParseException */ -void Try1or2() : -{} -{ - { prod_name = "Try1or2"; } - { setFeature_version(1); } - "try" -// try -// { - [ - // non choice, at bnf level 1, missing warning "sem la considered" - // not putting the expansion "(" would transform the [] optional sequence in a non optional sequence - // putting the expansion "(" scans for it and so keeps the sequence optional - // sem la false is handled in the empty else - // no ParseException thrown, no need to wrap it in a try catch and swallow the ParseException - LOOKAHEAD("(", { isCV2orMore() }) - { setFeature_version(2); } - "(" "res" ")" - { setFeature_version(1); } - ] -// } -// catch (ParseException pe) { /* raised when v2orMore() = false; swallow it */ } - Block1or2() - ( - "catch" "(" ("mod")* "type" - ( - // non choice, at bnf level 2 (2 levels of parenthesis), missing warning "sem la considered" - // not putting the expansion "|" would transform the ()* optional sequence in a non optional sequence - // putting the expansion "|" scans for it and so keeps the ()* optional sequence - // sem la false is handled in the else breaking the while loop - // no ParseException thrown, no need to wrap it in a try catch and swallow the ParseException - LOOKAHEAD("|", { isCV2orMore() }) - { setFeature_version(2); } - "|" "ann" - { setFeature_version(1); } - )* - "var" ")" - )* - [ - "finally" Block1or2() - ] - "." - { System.out.println("End Try1or2"); } -} - -void Block1() : -{} -{ - { prod_name = "Block1"; } - { setFeature_version(1); } - "{" ";" "}" -} - -/* tolerantly accepts grammar syntax in version 1 (isCV2orMore() == false) or 2 (isCV2orMore() == true), - depending on an external flag (isCV2orMore()): - a version 2 feature in a version 1 grammar will cause a warning, not a ParseException */ -void Block2() : -{} -{ - { prod_name = "Block2"; } - { setFeature_version(1); } - "{" - ( - ";" // choice 1 - | - { setFeature_version(2); } - "@a;" // choice 2 - { setFeature_version(1); } - | - { setFeature_version(2); } - "@b;" // choice 3 - { setFeature_version(1); } - ) - "}" -} - -/* strictly accepts grammar syntax in version 1 (isCV2orMore() == false) or 2 (isCV2orMore() == true), - depending on an external flag (isCV2orMore()): - a version 2 feature in a version 1 grammar will cause a ParseException */ -void Block1or2() : -{} -{ - { prod_name = "Block1or2"; } - { setFeature_version(1); } - "{" - ( - ";" // non conflicting choice 1 - | - // default la of 1 enough (no prefix for ";", "@a;" and "@b;"), - // no warning needed for the lookahead at a choice location - // in the LOOKAHEAD, the amount 1 and the expansion "@a;" forms are equivalent - // not putting the 1 / "@a;" would transform this second choice in a non choice (i.e. mandatory) - // putting the 1 / "@a;" scans for a token and so keeps this second choice as a choice; if scan ok then - // sem la true consumes the token; sem la false goes to next choice 3 - // no ParseException thrown (not the last choice) -// LOOKAHEAD(1, { isCV2orMore() }) - LOOKAHEAD("@a;", { isCV2orMore() }) - { setFeature_version(2); } - "@a;" // non conflicting choice 2 - { setFeature_version(1); } - | - // default la of 1 enough (no prefix for ";", "@a;" and "@b;"), - // no warning needed for the lookahead at a choice location - // not putting amount 1 or expansion "@b;" transforms this third choice in a non choice (i.e. mandatory) - // (but here this is fine as it is the last choice of the expansion_choices) - // sem la true consumes the token; sem la false throws a ParseException - // a ParseException is thrown (if no match an no more choices) and must no be catched, - // so no need to wrap it in a try catch here - LOOKAHEAD({ isCV2orMore() }) - { setFeature_version(2); } - "@b;" // non conflicting choice 3 - { setFeature_version(1); } - ) - "}" -} - diff --git a/examples/MailProcessing/README b/examples/MailProcessing/README deleted file mode 100644 index 4697d79..0000000 --- a/examples/MailProcessing/README +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This example illustrates the use of lexical states. - -In this directory are two grammar files Digest.jj and Faq.jj. These -generate parsers that process RMAIL files that are created by the GNU -emacs editor. A sample RMAIL file called sampleMailFile is also -included. - -Digest.jj and Faq.jj are both identical in their grammar and lexical -specifications. They only differ in their actions. Digest.jj takes a -mail file as standard input and produces a digest version of the -messages to standard output. This is what we used (before we moved -over to an automatic mailing list software) to produce the weekly mail -digest of the JavaCC mailing list. Faq.jj takes a mail file as -standard input and produces a mail FAQ in HTML format. It produces a -file "index.html" that contains all the mail headers and links to -other HTML files called "1.html", "2.html", etc. that contain the 1st, -2nd, etc. messages. The parser generated from Faq.jj accepts an -optional integer argument that specifies the message number from where -to begin processing. - -Type the following: - - javacc Digest.jj - javacc Faq.jj - javac *.java - java Digest < sampleMailFile > digestFile - java Faq < sampleMailFile - -And take a look at the output files created. - - -MORE DETAILS ON HOW THE GRAMMARS WORK: - -The grammar specification is rather trivial. It simply says that a -MailFile is is a sequence of MailMessage's followed by an end of file. -And that a MailMessage is a list of one or more 's, 's, -and 's followed by a list of zero or more 's followed by -an . - -Essentially, there are five lexical tokens: - -, : Are the strings of the Subject, From, and -Date fields of the message. - - : Is a single line of the message body. - - : is the end of message token. - -The lexical specification starts with a set of reusable private -regular expressions EOL, TWOEOLS, and NOT_EOL. These are defined to -be portable across different platforms where the end of line -characters are different. - -In the lexical state, the token manager simply eats up -characters until it sees the beginning of a message which is marked by -< "*** EOOH ***" >. See the sample mail file for details. -At this point, it switches to state . - -In the state , two consecutive end of line's indicate the -end of the mail header and therefore the token manager goes to the - lexical state. Also, if it sees "Subject: ", it goes to -the lexical state, and similarly for "From: " and "Date: ". - -The end of message is signified by the "^_" character, of "\u001f". -The state returns to the state when it sees this -character, otherwise it simply returns message body lines one by one. - -The general flow chart for the lexical states is shown below. It is -useful to make such a diagram when building complex lexical -specifications. - - - ---> --+--> -->+ - ^ | ^ | | - | | | | | - | | | +--> ----->+ - +- <--+ | | | - | | | - | +--> ----->+ - | | - | | - +----------------------------+ diff --git a/examples/MailProcessing/files/1.exp_out.html b/examples/MailProcessing/files/1.exp_out.html deleted file mode 100644 index c85b446..0000000 --- a/examples/MailProcessing/files/1.exp_out.html +++ /dev/null @@ -1,39 +0,0 @@ -A note on using RE's matching the emty string -Subject: A note on using RE's matching the emty string
-From: Sreenivasa Rao Viswanadha <sreeni@cs.albany.edu>
-Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST)
-
- -
In the last couple of days, we had seen a couple of users facing problems with -
regular expressions that match "". There is a minor bug in the way it is -
implemented in 0.6.-9. We will fix it. -
-
But the purpose of this mail is to suggest you should be careful when you use -
RE's that match the "" string. Consider the following example of string literals -
where two consecutive "" are interpreted as the literal " (equivalent to \" in -
Java). -
-
< STRING_LITERAL: ( "\"" (~["\""])* "\"" )* > -
-
This will work in general. But, if this a part of a lot of other lexical rules, -
then if there a lexical error, say a char is given that cannot be the first one -
of any token, then, the lexer decides to use the empty string "" and match it -
as STRING_LITERAL without actually giving the lexical error. And since this is -
the empty string, no character will be consumed and you will start getting the -
same STRING_LITERAL token (with "" as the image) infinte number of times. In -
fact, if this was the only lexical rule, then if you give a input that starts -
with any char other than the ", you will get into an infinite loop. -
-
So a better alternative is to use the + operator which will not match the empty -
string. As a matter of fact, I don't know any practical grammar where matching -
"" is useful. -
-
In version 0.5, the lexer generated implicitly treated it as + (which is not -
totally right). But in 0.6.-9, it does it right and so there is a chance that -
your grammar that used to work with 0.5 will not work with 0.6.-9. So if you -
have any top-level lexical rule with ? or *, please change those rules so that -
they don't match the empty string "". -
-
Sreeni. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/1.out.html b/examples/MailProcessing/files/1.out.html deleted file mode 100644 index c85b446..0000000 --- a/examples/MailProcessing/files/1.out.html +++ /dev/null @@ -1,39 +0,0 @@ -A note on using RE's matching the emty string -Subject: A note on using RE's matching the emty string
-From: Sreenivasa Rao Viswanadha <sreeni@cs.albany.edu>
-Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST)
-
- -
In the last couple of days, we had seen a couple of users facing problems with -
regular expressions that match "". There is a minor bug in the way it is -
implemented in 0.6.-9. We will fix it. -
-
But the purpose of this mail is to suggest you should be careful when you use -
RE's that match the "" string. Consider the following example of string literals -
where two consecutive "" are interpreted as the literal " (equivalent to \" in -
Java). -
-
< STRING_LITERAL: ( "\"" (~["\""])* "\"" )* > -
-
This will work in general. But, if this a part of a lot of other lexical rules, -
then if there a lexical error, say a char is given that cannot be the first one -
of any token, then, the lexer decides to use the empty string "" and match it -
as STRING_LITERAL without actually giving the lexical error. And since this is -
the empty string, no character will be consumed and you will start getting the -
same STRING_LITERAL token (with "" as the image) infinte number of times. In -
fact, if this was the only lexical rule, then if you give a input that starts -
with any char other than the ", you will get into an infinite loop. -
-
So a better alternative is to use the + operator which will not match the empty -
string. As a matter of fact, I don't know any practical grammar where matching -
"" is useful. -
-
In version 0.5, the lexer generated implicitly treated it as + (which is not -
totally right). But in 0.6.-9, it does it right and so there is a chance that -
your grammar that used to work with 0.5 will not work with 0.6.-9. So if you -
have any top-level lexical rule with ? or *, please change those rules so that -
they don't match the empty string "". -
-
Sreeni. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/2.exp_out.html b/examples/MailProcessing/files/2.exp_out.html deleted file mode 100644 index eed7e11..0000000 --- a/examples/MailProcessing/files/2.exp_out.html +++ /dev/null @@ -1,20 +0,0 @@ -Re: Looking for HTML.jack -Subject: Re: Looking for HTML.jack
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Sat, 11 Jan 1997 19:38:32 -0500
-
-Rupert Nagler wrote: -
> -
> I am very impressed by the Jack-Concept and I am looking for a "HTML.jack". -
> Is there anybody out there who has an example of a Jack-Definition file for -
> HTML 3.2? -
-
I previously sent a message entitled "A first cut at an HTML grammar". -
Did people not get it? If not, see: -
http://www.tiac.net/users/kimbo/jack/HTML.jack -
-
> Is there a way to construct a *.jack file out of a *.sgml file? -
-
Sorry, I can't help with this. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/2.out.html b/examples/MailProcessing/files/2.out.html deleted file mode 100644 index eed7e11..0000000 --- a/examples/MailProcessing/files/2.out.html +++ /dev/null @@ -1,20 +0,0 @@ -Re: Looking for HTML.jack -Subject: Re: Looking for HTML.jack
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Sat, 11 Jan 1997 19:38:32 -0500
-
-Rupert Nagler wrote: -
> -
> I am very impressed by the Jack-Concept and I am looking for a "HTML.jack". -
> Is there anybody out there who has an example of a Jack-Definition file for -
> HTML 3.2? -
-
I previously sent a message entitled "A first cut at an HTML grammar". -
Did people not get it? If not, see: -
http://www.tiac.net/users/kimbo/jack/HTML.jack -
-
> Is there a way to construct a *.jack file out of a *.sgml file? -
-
Sorry, I can't help with this. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/3.exp_out.html b/examples/MailProcessing/files/3.exp_out.html deleted file mode 100644 index b569576..0000000 --- a/examples/MailProcessing/files/3.exp_out.html +++ /dev/null @@ -1,22 +0,0 @@ -Re: HTML? -Subject: Re: HTML?
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Mon, 13 Jan 1997 02:03:28 -0500
-
-Well, I finally got an HTML grammar out there (at -
http://www.tiac.net/users/kimbo/jack/HTML.jack). I hope you saw it, I -
got some mailer errors, that seemed like the kind that you could ignore, -
but at least one person didn't receive my first posting. -
-
I'd be interested to know if this is the sort of thing people are -
looking for, or do they want the full set of tags enumerated in the -
grammar as well? Also, if there you have any desire to bundle this with -
Jack (possibly after upgrades and/or integration with other people's -
work), please feel free. -
-
I must say Jack is an amazing tool. It was really easy to learn. I -
love how readable the grammars are, and I love being able to pass info -
up and down the productions as the parser runs. I never want to have to -
settle for LALR(1) again! Thanks for writing it! -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/3.out.html b/examples/MailProcessing/files/3.out.html deleted file mode 100644 index b569576..0000000 --- a/examples/MailProcessing/files/3.out.html +++ /dev/null @@ -1,22 +0,0 @@ -Re: HTML? -Subject: Re: HTML?
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Mon, 13 Jan 1997 02:03:28 -0500
-
-Well, I finally got an HTML grammar out there (at -
http://www.tiac.net/users/kimbo/jack/HTML.jack). I hope you saw it, I -
got some mailer errors, that seemed like the kind that you could ignore, -
but at least one person didn't receive my first posting. -
-
I'd be interested to know if this is the sort of thing people are -
looking for, or do they want the full set of tags enumerated in the -
grammar as well? Also, if there you have any desire to bundle this with -
Jack (possibly after upgrades and/or integration with other people's -
work), please feel free. -
-
I must say Jack is an amazing tool. It was really easy to learn. I -
love how readable the grammars are, and I love being able to pass info -
up and down the productions as the parser runs. I never want to have to -
settle for LALR(1) again! Thanks for writing it! -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/cpy.1.out.html b/examples/MailProcessing/files/cpy.1.out.html deleted file mode 100644 index c85b446..0000000 --- a/examples/MailProcessing/files/cpy.1.out.html +++ /dev/null @@ -1,39 +0,0 @@ -A note on using RE's matching the emty string -Subject: A note on using RE's matching the emty string
-From: Sreenivasa Rao Viswanadha <sreeni@cs.albany.edu>
-Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST)
-
- -
In the last couple of days, we had seen a couple of users facing problems with -
regular expressions that match "". There is a minor bug in the way it is -
implemented in 0.6.-9. We will fix it. -
-
But the purpose of this mail is to suggest you should be careful when you use -
RE's that match the "" string. Consider the following example of string literals -
where two consecutive "" are interpreted as the literal " (equivalent to \" in -
Java). -
-
< STRING_LITERAL: ( "\"" (~["\""])* "\"" )* > -
-
This will work in general. But, if this a part of a lot of other lexical rules, -
then if there a lexical error, say a char is given that cannot be the first one -
of any token, then, the lexer decides to use the empty string "" and match it -
as STRING_LITERAL without actually giving the lexical error. And since this is -
the empty string, no character will be consumed and you will start getting the -
same STRING_LITERAL token (with "" as the image) infinte number of times. In -
fact, if this was the only lexical rule, then if you give a input that starts -
with any char other than the ", you will get into an infinite loop. -
-
So a better alternative is to use the + operator which will not match the empty -
string. As a matter of fact, I don't know any practical grammar where matching -
"" is useful. -
-
In version 0.5, the lexer generated implicitly treated it as + (which is not -
totally right). But in 0.6.-9, it does it right and so there is a chance that -
your grammar that used to work with 0.5 will not work with 0.6.-9. So if you -
have any top-level lexical rule with ? or *, please change those rules so that -
they don't match the empty string "". -
-
Sreeni. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/cpy.2.out.html b/examples/MailProcessing/files/cpy.2.out.html deleted file mode 100644 index eed7e11..0000000 --- a/examples/MailProcessing/files/cpy.2.out.html +++ /dev/null @@ -1,20 +0,0 @@ -Re: Looking for HTML.jack -Subject: Re: Looking for HTML.jack
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Sat, 11 Jan 1997 19:38:32 -0500
-
-Rupert Nagler wrote: -
> -
> I am very impressed by the Jack-Concept and I am looking for a "HTML.jack". -
> Is there anybody out there who has an example of a Jack-Definition file for -
> HTML 3.2? -
-
I previously sent a message entitled "A first cut at an HTML grammar". -
Did people not get it? If not, see: -
http://www.tiac.net/users/kimbo/jack/HTML.jack -
-
> Is there a way to construct a *.jack file out of a *.sgml file? -
-
Sorry, I can't help with this. -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/cpy.3.out.html b/examples/MailProcessing/files/cpy.3.out.html deleted file mode 100644 index b569576..0000000 --- a/examples/MailProcessing/files/cpy.3.out.html +++ /dev/null @@ -1,22 +0,0 @@ -Re: HTML? -Subject: Re: HTML?
-From: kimbo@highway1.com (Kimbo Mundy)
-Date: Mon, 13 Jan 1997 02:03:28 -0500
-
-Well, I finally got an HTML grammar out there (at -
http://www.tiac.net/users/kimbo/jack/HTML.jack). I hope you saw it, I -
got some mailer errors, that seemed like the kind that you could ignore, -
but at least one person didn't receive my first posting. -
-
I'd be interested to know if this is the sort of thing people are -
looking for, or do they want the full set of tags enumerated in the -
grammar as well? Also, if there you have any desire to bundle this with -
Jack (possibly after upgrades and/or integration with other people's -
work), please feel free. -
-
I must say Jack is an amazing tool. It was really easy to learn. I -
love how readable the grammars are, and I love being able to pass info -
up and down the productions as the parser runs. I never want to have to -
settle for LALR(1) again! Thanks for writing it! -
-
\ No newline at end of file diff --git a/examples/MailProcessing/files/cpy.index.out.html b/examples/MailProcessing/files/cpy.index.out.html deleted file mode 100644 index bb8e5a6..0000000 --- a/examples/MailProcessing/files/cpy.index.out.html +++ /dev/null @@ -1,5 +0,0 @@ -Selected list of emails from the JavaCC mailing list -

Selected list of emails from the JavaCC mailing list

-A note on using RE's matching the emty string
-Re: Looking for HTML.jack
-Re: HTML?
diff --git a/examples/MailProcessing/files/digestFile.exp_out b/examples/MailProcessing/files/digestFile.exp_out deleted file mode 100644 index 71e4772..0000000 --- a/examples/MailProcessing/files/digestFile.exp_out +++ /dev/null @@ -1,102 +0,0 @@ -DIGEST OF RECENT MESSAGES FROM THE JAVACC MAILING LIST ----------------------------------------------------------------------- - -MESSAGE SUMMARY: - -1. A note on using RE's matching the emty string -2. Re: Looking for HTML.jack -3. Re: HTML? - ----------------------------------------------------------------------- - - -Message 1: - -Subject: A note on using RE's matching the emty string -From: Sreenivasa Rao Viswanadha -Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST) - - -In the last couple of days, we had seen a couple of users facing problems with -regular expressions that match "". There is a minor bug in the way it is -implemented in 0.6.-9. We will fix it. - -But the purpose of this mail is to suggest you should be careful when you use -RE's that match the "" string. Consider the following example of string literals -where two consecutive "" are interpreted as the literal " (equivalent to \" in -Java). - -< STRING_LITERAL: ( "\"" (~["\""])* "\"" )* > - -This will work in general. But, if this a part of a lot of other lexical rules, -then if there a lexical error, say a char is given that cannot be the first one -of any token, then, the lexer decides to use the empty string "" and match it -as STRING_LITERAL without actually giving the lexical error. And since this is -the empty string, no character will be consumed and you will start getting the -same STRING_LITERAL token (with "" as the image) infinte number of times. In -fact, if this was the only lexical rule, then if you give a input that starts -with any char other than the ", you will get into an infinite loop. - -So a better alternative is to use the + operator which will not match the empty -string. As a matter of fact, I don't know any practical grammar where matching -"" is useful. - -In version 0.5, the lexer generated implicitly treated it as + (which is not -totally right). But in 0.6.-9, it does it right and so there is a chance that -your grammar that used to work with 0.5 will not work with 0.6.-9. So if you -have any top-level lexical rule with ? or *, please change those rules so that -they don't match the empty string "". - -Sreeni. - - ----------------------------------------------------------------------- - -Message 2: - -Subject: Re: Looking for HTML.jack -From: kimbo@highway1.com (Kimbo Mundy) -Date: Sat, 11 Jan 1997 19:38:32 -0500 - -Rupert Nagler wrote: -> -> I am very impressed by the Jack-Concept and I am looking for a "HTML.jack". -> Is there anybody out there who has an example of a Jack-Definition file for -> HTML 3.2? - -I previously sent a message entitled "A first cut at an HTML grammar". -Did people not get it? If not, see: -http://www.tiac.net/users/kimbo/jack/HTML.jack - -> Is there a way to construct a *.jack file out of a *.sgml file? - -Sorry, I can't help with this. - - ----------------------------------------------------------------------- - -Message 3: - -Subject: Re: HTML? -From: kimbo@highway1.com (Kimbo Mundy) -Date: Mon, 13 Jan 1997 02:03:28 -0500 - -Well, I finally got an HTML grammar out there (at -http://www.tiac.net/users/kimbo/jack/HTML.jack). I hope you saw it, I -got some mailer errors, that seemed like the kind that you could ignore, -but at least one person didn't receive my first posting. - -I'd be interested to know if this is the sort of thing people are -looking for, or do they want the full set of tags enumerated in the -grammar as well? Also, if there you have any desire to bundle this with -Jack (possibly after upgrades and/or integration with other people's -work), please feel free. - -I must say Jack is an amazing tool. It was really easy to learn. I -love how readable the grammars are, and I love being able to pass info -up and down the productions as the parser runs. I never want to have to -settle for LALR(1) again! Thanks for writing it! - - ----------------------------------------------------------------------- - diff --git a/examples/MailProcessing/files/index.exp_out.html b/examples/MailProcessing/files/index.exp_out.html deleted file mode 100644 index bb8e5a6..0000000 --- a/examples/MailProcessing/files/index.exp_out.html +++ /dev/null @@ -1,5 +0,0 @@ -Selected list of emails from the JavaCC mailing list -

Selected list of emails from the JavaCC mailing list

-A note on using RE's matching the emty string
-Re: Looking for HTML.jack
-Re: HTML?
diff --git a/examples/MailProcessing/files/index.out.html b/examples/MailProcessing/files/index.out.html deleted file mode 100644 index bb8e5a6..0000000 --- a/examples/MailProcessing/files/index.out.html +++ /dev/null @@ -1,5 +0,0 @@ -Selected list of emails from the JavaCC mailing list -

Selected list of emails from the JavaCC mailing list

-A note on using RE's matching the emty string
-Re: Looking for HTML.jack
-Re: HTML?
diff --git a/examples/MailProcessing/files/sampleMailFile.in b/examples/MailProcessing/files/sampleMailFile.in deleted file mode 100644 index bfb75c5..0000000 --- a/examples/MailProcessing/files/sampleMailFile.in +++ /dev/null @@ -1,237 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -BABYL OPTIONS: -Version: 5 -Labels: -Note: This is the header of an rmail file. -Note: If you are seeing it in rmail, -Note: it means the file has no messages in it. - -1, filed,, -Summary-line: 11-Jan sreeni@cs.albany.edu #A note on using RE's matching the emty string -Return-Path: -Received: from Eng.Sun.COM by schizophrenia.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id HAA21134; Sat, 11 Jan 1997 07:47:28 -0800 -Received: from sunmail1.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id HAA02652; Sat, 11 Jan 1997 07:44:26 -0800 -Received: from Eng.Sun.COM by sunmail1.Sun.COM (SMI-8.6/SMI-4.1) - id HAA06974; Sat, 11 Jan 1997 07:44:26 -0800 -Received: from suntest.Eng.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id HAA02640; Sat, 11 Jan 1997 07:44:24 -0800 -Received: from asap.Eng.Sun.COM by suntest.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id HAA21295; Sat, 11 Jan 1997 07:44:18 -0800 -Received: from Eng.Sun.COM by asap.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id HAA24684; Sat, 11 Jan 1997 07:44:19 -0800 -Received: from mercury.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id HAA02630; Sat, 11 Jan 1997 07:44:17 -0800 -Received: from cs.albany.edu (cs.albany.edu [169.226.2.22]) by mercury.Sun.COM (SMI-8.6/mail.byaddr) with SMTP id HAA01828 for ; Sat, 11 Jan 1997 07:44:18 -0800 -Received: from bhaskara.cs.albany.edu (sreeni@bhaskara.cs.albany.edu [169.226.2.60]) by cs.albany.edu (8.7.4/HUB03) with ESMTP id KAA01464; Sat, 11 Jan 1997 10:44:06 -0500 (EST) -Received: (from sreeni@localhost) by bhaskara.cs.albany.edu (8.7.4/CLI2) id KAA09608; Sat, 11 Jan 1997 10:43:58 -0500 (EST) -From: Sreenivasa Rao Viswanadha -Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST) -Message-Id: <199701111543.KAA09608@bhaskara.cs.albany.edu> -To: jack-interest@asap.Eng.Sun.COM -Subject: A note on using RE's matching the emty string -Cc: sreeni@cs.albany.edu -X-Sun-Charset: US-ASCII -Content-Type: text -Content-Length: 1639 -X-Lines: 32 -Status: RO - -*** EOOH *** -Return-Path: -From: Sreenivasa Rao Viswanadha -Date: Sat, 11 Jan 1997 10:43:58 -0500 (EST) -To: jack-interest@asap.Eng.Sun.COM -Subject: A note on using RE's matching the emty string -Cc: sreeni@cs.albany.edu -X-Sun-Charset: US-ASCII -Content-Type: text -Content-Length: 1639 -X-Lines: 32 - - -In the last couple of days, we had seen a couple of users facing problems with -regular expressions that match "". There is a minor bug in the way it is -implemented in 0.6.-9. We will fix it. - -But the purpose of this mail is to suggest you should be careful when you use -RE's that match the "" string. Consider the following example of string literals -where two consecutive "" are interpreted as the literal " (equivalent to \" in -Java). - -< STRING_LITERAL: ( "\"" (~["\""])* "\"" )* > - -This will work in general. But, if this a part of a lot of other lexical rules, -then if there a lexical error, say a char is given that cannot be the first one -of any token, then, the lexer decides to use the empty string "" and match it -as STRING_LITERAL without actually giving the lexical error. And since this is -the empty string, no character will be consumed and you will start getting the -same STRING_LITERAL token (with "" as the image) infinte number of times. In -fact, if this was the only lexical rule, then if you give a input that starts -with any char other than the ", you will get into an infinite loop. - -So a better alternative is to use the + operator which will not match the empty -string. As a matter of fact, I don't know any practical grammar where matching -"" is useful. - -In version 0.5, the lexer generated implicitly treated it as + (which is not -totally right). But in 0.6.-9, it does it right and so there is a chance that -your grammar that used to work with 0.5 will not work with 0.6.-9. So if you -have any top-level lexical rule with ? or *, please change those rules so that -they don't match the empty string "". - -Sreeni. - - -1,, -Summary-line: 11-Jan kimbo@highway1.com #Re: Looking for HTML.jack -Return-Path: -Received: from Eng.Sun.COM by schizophrenia.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id QAA21339; Sat, 11 Jan 1997 16:41:53 -0800 -Received: from sunmail1.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id QAA18458; Sat, 11 Jan 1997 16:38:44 -0800 -Received: from Eng.Sun.COM by sunmail1.Sun.COM (SMI-8.6/SMI-4.1) - id QAA16642; Sat, 11 Jan 1997 16:38:51 -0800 -Received: from suntest.Eng.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id QAA18449; Sat, 11 Jan 1997 16:38:42 -0800 -Received: from asap.Eng.Sun.COM by suntest.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id QAA23127; Sat, 11 Jan 1997 16:38:42 -0800 -Received: from Eng.Sun.COM by asap.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id QAA24956; Sat, 11 Jan 1997 16:38:41 -0800 -Received: from mercury.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id QAA18438; Sat, 11 Jan 1997 16:38:36 -0800 -Received: from chmls01.highway1.com (ne.highway1.com [24.128.1.82]) by mercury.Sun.COM (SMI-8.6/mail.byaddr) with SMTP id QAA22125 for ; Sat, 11 Jan 1997 16:38:42 -0800 -Received: from papa ([24.128.36.164]) by chmls01.highway1.com - (Netscape Mail Server v2.0) with SMTP id AAA17669; - Sat, 11 Jan 1997 19:38:31 -0400 -Message-ID: <32D83288.5A8@highway1.com> -Date: Sat, 11 Jan 1997 19:38:32 -0500 -From: kimbo@highway1.com (Kimbo Mundy) -X-Mailer: Mozilla 3.0Gold (WinNT; U) -MIME-Version: 1.0 -To: Rupert Nagler -CC: jack-interest@asap.Eng.Sun.COM -Subject: Re: Looking for HTML.jack -References: <1.5.4.32.19970111214054.0069e40c@mail.austria.eu.net> -Content-Transfer-Encoding: 7bit -X-Lines: 13 -Status: RO -Content-Type: text/plain; charset="us-ascii" -Content-Length: 447 - -*** EOOH *** -Return-Path: -Date: Sat, 11 Jan 1997 19:38:32 -0500 -From: kimbo@highway1.com (Kimbo Mundy) -X-Mailer: Mozilla 3.0Gold (WinNT; U) -MIME-Version: 1.0 -To: Rupert Nagler -CC: jack-interest@asap.Eng.Sun.COM -Subject: Re: Looking for HTML.jack -References: <1.5.4.32.19970111214054.0069e40c@mail.austria.eu.net> -Content-Transfer-Encoding: 7bit -X-Lines: 13 -Content-Type: text/plain; charset="us-ascii" -Content-Length: 447 - -Rupert Nagler wrote: -> -> I am very impressed by the Jack-Concept and I am looking for a "HTML.jack". -> Is there anybody out there who has an example of a Jack-Definition file for -> HTML 3.2? - -I previously sent a message entitled "A first cut at an HTML grammar". -Did people not get it? If not, see: -http://www.tiac.net/users/kimbo/jack/HTML.jack - -> Is there a way to construct a *.jack file out of a *.sgml file? - -Sorry, I can't help with this. - - -1,, -Summary-line: 13-Jan kimbo@highway1.com #Re: HTML? -Return-Path: -Received: from suntest.Eng.Sun.COM by schizophrenia.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id XAA21746; Sun, 12 Jan 1997 23:06:34 -0800 -Received: from Eng.Sun.COM by suntest.Eng.Sun.COM (SMI-8.6/SMI-SVR4) - id XAA29422; Sun, 12 Jan 1997 23:03:31 -0800 -Received: from mercury.Sun.COM by Eng.Sun.COM (SMI-8.6/SMI-5.3) - id XAA07269; Sun, 12 Jan 1997 23:03:30 -0800 -Received: from chmls01.highway1.com (ne.highway1.com [24.128.1.82]) by mercury.Sun.COM (SMI-8.6/mail.byaddr) with SMTP id XAA18021 for ; Sun, 12 Jan 1997 23:03:30 -0800 -Received: from papa ([24.128.36.164]) by chmls01.highway1.com - (Netscape Mail Server v2.0) with SMTP id AAA20062 - for ; Mon, 13 Jan 1997 02:03:25 -0400 -Message-ID: <32D9DE40.3604@highway1.com> -Date: Mon, 13 Jan 1997 02:03:28 -0500 -From: kimbo@highway1.com (Kimbo Mundy) -X-Mailer: Mozilla 3.0Gold (WinNT; U) -MIME-Version: 1.0 -To: Sriram Sankar -Subject: Re: HTML? -References: <199612162037.MAA29649@schizophrenia.Eng.Sun.COM> -Content-Transfer-Encoding: 7bit -X-Lines: 34 -Status: RO -Content-Type: text/plain; charset="us-ascii" -Content-Length: 1420 - -*** EOOH *** -Return-Path: -Date: Mon, 13 Jan 1997 02:03:28 -0500 -From: kimbo@highway1.com (Kimbo Mundy) -X-Mailer: Mozilla 3.0Gold (WinNT; U) -MIME-Version: 1.0 -To: Sriram Sankar -Subject: Re: HTML? -References: <199612162037.MAA29649@schizophrenia.Eng.Sun.COM> -Content-Transfer-Encoding: 7bit -X-Lines: 34 -Content-Type: text/plain; charset="us-ascii" -Content-Length: 1420 - -Well, I finally got an HTML grammar out there (at -http://www.tiac.net/users/kimbo/jack/HTML.jack). I hope you saw it, I -got some mailer errors, that seemed like the kind that you could ignore, -but at least one person didn't receive my first posting. - -I'd be interested to know if this is the sort of thing people are -looking for, or do they want the full set of tags enumerated in the -grammar as well? Also, if there you have any desire to bundle this with -Jack (possibly after upgrades and/or integration with other people's -work), please feel free. - -I must say Jack is an amazing tool. It was really easy to learn. I -love how readable the grammars are, and I love being able to pass info -up and down the productions as the parser runs. I never want to have to -settle for LALR(1) again! Thanks for writing it! - - diff --git a/examples/MailProcessing/pom.xml b/examples/MailProcessing/pom.xml deleted file mode 100644 index 48fccd8..0000000 --- a/examples/MailProcessing/pom.xml +++ /dev/null @@ -1,182 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - mailprocessing - jar - - JavaCC Java code generator / examples / MailProcessing - - - - - - - org.apache.maven.plugins - maven-clean-plugin - - - clear-res-test - process-test-resources - - clean - - - true - - - files - - cpy.*,*.out,*.out.html - - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - exec-Digest-test - test - - java - - - ${skip.test.java.examples.MailProcessing.Digest} - dig.DigestMain - - ${project.basedir}/files/sampleMailFile.in - ${project.basedir}/files/digestFile.out - - - - - exec-Faq-test - test - - java - - - ${skip.test.java.examples.MailProcessing.Faq} - faq.FaqMain - - 1 - ${project.basedir}/files/sampleMailFile.in - ${project.basedir}/files - - - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - check-Digest-test - test - - run - - - ${skip.test.java.examples.MailProcessing.Digest} - ${failOnError.check.java.examples.MailProcessing.Digest} - - - - - - - - - - - check-Faq-test - test - - run - - - ${skip.test.java.examples.MailProcessing.Faq} - ${failOnError.check.java.examples.MailProcessing.Faq} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/MailProcessing/src/main/java/dig/DigestMain.java b/examples/MailProcessing/src/main/java/dig/DigestMain.java deleted file mode 100644 index 5449729..0000000 --- a/examples/MailProcessing/src/main/java/dig/DigestMain.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package dig; - -import java.io.*; - -public class DigestMain { - - PrintWriter digpw; - - /* - * Note that this example silently displays nothing on these 3 exceptions, - * and IOException is indeed occurring when the end of the input file is reached - * and seen by the SimpleCharStream, who throws a new IOException(). - */ - - public static void main(String[] args) throws ParseException, IOException, FileNotFoundException { - if (args.length < 1) { - System.err.println("Error: bad number of arguments (" + args.length + " instead of 2)"); - System.err.println("Usage: DigestMain infile outfile"); - System.exit(4); - } - DigestMain dm = new DigestMain(); - dm.doMain(args); - } - - void doMain(String[] args) throws ParseException, IOException, FileNotFoundException { - digpw = new PrintWriter(new FileWriter(args[1])); - Digest parser = new Digest(new FileInputStream(args[0])); - parser.setDigpw(digpw); - - digpw.println("DIGEST OF RECENT MESSAGES FROM THE JAVACC MAILING LIST"); - digpw.println("----------------------------------------------------------------------"); - digpw.println(""); - digpw.println("MESSAGE SUMMARY:"); - digpw.println(""); - - String buffer = parser.MailFile(); - - if (buffer.length() == 0) { - digpw.println("There have been no messages since the last digest posting."); - digpw.println(""); - digpw.println("----------------------------------------------------------------------"); - } else { - digpw.println(""); - digpw.println("----------------------------------------------------------------------"); - digpw.println(""); - digpw.println(buffer); - } - digpw.close(); - } -} diff --git a/examples/MailProcessing/src/main/java/faq/FaqMain.java b/examples/MailProcessing/src/main/java/faq/FaqMain.java deleted file mode 100644 index 16f5716..0000000 --- a/examples/MailProcessing/src/main/java/faq/FaqMain.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package faq; - -import java.io.*; - -public class FaqMain { - - static int count = 0; - - static int beginAt = 1; - - static String outdir; - - static PrintWriter indexpw; - - static String fix(String s) { - String retval = ""; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '<') { - retval += "<"; - } else if (c == '>') { - retval += ">"; - } else { - retval += c; - } - } - return retval; - } - - /* - * Note that this example silently displays nothing on these 3 exceptions, - * and IOException is indeed occurring when the end of the input file is reached - * and seen by the SimpleCharStream, who throws a new IOException(). - */ - - public static void main(String args[]) throws ParseException, IOException, FileNotFoundException { - if (args.length < 2) { - System.err.println("Error: bad number of arguments (" + args.length + " instead of 3)"); - System.err.println("Usage: FaqMain index infile outdir"); - System.exit(4); - } - - beginAt = Integer.parseInt(args[0]); - outdir = args[2]; - indexpw = new PrintWriter(new FileWriter(outdir + "/index.out.html")); - indexpw.println("Selected list of emails from the JavaCC mailing list"); - indexpw.println("

Selected list of emails from the JavaCC mailing list

"); - - Faq parser = new Faq(new FileInputStream(args[1])); - parser.MailFile(); - } -} diff --git a/examples/MailProcessing/src/main/javacc/Digest.jj b/examples/MailProcessing/src/main/javacc/Digest.jj deleted file mode 100644 index 3a4150a..0000000 --- a/examples/MailProcessing/src/main/javacc/Digest.jj +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options { - STATIC = false; // not JavaCC's default; not the same as Faq -} - -PARSER_BEGIN(Digest) -package dig; // different from Faq, to allow different helper files - -import java.io.*; - -public class Digest { - private int count = 0; - PrintWriter digpw; - -public void setDigpw(final PrintWriter aDigpw) { - digpw = aDigpw; - } -} - -PARSER_END(Digest) - -String MailFile() : -{ - String mail, mails = ""; - System.out.print("Digest: "); -} -{ - ( - { - count++; - } - mail = MailMessage() - { - mails += mail; - System.out.print(count + ". "); - System.out.flush(); - } - )* - - { - System.out.println(); - return mails; - } -} - -String MailMessage() : -{ - Token subj = null, from = null, date = null, body; - String buffer = ""; -} -{ - ( subj = | from = | date = )+ - { - digpw.println(count + ". " + ( subj == null ? "no subject" : subj.image) ); - buffer += "\n"; - buffer += "Message " + count + ":\n"; - buffer += "\n"; - buffer += "Subject: " + (subj == null ? "no subject" : subj.image) + "\n"; - buffer += "From: " + (from == null ? "" : from.image) + "\n"; - buffer += "Date: " + (date == null ? "" : date.image) + "\n"; - buffer += "\n"; - } - ( - body = - { - buffer += body.image; - } - )* - - { - buffer += "\n"; - buffer += "----------------------------------------------------------------------\n"; - return buffer; - } -} - -TOKEN : -{ - < #EOL : "\n" | "\r" | "\r\n" > -| - < #TWOEOLS : ( ( "\n" | "\r\n" ) ) | ( "\r\r" [ "\n" ] )> -| - < #NOT_EOL : ~[ "\n", "\r" ] > -} - - -SKIP : -{ - < "*** EOOH ***" > : MAILHEADER -| - <~[]> -} - - -SKIP : -{ - < _TWOEOLS : > : MAILBODY - // We cannot have just a reference to a regular expression in a - // lexical specification - i.e., we cannot simply have . -| - "Subject: " : MAILSUBJECT -| - "From: " : MAILFROM -| - "Date: " : MAILDATE -| - <~[]> -} - - -TOKEN : -{ - < SUBJECT : ( )+ > -} - - -SKIP : -{ - < _EOL1 : > : MAILHEADER -} - - -TOKEN : -{ - < FROM : ( )+ > -} - - -SKIP: -{ - < _EOL2 : > : MAILHEADER -} - - -TOKEN: -{ - < DATE : ( )+ > -} - - -SKIP : -{ - < _EOL3 : > : MAILHEADER -} - - -TOKEN : -{ - < BODY : ( ~["\n", "\r", "\u001f" ] )* > -| - < END : "\u001f" > : DEFAULT -} diff --git a/examples/MailProcessing/src/main/javacc/Faq.jj b/examples/MailProcessing/src/main/javacc/Faq.jj deleted file mode 100644 index 8e3815e..0000000 --- a/examples/MailProcessing/src/main/javacc/Faq.jj +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2020-2025, Sreeni Viswanadha . - * Copyright (c) 2024-2025, Marc Mazas . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -options { - STATIC = true; // JavaCC's default; not the same as Digest -} - -PARSER_BEGIN(Faq) -package faq; // different from Digest, to allow different helper files - -import java.io.*; - -public class Faq { - static int count = FaqMain.count; - static int beginAt = FaqMain.beginAt; - static String outdir = FaqMain.outdir; - static PrintWriter indexpw = FaqMain.indexpw; -} - -PARSER_END(Faq) - -void MailFile() : -{ - System.out.print("Faq: "); -} -{ - ( - { - count++; - } - MailMessage() - { - System.out.print(count + ". "); - System.out.flush(); - } - )* - - { - System.out.println(""); - indexpw.close(); - } -} - -void MailMessage() : -{ - PrintWriter msgpw = null; - Token subj = null, from = null, date = null, body; - if (count >= beginAt) { - try { - msgpw = new PrintWriter(new FileWriter(outdir + "/" + count + ".out.html")); - } catch (IOException e) { - System.err.println("IOE on " +outdir + "/" + count + ".out.html"); - e.printStackTrace(); - System.exit(4); - } - } else { - System.err.println("count (" + count + ") < beginAt (" + beginAt + ")" ); - return; - } -} -{ - ( subj = | from = | date = )+ - { - indexpw.print(""); - if (subj == null) { - indexpw.println("no subject
"); - } else { - indexpw.println(FaqMain.fix(subj.image) + "
"); - } - if (count >= beginAt) { - msgpw.println("" + (subj==null ? "no subject" : FaqMain.fix(subj.image)) + ""); - msgpw.println("Subject: " + (subj==null ? "no subject" : FaqMain.fix(subj.image)) + "
"); - msgpw.println("From: " + (from==null ? "" : FaqMain.fix(from.image)) + "
"); - msgpw.println("Date: " + (date==null ? "" : FaqMain.fix(date.image)) + "
"); - msgpw.println("
"); - } - } - ( - body = - { - if (count >= beginAt) { - msgpw.print(FaqMain.fix(body.image) + "
"); - } - } - )* - - { - if (msgpw != null) { - msgpw.close(); - } - } -} - -TOKEN: -{ - <#EOL: "\n" | "\r" | "\r\n"> -| - <#TWOEOLS: ( ( "\n" | "\r\n" ) ) | ( "\r\r" [ "\n" ] )> -| - <#NOT_EOL: ~[ "\n", "\r" ]> -} - - -SKIP : -{ - < "*** EOOH ***" > : MAILHEADER -| - <~[]> -} - - -SKIP : -{ - < _TWOEOLS : > : MAILBODY - // We cannot have just a reference to a regular expression in a - // lexical specification - i.e., we cannot simply have . -| - "Subject: " : MAILSUBJECT -| - "From: " : MAILFROM -| - "Date: " : MAILDATE -| - <~[]> -} - - -TOKEN : -{ - < SUBJECT : ( )+ > -} - - -SKIP : -{ - < _EOL1 : > : MAILHEADER -} - - -TOKEN : -{ - < FROM : ( )+ > -} - - -SKIP: -{ - < _EOL2 : > : MAILHEADER -} - - -TOKEN: -{ - < DATE : ( )+ > -} - - -SKIP : -{ - < _EOL3 : > : MAILHEADER -} - - -TOKEN : -{ - < BODY : ( ~["\n", "\r", "\u001f" ] )* > -| - < END : "\u001f" > : DEFAULT -} diff --git a/examples/Obfuscator/README b/examples/Obfuscator/README deleted file mode 100644 index 24d4769..0000000 --- a/examples/Obfuscator/README +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This directory contains an obfuscation program. This program takes -the following inputs: - -. An input directory which contains the original Java programs. This - must be the CLASSPATH directory. All Java files within this - directory except those under SCCS directories are considered for - obfuscation. - -. An output directory into which the obfuscated files are generated. - It should be possible to build the obfuscated version by setting the - CLASSPATH to this directory. - -. A file of mappings of the form: - ( originalId "->" obfuscatedId ";" )* - This specifies mappings from original identifiers to corresponding - obfuscated ones. This file is optional, and even when it is - present, it does not have to specify all identifiers in the input - file. - -. A file containing identifiers that must not be obfuscated. This is - typically used to prevent references to the standard API's from - being changed. This file is optional. - -. A file containing identifiers to be used for obfuscation. If an - identifier is encountered in the original file that does not have a - specified mapping and is not an identifier that must not be - obfuscated, then identifiers from this file are used for - obfuscation. Once identifiers from this file are exhausted, then - identifiers starting with "O0" the letter 'O' followed by the digit - '0' are generated automatically. This file is optional. - -The output of the program is: - -. An obfuscated version for each input Java file. Since package and - class names are also obfuscated, the directory and file names will - be different also. - -. A main program for each of the original main programs in their - original forms (with the same package and class names) that calls - the corresponding obfuscated main program. This is useful to retain - access to the system as before. - -. A file containing all the mappings used during the obfuscation - process. This file is in the same syntax as the input mapping file, - and therefore it can be used as input for future obfuscations. This - is useful when related systems are obfuscated in different runs of - this program. - -To build the obfuscator, do the following: - - javacc Java1.1.jj - javacc IdsFile.jj - javacc MapFile.jj - javac *.java - -Now the obfuscator is ready for use. Try it out as follows on the -example provided: - - java Main input output maps nochangeids useids - -And take a look at the input and output directories. - -This example illustrates the use of multiple grammar files, some of -which are used more than once while the system is running. Take a -look at the usage of ReInit's and also the actions in the grammar. -Note how easy it was to include actions into the Java grammar to -determine whether or not it had a main program. Also note how easy it -is to modify this program. - -Some comments are present in each of the files that comprise this -example. diff --git a/examples/Obfuscator/in/package1/Main.java b/examples/Obfuscator/in/package1/Main.java deleted file mode 100644 index 1683248..0000000 --- a/examples/Obfuscator/in/package1/Main.java +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -package package1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Calling incr 10 times..."); - for (int i = 0; i < 10; i++) { - System.out.println(package2.Incr.incr()); - } - } - -} diff --git a/examples/Obfuscator/in/package2/Incr.java b/examples/Obfuscator/in/package2/Incr.java deleted file mode 100644 index 83064c4..0000000 --- a/examples/Obfuscator/in/package2/Incr.java +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -package package2; - -public class Incr { - - static private int count = 0; - - /** - * Returns the next integer value each time it is called. The - * state information is stored in the variable count. - */ - static public int incr() { - return count++; - } - -} diff --git a/examples/Obfuscator/obf/maps b/examples/Obfuscator/obf/maps deleted file mode 100644 index be154a8..0000000 --- a/examples/Obfuscator/obf/maps +++ /dev/null @@ -1,4 +0,0 @@ -// Mappings from original names to obfuscated names - -incr -> square_root; -Incr -> MyMath; diff --git a/examples/Obfuscator/obf/nochangeids b/examples/Obfuscator/obf/nochangeids deleted file mode 100644 index 10d0a2b..0000000 --- a/examples/Obfuscator/obf/nochangeids +++ /dev/null @@ -1,6 +0,0 @@ -// Identifiers that must not be obfuscated. - -System -out -println -String diff --git a/examples/Obfuscator/obf/useids b/examples/Obfuscator/obf/useids deleted file mode 100644 index 173aa07..0000000 --- a/examples/Obfuscator/obf/useids +++ /dev/null @@ -1,5 +0,0 @@ -// Obfuscated identifiers to use (preferably). - -fileName -randomNumber -html diff --git a/examples/Obfuscator/out/O01/MyMath.java b/examples/Obfuscator/out/O01/MyMath.java deleted file mode 100644 index a178196..0000000 --- a/examples/Obfuscator/out/O01/MyMath.java +++ /dev/null @@ -1,15 +0,0 @@ -package O01; - -public class MyMath { - - static private int O02 = 0; - - - - - - static public int square_root() { - return O02++; - } - -} diff --git a/examples/Obfuscator/out/html/randomNumber.java b/examples/Obfuscator/out/html/randomNumber.java deleted file mode 100644 index 803d9f0..0000000 --- a/examples/Obfuscator/out/html/randomNumber.java +++ /dev/null @@ -1,12 +0,0 @@ -package html; - -public class randomNumber { - - public static void main(String[] fileName) { - System.out.println("Calling incr 10 times..."); - for (int O00 = 0; O00 < 10; O00++) { - System.out.println(O01.MyMath.square_root()); - } - } - -} diff --git a/examples/Obfuscator/out/package1/Main.java b/examples/Obfuscator/out/package1/Main.java deleted file mode 100644 index 545e98a..0000000 --- a/examples/Obfuscator/out/package1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package package1; - -public class Main { - - public static void main(String[] args) { - html.randomNumber.main(args); - } - -} diff --git a/examples/Obfuscator/pom.xml b/examples/Obfuscator/pom.xml deleted file mode 100644 index e41f653..0000000 --- a/examples/Obfuscator/pom.xml +++ /dev/null @@ -1,154 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - obfuscator - jar - - JavaCC Java code generator / examples / Obfuscator - - - - - - org.codehaus.mojo - exec-maven-plugin - - - test - - java - - - - - Main - - ${project.basedir}/in - ${project.basedir}/out - ${project.basedir}/obf/maps - ${project.basedir}/obf/nochangeids - ${project.basedir}/obf/useids - - - - - - - - - \ No newline at end of file diff --git a/examples/Obfuscator/ref/O01/MyMath.java b/examples/Obfuscator/ref/O01/MyMath.java deleted file mode 100644 index a178196..0000000 --- a/examples/Obfuscator/ref/O01/MyMath.java +++ /dev/null @@ -1,15 +0,0 @@ -package O01; - -public class MyMath { - - static private int O02 = 0; - - - - - - static public int square_root() { - return O02++; - } - -} diff --git a/examples/Obfuscator/ref/html/randomNumber.java b/examples/Obfuscator/ref/html/randomNumber.java deleted file mode 100644 index 803d9f0..0000000 --- a/examples/Obfuscator/ref/html/randomNumber.java +++ /dev/null @@ -1,12 +0,0 @@ -package html; - -public class randomNumber { - - public static void main(String[] fileName) { - System.out.println("Calling incr 10 times..."); - for (int O00 = 0; O00 < 10; O00++) { - System.out.println(O01.MyMath.square_root()); - } - } - -} diff --git a/examples/Obfuscator/ref/package1/Main.java b/examples/Obfuscator/ref/package1/Main.java deleted file mode 100644 index 545e98a..0000000 --- a/examples/Obfuscator/ref/package1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package package1; - -public class Main { - - public static void main(String[] args) { - html.randomNumber.main(args); - } - -} diff --git a/examples/Obfuscator/src/main/java/Globals.java b/examples/Obfuscator/src/main/java/Globals.java deleted file mode 100644 index 64d5e24..0000000 --- a/examples/Obfuscator/src/main/java/Globals.java +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -import java.io.*; -import java.util.*; - -public class Globals { - - // The mappings from old id's to new id's. - static Hashtable mappings = new Hashtable(); - - // A table of targets of all known mappings. - static Hashtable mapTargets = new Hashtable(); - - // These id's may not be changed. - static Hashtable noChangeIds = new Hashtable(); - - // These id's should be used for mappings. - static Hashtable useIds = new Hashtable(); - - // The location of the input and output directories. - static File inpDir, outDir; - - // Set to true by Java parser if class has a main program. - static boolean mainExists; - - // Returns the map of old to obfuscated id. If map does not - // exist, it is created. - static String map(String str) { - Object obj = mappings.get(str); - if (obj != null) { - return (String)obj; - } - if (useIds.isEmpty()) { - String newId = "O0" + counter++; - mappings.put(str, newId); - return newId; - } else { - obj = useIds.keys().nextElement(); - useIds.remove(obj); - String newId = (String)obj; - mappings.put(str, newId); - return newId; - } - } - - // A counter used to generate new identifiers - static int counter = 0; - -} diff --git a/examples/Obfuscator/src/main/java/Main.java b/examples/Obfuscator/src/main/java/Main.java deleted file mode 100644 index 99edbb4..0000000 --- a/examples/Obfuscator/src/main/java/Main.java +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -import java.io.*; -import java.util.*; - -public class Main extends Globals { - - /* - * This main program collects the input arguments. If one or more of the three - * latter arguments are present, then these files are opened and parsed with the - * appropriate parsers. Then the method Obfuscator.start() is called that does - * the actual obfuscation. Finally, the file map.log is generated. - */ - public static void main(String[] args) throws FileNotFoundException { - IdsFile idparser = null; - if (args.length < 2 || args.length > 5) { - System.out.println("Usage is \"java Main \""); - System.out.println(" must be the CLASSPATH directory."); - System.out.println(" , , and are optional, but if any of"); - System.out.println(" these are present, then the ones preceding them must also be present."); - return; - } - inpDir = new File(args[0]); - if (!inpDir.isDirectory()) { - System.out.println("Error: " + args[0] + " is not a directory."); - return; - } - outDir = new File(args[1]); - if (outDir.exists()) { - if (!outDir.isDirectory()) { - System.out.println("Error: " + args[1] + " is not a directory."); - return; - } - } else { - System.out.println(args[1] + " does not exist. Will create it."); - if (!outDir.mkdirs()) { - System.out.println("Could not create directory " + args[1]); - return; - } - } - if (args.length >= 4) { - try { - idparser = new IdsFile(new FileInputStream(args[3])); - idparser.input(true, args[3]); - } catch (ParseException e) { - System.out.println("Parse error in " + args[3]); - return; - } - } - if (args.length >= 3) { - try { - MapFile mapparser = new MapFile(new FileInputStream(args[2])); - mapparser.input(); - } catch (ParseException e) { - System.out.println("Parse error in " + args[2]); - return; - } - } - if (args.length == 5) { - try { - idparser.ReInit(new FileInputStream(args[4])); - idparser.input(false, args[4]); - } catch (ParseException e) { - System.out.println("Parse error in " + args[4]); - return; - } - } - mappings.put("main", "main"); - Obfuscator.start(); - System.out.println("Dumping mappings used into map.log."); - PrintWriter mstr; - try { - mstr = new PrintWriter(new FileWriter("map.log")); - } catch (IOException e) { - System.out.println("Could not create file map.log"); - throw new Error(); - } - for (Enumeration enumeration = mappings.keys(); enumeration.hasMoreElements();) { - String from = (String)enumeration.nextElement(); - String to = (String)mappings.get(from); - mstr.println(from + " -> " + to + ";"); - } - mstr.close(); - } - -} diff --git a/examples/Obfuscator/src/main/java/Obfuscator.java b/examples/Obfuscator/src/main/java/Obfuscator.java deleted file mode 100644 index bb43469..0000000 --- a/examples/Obfuscator/src/main/java/Obfuscator.java +++ /dev/null @@ -1,268 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -import java.io.*; -import java.util.*; - -public class Obfuscator extends Globals { - - // These data structures implement a stack that is used to recursively - // walk the input directory structure looking for Java files. - - static String[][] dirStack = new String[100][]; - static int[] dirStackIndex = new int[100]; - static int dirStackSize; - static File[] dirFile = new File[100]; - - static { - dirFile[0] = inpDir; - dirStackSize = 1; - dirStack[dirStackSize] = dirFile[dirStackSize-1].list(); - dirStackIndex[dirStackSize] = 0; - } - - // Returns true if this is a Java file. - static boolean javaFile(String name) { - if (name.length() < 6) { - return false; - } - if (name.substring(name.length() - 5).equals(".java")) { - return true; - } - return false; - } - - // The iterator. This uses the above datastructures to walk the input - // directory tree. Every time it finds a Java file or when it cannot find - // any more Java file, it returns to the caller. - static void nextJavaFile() { - while (true) { - if (dirStackIndex[dirStackSize] == dirStack[dirStackSize].length) { - dirStackSize--; - if (dirStackSize == 0) { - return; - } else { - dirStackIndex[dirStackSize]++; - } - } else { - dirFile[dirStackSize] = new File(dirFile[dirStackSize-1], - dirStack[dirStackSize][dirStackIndex[dirStackSize]]); - if (dirStack[dirStackSize][dirStackIndex[dirStackSize]].equals("SCCS")) { - dirStackIndex[dirStackSize]++; - } else if (dirFile[dirStackSize].isDirectory()) { - dirStackSize++; - dirStack[dirStackSize] = dirFile[dirStackSize-1].list(); - dirStackIndex[dirStackSize] = 0; - } else if (javaFile(dirStack[dirStackSize][dirStackIndex[dirStackSize]])) { - dirStackIndex[dirStackSize]++; - return; - } else { - dirStackIndex[dirStackSize]++; - } - } - } - } - - // The main Obfuscator routine. It calls the iterator for each Java file to - // work on. It then creates the output file, then parses the input Java file - // to determine whether or not it has a main program and also to collect the - // tokens that make up this file. It then calls printOutputFile that takes - // first token and walks the next field chain printing tokens as it goes along. - // Finally a main program is created if necessary. - static public void start() { - boolean parserInitialized = false; - JavaParser parser = null; - Token first; - while (true) { - nextJavaFile(); - if (dirStackSize == 0) { - break; - } - createOutputFile(); - System.out.println("Obfuscating " + dirFile[dirStackSize].getPath()); - System.out.println(" into " + outFile.getPath()); - try { - if (parserInitialized) { - parser.ReInit(new FileInputStream(dirFile[dirStackSize])); - } else { - parser = new JavaParser(new FileInputStream(dirFile[dirStackSize])); - parserInitialized = true; - } - first = parser.CompilationUnit(dirStack[dirStackSize][dirStackIndex[dirStackSize]-1]); - } catch (ParseException e1) { - System.out.println("Parse error in file " + dirFile[dirStackSize].getPath()); - throw new Error(); - } catch (IOException e2) { - System.out.println("Could not open file " + dirFile[dirStackSize].getPath()); - throw new Error(); - } - printOutputFile(first); - if (mainExists) { - createMainClass(); - } - } - } - - static File outFile; - static PrintWriter ostr; - - static void createOutputFile() { - // sets outFile and ostr - outFile = outDir; - for (int i = 1; i < dirStackSize; i++) { - outFile = new File(outFile, map(dirStack[i][dirStackIndex[i]])); - if (outFile.exists()) { - if (!outFile.isDirectory()) { - System.out.println("Unexpected error!"); - throw new Error(); - } - } else { - if (!outFile.mkdir()) { - System.out.println("Could not create directory " + outFile.getPath()); - throw new Error(); - } - } - } - String origFileName = dirStack[dirStackSize][dirStackIndex[dirStackSize]-1]; - String newFileName = map(origFileName.substring(0, origFileName.length() - 5)) + ".java"; - outFile = new File(outFile, newFileName); - try { - ostr = new PrintWriter(new FileWriter(outFile)); - } catch (IOException e) { - System.out.println("Could not create file " + outFile.getPath()); - throw new Error(); - } - } - - static void printOutputFile(Token first) { - Token t = first; - for (int i = 1; i < t.beginColumn; i++) { - ostr.print(" "); - } - while (true) { - if (t.kind == JavaParserConstants.IDENTIFIER) { - t.image = map(t.image); - } - ostr.print(addUnicodeEscapes(t.image)); - if (t.next == null) { - ostr.println(""); - break; - } - if (t.endLine != t.next.beginLine) { - for (int i = t.endLine; i < t.next.beginLine; i++) { - ostr.println(""); - } - for (int i = 1; i < t.next.beginColumn; i++) { - ostr.print(" "); - } - } else { - for (int i = t.endColumn+1; i < t.next.beginColumn; i++) { - ostr.print(" "); - } - } - t = t.next; - } - ostr.close(); - } - - static String addUnicodeEscapes(String str) { - String retval = ""; - char ch; - for (int i = 0; i < str.length(); i++) { - ch = str.charAt(i); - if (ch < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval += "\\u" + s.substring(s.length() - 4, s.length()); - } else { - retval += ch; - } - } - return retval; - } - - // This creates a main program if there was one in the original file. This - // main program has the same name and resides in the same package as the original - // file and it simply calls the obfuscated main program. This allows scripts - // to continue to work. - static void createMainClass() { - PrintWriter mstr; - boolean mustCreate = false; - File mFile = outDir; - for (int i = 1; i < dirStackSize; i++) { - mFile = new File(mFile, dirStack[i][dirStackIndex[i]]); - mustCreate = mustCreate || !map(dirStack[i][dirStackIndex[i]]).equals(dirStack[i][dirStackIndex[i]]); - if (mFile.exists()) { - if (!mFile.isDirectory()) { - System.out.println("Error: Created file " + mFile.getPath() + ", but need to create a main program with the same path prefix. Please remove identifiers from the path prefix from your and run again."); - throw new Error(); - } - } - } - String origFileName = dirStack[dirStackSize][dirStackIndex[dirStackSize]-1]; - String newFileName = map(origFileName.substring(0, origFileName.length() - 5)) + ".java"; - if (!mustCreate && origFileName.equals(newFileName)) { - return; // this main program has not been obfuscated. - } - if (!mFile.exists() && !mFile.mkdirs()) { - System.out.println("Could not create " + mFile.getPath()); - throw new Error(); - } - mFile = new File(mFile, origFileName); - try { - mstr = new PrintWriter(new FileWriter(mFile)); - } catch (IOException e) { - System.out.println("Could not create " + mFile.getPath()); - throw new Error(); - } - System.out.print("Generating main program "); - String pname = ""; - if (dirStackSize > 1) { - for (int i = 1; i < dirStackSize; i++) { - pname += "." + dirStack[i][dirStackIndex[i]]; - } - mstr.println("package " + pname.substring(1) + ";"); - System.out.print(pname.substring(1) + "."); - mstr.println(""); - } - System.out.println(origFileName.substring(0, origFileName.length() - 5)); - mstr.println("public class " + origFileName.substring(0, origFileName.length() - 5) + " {"); - mstr.println(""); - mstr.println(" public static void main(String[] args) {"); - pname = ""; - for (int i = 1; i < dirStackSize; i++) { - pname += map(dirStack[i][dirStackIndex[i]]) + "."; - } - mstr.println(" " + pname + map(origFileName.substring(0, origFileName.length() - 5)) + ".main(args);"); - mstr.println(" }"); - mstr.println(""); - mstr.println("}"); - mstr.close(); - } - -} diff --git a/examples/Obfuscator/src/main/javacc/IdsFile.jj b/examples/Obfuscator/src/main/javacc/IdsFile.jj deleted file mode 100644 index 0fbb04c..0000000 --- a/examples/Obfuscator/src/main/javacc/IdsFile.jj +++ /dev/null @@ -1,195 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -options { - JAVA_UNICODE_ESCAPE = true; - STATIC = false; -} - -PARSER_BEGIN(IdsFile) - -import java.util.*; - -public class IdsFile { -} - -PARSER_END(IdsFile) - -/* - * Following is the only production in this grammar. This describes the grammar - * of the nochangeidsfile and useidsfile, which are simply lists of identifiers. - * The actions here insert these identifiers into the appropriate Hashtable's - * in Globals.java. - */ - -void input(boolean noChangeIds, String fileName) : - { - Token t; - Object obj; - Hashtable symtab = noChangeIds ? Globals.noChangeIds : Globals.useIds; - } -{ - ( - t= - { - if (!noChangeIds) { - // truncate size just to be safe on machines like Macs - if (t.image.length() > 24) { - t.image = t.image.substring(0,24); - } - } - if (!noChangeIds && Globals.mapTargets.get(t.image) != null) { - System.out.println("Warning: Identifier " + t.image + " from already mapped."); - } else { - obj = symtab.put(t.image, ""); - if (obj != null) { - System.out.println("Warning: Multiple occurrence of identifier " + t.image + " in " + fileName); - } else if (noChangeIds) { - Globals.mappings.put(t.image, t.image); - Globals.mapTargets.put(t.image, ""); - } - } - } - )* - -} - -// Lexical specifications follow (copied from the Java 1.1 grammar) - -SKIP : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -SKIP : /* COMMENTS */ -{ - -| -| -} - -TOKEN : /* RESERVED WORDS */ -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} diff --git a/examples/Obfuscator/src/main/javacc/Java1.1.jj b/examples/Obfuscator/src/main/javacc/Java1.1.jj deleted file mode 100644 index f4bbf0b..0000000 --- a/examples/Obfuscator/src/main/javacc/Java1.1.jj +++ /dev/null @@ -1,1108 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -/* - * This modifies the original Java1.1.jj to include actions to determine - * if the file has a main program or not. This information is stored in - * Globals.mainExists and used to decide when to generate main programs. - * The method CompilationUnit returns the first token of the Java program - * using which all tokens can be recovered through the next field. - */ - -options { - JAVA_UNICODE_ESCAPE = true; - STATIC = false; -} - -PARSER_BEGIN(JavaParser) - -import java.util.*; - -public class JavaParser { - static String className, fileName; -} - -PARSER_END(JavaParser) - - -/* WHITE SPACE */ - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -/* COMMENTS */ - -MORE : -{ - "//" : IN_SINGLE_LINE_COMMENT -| - <"/**" ~["/"]> { input_stream.backup(1); } : IN_FORMAL_COMMENT -| - "/*" : IN_MULTI_LINE_COMMENT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -MORE : -{ - < ~[] > -} - -/* RESERVED WORDS AND LITERALS */ - -TOKEN : -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -/* LITERALS */ - -TOKEN : -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -| - < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? (["f","F","d","D"])? - | "." (["0"-"9"])+ ()? (["f","F","d","D"])? - | (["0"-"9"])+ (["f","F","d","D"])? - | (["0"-"9"])+ ()? ["f","F","d","D"] - > -| - < #EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ > -| - < CHARACTER_LITERAL: - "'" - ( (~["'","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - ) - "'" - > -| - < STRING_LITERAL: - "\"" - ( (~["\"","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - )* - "\"" - > -} - -/* IDENTIFIERS */ - -TOKEN : -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} - -/* SEPARATORS */ - -TOKEN : -{ - < LPAREN: "(" > -| < RPAREN: ")" > -| < LBRACE: "{" > -| < RBRACE: "}" > -| < LBRACKET: "[" > -| < RBRACKET: "]" > -| < SEMICOLON: ";" > -| < COMMA: "," > -| < DOT: "." > -} - -/* OPERATORS */ - -TOKEN : -{ - < ASSIGN: "=" > -| < GT: ">" > -| < LT: "<" > -| < BANG: "!" > -| < TILDE: "~" > -| < HOOK: "?" > -| < COLON: ":" > -| < EQ: "==" > -| < LE: "<=" > -| < GE: ">=" > -| < NE: "!=" > -| < SC_OR: "||" > -| < SC_AND: "&&" > -| < INCR: "++" > -| < DECR: "--" > -| < PLUS: "+" > -| < MINUS: "-" > -| < STAR: "*" > -| < SLASH: "/" > -| < BIT_AND: "&" > -| < BIT_OR: "|" > -| < XOR: "^" > -| < REM: "%" > -| < LSHIFT: "<<" > -| < RSIGNEDSHIFT: ">>" > -| < RUNSIGNEDSHIFT: ">>>" > -| < PLUSASSIGN: "+=" > -| < MINUSASSIGN: "-=" > -| < STARASSIGN: "*=" > -| < SLASHASSIGN: "/=" > -| < ANDASSIGN: "&=" > -| < ORASSIGN: "|=" > -| < XORASSIGN: "^=" > -| < REMASSIGN: "%=" > -| < LSHIFTASSIGN: "<<=" > -| < RSIGNEDSHIFTASSIGN: ">>=" > -| < RUNSIGNEDSHIFTASSIGN: ">>>=" > -} - - -/***************************************** - * THE JAVA LANGUAGE GRAMMAR STARTS HERE * - *****************************************/ - -/* - * Program structuring syntax follows. - */ - -Token CompilationUnit(String file) : - { - Token retval = getToken(1); - fileName = file; - Globals.mainExists = false; - } -{ - [ PackageDeclaration() ] - ( ImportDeclaration() )* - ( TypeDeclaration() )* - - { - return retval; - } -} - -void PackageDeclaration() : -{} -{ - "package" Name() ";" -} - -void ImportDeclaration() : -{} -{ - "import" Name() [ "." "*" ] ";" -} - -void TypeDeclaration() : -{} -{ - LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() -| - InterfaceDeclaration() -| - ";" -} - - -/* - * Declaration syntax follows. - */ - -void ClassDeclaration() : -{} -{ - ( "abstract" | "final" | "public" )* - UnmodifiedClassDeclaration(true) -} - -void UnmodifiedClassDeclaration(boolean topLevel) : - { - Token t; - String backupOfClassName = ""; - } -{ - "class" t= [ "extends" Name() ] [ "implements" NameList() ] - { - if (topLevel) { - className = t.image; - } else if (!className.equals("")) { - backupOfClassName = className; - className = ""; - } - } - ClassBody() - { - if (topLevel) { - className = ""; - } else if (!backupOfClassName.equals("")) { - className = backupOfClassName; - } - } -} - -void ClassBody() : -{} -{ - "{" ( ClassBodyDeclaration() )* "}" -} - -void NestedClassDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedClassDeclaration(false) -} - -void ClassBodyDeclaration() : -{} -{ - LOOKAHEAD(2) - Initializer() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( [ "public" | "protected" | "private" ] Name() "(" ) - ConstructorDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -// This production is to determine lookahead only. -void MethodDeclarationLookahead() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() "(" -} - -void InterfaceDeclaration() : -{} -{ - ( "abstract" | "public" )* - UnmodifiedInterfaceDeclaration() -} - -void NestedInterfaceDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedInterfaceDeclaration() -} - -void UnmodifiedInterfaceDeclaration() : -{} -{ - "interface" [ "extends" NameList() ] - "{" ( InterfaceMemberDeclaration() )* "}" -} - -void InterfaceMemberDeclaration() : -{} -{ - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -void FieldDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "final" | "transient" | "volatile" )* - Type() VariableDeclarator() ( "," VariableDeclarator() )* ";" -} - -void VariableDeclarator() : -{} -{ - VariableDeclaratorId() [ "=" VariableInitializer() ] -} - -void VariableDeclaratorId() : -{} -{ - ( "[" "]" )* -} - -void VariableInitializer() : -{} -{ - ArrayInitializer() -| - Expression() -} - -void ArrayInitializer() : -{} -{ - "{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}" -} - -void MethodDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() MethodDeclarator() [ "throws" NameList() ] - ( Block() | ";" ) -} - -void MethodDeclarator() : - { - Token t; - } -{ - t= FormalParameters() ( "[" "]" )* - { - if (fileName.substring(0, fileName.length() - 5).equals(className)) { - if (t.image.equals("main")) { - Globals.mainExists = true; - } - } - } -} - -void FormalParameters() : -{} -{ - "(" [ FormalParameter() ( "," FormalParameter() )* ] ")" -} - -void FormalParameter() : -{} -{ - [ "final" ] Type() VariableDeclaratorId() -} - -void ConstructorDeclaration() : -{} -{ - [ "public" | "protected" | "private" ] - FormalParameters() [ "throws" NameList() ] - "{" - [ LOOKAHEAD(ExplicitConstructorInvocation()) ExplicitConstructorInvocation() ] - ( BlockStatement() )* - "}" -} - -void ExplicitConstructorInvocation() : -{} -{ - LOOKAHEAD("this" Arguments() ";") - "this" Arguments() ";" -| - [ LOOKAHEAD(2) PrimaryExpression() "." ] "super" Arguments() ";" -} - -void Initializer() : -{} -{ - [ "static" ] Block() -} - - -/* - * Type, name and expression syntax follows. - */ - -void Type() : -{} -{ - ( PrimitiveType() | Name() ) ( "[" "]" )* -} - -void PrimitiveType() : -{} -{ - "boolean" -| - "char" -| - "byte" -| - "short" -| - "int" -| - "long" -| - "float" -| - "double" -} - -void ResultType() : -{} -{ - "void" -| - Type() -} - -void Name() : -/* - * A lookahead of 2 is required below since "Name" can be followed - * by a ".*" when used in the context of an "ImportDeclaration". - */ -{} -{ - - ( LOOKAHEAD(2) "." - )* -} - -void NameList() : -{} -{ - Name() - ( "," Name() - )* -} - - -/* - * Expression syntax follows. - */ - -void Expression() : -/* - * This expansion has been written this way instead of: - * Assignment() | ConditionalExpression() - * for performance reasons. - * However, it is a weakening of the grammar for it allows the LHS of - * assignments to be any conditional expression whereas it can only be - * a primary expression. Consider adding a semantic predicate to work - * around this. - */ -{} -{ - ConditionalExpression() - [ - AssignmentOperator() Expression() - ] -} - -void AssignmentOperator() : -{} -{ - "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | ">>>=" | "&=" | "^=" | "|=" -} - -void ConditionalExpression() : -{} -{ - ConditionalOrExpression() [ "?" Expression() ":" ConditionalExpression() ] -} - -void ConditionalOrExpression() : -{} -{ - ConditionalAndExpression() ( "||" ConditionalAndExpression() )* -} - -void ConditionalAndExpression() : -{} -{ - InclusiveOrExpression() ( "&&" InclusiveOrExpression() )* -} - -void InclusiveOrExpression() : -{} -{ - ExclusiveOrExpression() ( "|" ExclusiveOrExpression() )* -} - -void ExclusiveOrExpression() : -{} -{ - AndExpression() ( "^" AndExpression() )* -} - -void AndExpression() : -{} -{ - EqualityExpression() ( "&" EqualityExpression() )* -} - -void EqualityExpression() : -{} -{ - InstanceOfExpression() ( ( "==" | "!=" ) InstanceOfExpression() )* -} - -void InstanceOfExpression() : -{} -{ - RelationalExpression() [ "instanceof" Type() ] -} - -void RelationalExpression() : -{} -{ - ShiftExpression() ( ( "<" | ">" | "<=" | ">=" ) ShiftExpression() )* -} - -void ShiftExpression() : -{} -{ - AdditiveExpression() ( ( "<<" | ">>" | ">>>" ) AdditiveExpression() )* -} - -void AdditiveExpression() : -{} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -void MultiplicativeExpression() : -{} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -void UnaryExpression() : -{} -{ - ( "+" | "-" ) UnaryExpression() -| - PreIncrementExpression() -| - PreDecrementExpression() -| - UnaryExpressionNotPlusMinus() -} - -void PreIncrementExpression() : -{} -{ - "++" PrimaryExpression() -} - -void PreDecrementExpression() : -{} -{ - "--" PrimaryExpression() -} - -void UnaryExpressionNotPlusMinus() : -{} -{ - ( "~" | "!" ) UnaryExpression() -| - LOOKAHEAD( CastLookahead() ) - CastExpression() -| - PostfixExpression() -} - -// This production is to determine lookahead only. The LOOKAHEAD specifications -// below are not used, but they are there just to indicate that we know about -// this. -void CastLookahead() : -{} -{ - LOOKAHEAD(2) - "(" PrimitiveType() -| - LOOKAHEAD("(" Name() "[") - "(" Name() "[" "]" -| - "(" Name() ")" ( "~" | "!" | "(" | | "this" | "super" | "new" | Literal() ) -} - -void PostfixExpression() : -{} -{ - PrimaryExpression() [ "++" | "--" ] -} - -void CastExpression() : -{} -{ - LOOKAHEAD("(" PrimitiveType()) - "(" Type() ")" UnaryExpression() -| - "(" Type() ")" UnaryExpressionNotPlusMinus() -} - -void PrimaryExpression() : -{} -{ - PrimaryPrefix() ( LOOKAHEAD(2) PrimarySuffix() )* -} - -void PrimaryPrefix() : -{} -{ - Literal() -| - "this" -| - "super" "." -| - "(" Expression() ")" -| - AllocationExpression() -| - LOOKAHEAD( ResultType() "." "class" ) - ResultType() "." "class" -| - Name() -} - -void PrimarySuffix() : -{} -{ - LOOKAHEAD(2) - "." "this" -| - LOOKAHEAD(2) - "." AllocationExpression() -| - "[" Expression() "]" -| - "." -| - Arguments() -} - -void Literal() : -{} -{ - -| - -| - -| - -| - BooleanLiteral() -| - NullLiteral() -} - -void BooleanLiteral() : -{} -{ - "true" -| - "false" -} - -void NullLiteral() : -{} -{ - "null" -} - -void Arguments() : -{} -{ - "(" [ ArgumentList() ] ")" -} - -void ArgumentList() : -{} -{ - Expression() ( "," Expression() )* -} - -void AllocationExpression() : -{} -{ - LOOKAHEAD(2) - "new" PrimitiveType() ArrayDimsAndInits() -| - "new" Name() - ( - ArrayDimsAndInits() - | - Arguments() [ ClassBody() ] - ) -} - -/* - * The third LOOKAHEAD specification below is to parse to PrimarySuffix - * if there is an expression between the "[...]". - */ -void ArrayDimsAndInits() : -{} -{ - LOOKAHEAD(2) - ( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )* -| - ( "[" "]" )+ ArrayInitializer() -} - - -/* - * Statement syntax follows. - */ - -void Statement() : -{} -{ - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - EmptyStatement() -| - StatementExpression() ";" -| - SwitchStatement() -| - IfStatement() -| - WhileStatement() -| - DoStatement() -| - ForStatement() -| - BreakStatement() -| - ContinueStatement() -| - ReturnStatement() -| - ThrowStatement() -| - SynchronizedStatement() -| - TryStatement() -} - -void LabeledStatement() : -{} -{ - ":" Statement() -} - -void Block() : -{} -{ - "{" ( BlockStatement() )* "}" -} - -void BlockStatement() : -{} -{ - LOOKAHEAD([ "final" ] Type() ) - LocalVariableDeclaration() ";" -| - Statement() -| - UnmodifiedClassDeclaration(false) -| - UnmodifiedInterfaceDeclaration() -} - -void LocalVariableDeclaration() : -{} -{ - [ "final" ] Type() VariableDeclarator() ( "," VariableDeclarator() )* -} - -void EmptyStatement() : -{} -{ - ";" -} - -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * Java expansions for StatementExpression. This expansion does not - * use PostfixExpression for performance reasons. - */ -{} -{ - PreIncrementExpression() -| - PreDecrementExpression() -| - PrimaryExpression() - [ - "++" - | - "--" - | - AssignmentOperator() Expression() - ] -} - -void SwitchStatement() : -{} -{ - "switch" "(" Expression() ")" "{" - ( SwitchLabel() ( BlockStatement() )* )* - "}" -} - -void SwitchLabel() : -{} -{ - "case" Expression() ":" -| - "default" ":" -} - -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -void DoStatement() : -{} -{ - "do" Statement() "while" "(" Expression() ")" ";" -} - -void ForStatement() : -{} -{ - "for" "(" [ ForInit() ] ";" [ Expression() ] ";" [ ForUpdate() ] ")" Statement() -} - -void ForInit() : -{} -{ - LOOKAHEAD( [ "final" ] Type() ) - LocalVariableDeclaration() -| - StatementExpressionList() -} - -void StatementExpressionList() : -{} -{ - StatementExpression() ( "," StatementExpression() )* -} - -void ForUpdate() : -{} -{ - StatementExpressionList() -} - -void BreakStatement() : -{} -{ - "break" [ ] ";" -} - -void ContinueStatement() : -{} -{ - "continue" [ ] ";" -} - -void ReturnStatement() : -{} -{ - "return" [ Expression() ] ";" -} - -void ThrowStatement() : -{} -{ - "throw" Expression() ";" -} - -void SynchronizedStatement() : -{} -{ - "synchronized" "(" Expression() ")" Block() -} - -void TryStatement() : -/* - * Semantic check required here to make sure that at least one - * finally/catch is present. - */ -{} -{ - "try" Block() - ( "catch" "(" FormalParameter() ")" Block() )* - [ "finally" Block() ] -} diff --git a/examples/Obfuscator/src/main/javacc/MapFile.jj b/examples/Obfuscator/src/main/javacc/MapFile.jj deleted file mode 100644 index 8041b82..0000000 --- a/examples/Obfuscator/src/main/javacc/MapFile.jj +++ /dev/null @@ -1,193 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -options { - JAVA_UNICODE_ESCAPE = true; - STATIC = false; -} - -PARSER_BEGIN(MapFile) - -import java.util.*; - -public class MapFile { -} - -PARSER_END(MapFile) - -/* - * Following is the only production in this grammar. This describes the grammar - * of the mapsfile, which is simply a list of maps from actual identifiers to - * obfuscated identifiers. The actions here insert these mappings into the - * appropriate Hashtable's in Globals.java. - */ - -void input() : - { - Token t1, t2; - } -{ - ( - t1= "->" t2= ";" - { - if (Globals.mappings.get(t1.image) != null) { - if (!t1.image.equals(t2.image)) { - System.out.println("Warning: Map specification of " + t1.image + " to " + t2.image + " overrides entry in ."); - } - } - // truncate size just to be safe on machines like Macs - if (t2.image.length() > 24) { - t2.image = t2.image.substring(0,24); - } - Globals.mappings.put(t1.image, t2.image); - Globals.mapTargets.put(t2.image, ""); - if (t2.image.length() > 2 && t2.image.substring(0,2).equals("O0")) { - int i = Integer.parseInt(t2.image.substring(2)); - if (i > Globals.counter) { - Globals.counter = i; - } - } - } - )* - -} - -// Lexical specifications follow (copied from the Java 1.1 grammar) - -SKIP : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -SKIP : /* COMMENTS */ -{ - -| -| -} - -TOKEN : /* RESERVED WORDS */ -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index c6c1158..0000000 --- a/examples/README.md +++ /dev/null @@ -1,5 +0,0 @@ -In this directory lie the legacy examples, with their build and test files, -targeted to explain some aspects of the JavaCC/JJTree grammar; -they are considered as a subset of integration tests. - -Some examples have been ported from Java to C++ and C#, with the goal to be fully equivalent. \ No newline at end of file diff --git a/examples/Simple/README b/examples/Simple/README deleted file mode 100644 index 6741b38..0000000 --- a/examples/Simple/README +++ /dev/null @@ -1,403 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This directory contains five examples to get you started using JavaCC. -Each example is contained in a single grammar file and are listed -below: - - Simple1.jj - Simple2.jj - Simple3.jj - Simple4.jj - NL_Xlator.jj - IdList.jj - -Once you have tried out and understood each of these examples, you -should take a look at more complex examples in other sub-directories -under the examples directory. But even with just these examples, you -should be able to get started on reasonable complex grammars. - ---------------------------------------------------------------------- - -Summary Instructions: - -If you are a parser and lexical analyzer expert and can understand the -examples by just reading them, the following instructions show you how -to get started with javacc. The instructions below are with respect -to Simple1.jj, but you can build any parser using the same set of -commands. - -1. Run javacc on the grammar input file to generate a bunch of Java - files that implement the parser and lexical analyzer (or token - manager): - - javacc Simple1.jj - -2. Now compile the resulting Java programs: - - javac *.java - -3. The parser is now ready to use. To run the parser, type: - - java Simple1 - -The Simple1 parser and others in this directory are designed to take -input from standard input. Simple1 recognizes matching braces -followed by zero or more line terminators and then an end of file. - -Examples of legal strings in this grammar are: - - "{}", "{{{{{}}}}}", etc. - -Examples of illegal strings are: - - "{{{{", "{}{}", "{}}", "{{}{}}", "{ }", "{x}", etc. - -Try typing various different inputs to Simple1. Remember -may be used to indicate the end of file (this is on the UNIX platform). -Here are some sample runs: - - % java Simple1 - {{}} - - % - - % java Simple1 - {x - Lexical error at line 1, column 2. Encountered: "x" - TokenMgrError: Lexical error at line 1, column 2. Encountered: "x" (120), after : "" - at Simple1TokenManager.getNextToken(Simple1TokenManager.java:146) - at Simple1.getToken(Simple1.java:140) - at Simple1.MatchedBraces(Simple1.java:51) - at Simple1.Input(Simple1.java:10) - at Simple1.main(Simple1.java:6) - % - - % java Simple1 - {}} - ParseException: Encountered "}" at line 1, column 3. - Was expecting one of: - - "\n" ... - "\r" ... - - at Simple1.generateParseException(Simple1.java:184) - at Simple1.jj_consume_token(Simple1.java:126) - at Simple1.Input(Simple1.java:32) - at Simple1.main(Simple1.java:6) - % - ---------------------------------------------------------------------- - -DETAILED DESCRIPTION OF Simple1.jj: - -This is a simple JavaCC grammar that recognizes a set of left braces -followed by the same number of right braces and finally followed by -zero or more line terminators and finally an end of file. Examples of -legal strings in this grammar are: - - "{}", "{{{{{}}}}}", etc. - -Examples of illegal strings are: - - "{{{{", "{}{}", "{}}", "{{}{}}", etc. - -This grammar file starts with settings for all the options offered by -JavaCC. In this case the option settings are their default values. -Hence these option settings were really not necessary. One could as -well have completely omitted the options section, or omitted one or -more of the individual option settings. The details of the individual -options is described in the JavaCC documentation in the web pages. - -Following this is a Java compilation unit enclosed between -"PARSER_BEGIN(name)" and "PARSER_END(name)". This compilation unit -can be of arbitrary complexity. The only constraint on this -compilation unit is that it must define a class called "name" - the -same as the arguments to PARSER_BEGIN and PARSER_END. This is the -name that is used as the prefix for the Java files generated by the -parser generator. The parser code that is generated is inserted -immediately before the closing brace of the class called "name". - -In the above example, the class in which the parser is generated -contains a main program. This main program creates an instance of the -parser object (an object of type Simple1) by using a constructor that -takes one argument of type java.io.InputStream ("System.in" in this -case). - -The main program then makes a call to the non-terminal in the grammar -that it would like to parse - "Input" in this case. All non-terminals -have equal status in a JavaCC generated parser, and hence one may -parse with respect to any grammar non-terminal. - -Following this is a list of productions. In this example, there are -two productions, that define the non-terminals "Input" and -"MatchedBraces" respectively. In JavaCC grammars, non-terminals are -written and implemented (by JavaCC) as Java methods. When the -non-terminal is used on the left-hand side of a production, it is -considered to be declared and its syntax follows the Java syntax. On -the right-hand side its use is similar to a method call in Java. - -Each production defines its left-hand side non-terminal followed by a -colon. This is followed by a bunch of declarations and statements -within braces (in both cases in the above example, there are no -declarations and hence this appears as "{}") which are generated as -common declarations and statements into the generated method. This is -then followed by a set of expansions also enclosed within braces. - -Lexical tokens (regular expressions) in a JavaCC input grammar are -either simple strings ("{", "}", "\n", and "\r" in the above example), -or a more complex regular expression. In our example above, there is -one such regular expression "" which is matched by the end of -file. All complex regular expressions are enclosed within angular -brackets. - -The first production above says that the non-terminal "Input" expands -to the non-terminal "MatchedBraces" followed by zero or more line -terminators ("\n" or "\r") and then the end of file. - -The second production above says that the non-terminal "MatchedBraces" -expands to the token "{" followed by an optional nested expansion of -"MatchedBraces" followed by the token "}". Square brackets [...] -in a JavaCC input file indicate that the ... is optional. - -[...] may also be written as (...)?. These two forms are equivalent. -Other structures that may appear in expansions are: - - e1 | e2 | e3 | ... : A choice of e1, e2, e3, etc. - ( e )+ : One or more occurrences of e - ( e )* : Zero or more occurrences of e - -Note that these may be nested within each other, so we can have -something like: - - (( e1 | e2 )* [ e3 ] ) | e4 - -To build this parser, simply run JavaCC on this file and compile the -resulting Java files: - - javacc Simple1.jj - javac *.java - -Now you should be able to run the generated parser. Make sure that -the current directory is in your CLASSPATH and type: - - java Simple1 - -Now type a sequence of matching braces followed by a return and an end -of file (CTRL-D on UNIX machines). If this is a problem on your -machine, you can create a file and pipe it as input to the generated -parser in this manner (piping also does not work on all machines - if -this is a problem, just replace "System.in" in the grammar file with -'new FileInputStream("testfile")' and place your input inside this -file): - - java Simple1 < myfile - -Also try entering illegal sequences such as mismatched braces, spaces, -and carriage returns between braces as well as other characters and -take a look at the error messages produced by the parser. - ---------------------------------------------------------------------- - -DETAILED DESCRIPTION OF Simple2.jj: - -Simple2.jj is a minor modification to Simple1.jj to allow white space -characters to be interspersed among the braces. So then input such -as: - - "{{ }\n}\n\n" - -will now be legal. - -Take a look at Simple2.jj. The first thing you will note is that we -have omitted the options section. This does not change anything since -the options in Simple1.jj were all assigned their default values. - -The other difference between this file and Simple1.jj is that this -file contains a lexical specification - the region that starts with -"SKIP". Within this region are 4 regular expressions - space, tab, -newline, and return. This says that matches of these regular -expressions are to be ignored (and not considered for parsing). Hence -whenever any of these 4 characters are encountered, they are just -thrown away. - -In addition to SKIP, JavaCC has three other lexical specification -regions. These are: - -. TOKEN: This is used to specify lexical tokens (see next example) -. SPECIAL_TOKEN: This is used to specify lexical tokens that are to be - ignored during parsing. In this sense, SPECIAL_TOKEN is - the same as SKIP. However, these tokens can be recovered - within parser actions to be handled appropriately. -. MORE: This specifies a partial token. A complete token is - made up of a sequence of MORE's followed by a TOKEN - or SPECIAL_TOKEN. - -Please take a look at some of the more complex grammars such as the -Java grammars for examples of usage of these lexical specification -regions. - -You may build Simple2 and invoke the generated parser with input from -the keyboard as standard input. - -You can also try generating the parser with the various debug options -turned on and see what the output looks like. To do this type: - - javacc -debug_parser Simple2.jj - javac Simple2*.java - java Simple2 - -Then type: - - javacc -debug_token_manager Simple2.jj - javac Simple2*.java - java Simple2 - -Note that token manager debugging produces a lot of diagnostic -information and it is typically used to look at debug traces a single -token at a time. - ---------------------------------------------------------------------- - -DETAILED DESCRIPTION OF Simple3.jj: - -Simple3.jj is the third and final version of our matching brace -detector. This example illustrates the use of the TOKEN region for -specifying lexical tokens. In this case, "{" and "}" are defined as -tokens and given names LBRACE and RBRACE respectively. These labels -can then be used within angular brackets (as in the example) to refer -to this token. Typically such token specifications are used for -complex tokens such as identifiers and literals. Tokens that are -simple strings are left as is (in the previous examples). - -This example also illustrates the use of actions in the grammar -productions. The actions inserted in this example count the number of -matching braces. Note the use of the declaration region to declare -variables "count" and "nested_count". Also note how the non-terminal -"MatchedBraces" returns its value as a function return value. - ---------------------------------------------------------------------- - -DETAILED DESCRIPTION OF NL_Xlator.jj: - -This example goes into the details of writing regular expressions in -JavaCC grammar files. It also illustrates a slightly more complex set -of actions that translate the expressions described by the grammar -into English. - -The new concept in the above example is the use of more complex -regular expressions. The regular expression: - - < ID: ["a"-"z","A"-"Z","_"] ( ["a"-"z","A"-"Z","_","0"-"9"] )* > - -creates a new regular expression whose name is ID. This can be -referred anywhere else in the grammar simply as . What follows in -square brackets are a set of allowable characters - in this case it is -any of the lower or upper case letters or the underscore. This is -followed by 0 or more occurrences of any of the lower or upper case -letters, digits, or the underscore. - -Other constructs that may appear in regular expressions are: - - ( ... )+ : One or more occurrences of ... - ( ... )? : An optional occurrence of ... (Note that in the case - of lexical tokens, (...)? and [...] are not equivalent) - ( r1 | r2 | ... ) : Any one of r1, r2, ... - -A construct of the form [...] is a pattern that is matched by the -characters specified in ... . These characters can be individual -characters or character ranges. A "~" before this construct is a -pattern that matches any character not specified in ... . Therefore: - - ["a"-"z"] matches all lower case letters - ~[] matches any character - ~["\n","\r"] matches any character except the new line characters - -When a regular expression is used in an expansion, it takes a value of -type "Token". This is generated into the generated parser directory -as "Token.java". In the above example, we have defined a variable of -type "Token" and assigned the value of the regular expression to it. - ---------------------------------------------------------------------- - -DETAILED DESCRIPTION OF IdList.jj: - -This example illustrates an important attribute of the SKIP -specification. The main point to note is that the regular expressions -in the SKIP specification are only ignored *between tokens* and not -*within tokens*. This grammar accepts any sequence of identifiers -with white space in between. - -A legal input for this grammar is: - -"abc xyz123 A B C \t\n aaa" - -This is because any number of the SKIP regular expressions are allowed -in between consecutive 's. However, the following is not a legal -input: - -"xyz 123" - -This is because the space character after "xyz" is in the SKIP -category and therefore causes one token to end and another to begin. -This requires "123" to be a separate token and hence does not match -the grammar. - -If spaces were OK within 's, then all one has to do is to replace -the definition of Id to: - -TOKEN : -{ - < Id: ["a"-"z","A"-"Z"] ( (" ")* ["a"-"z","A"-"Z","0"-"9"] )* > -} - -Note that having a space character within a TOKEN specification does -not mean that the space character cannot be used in the SKIP -specification. All this means is that any space character that -appears in the context where it can be placed within an identifier -will participate in the match for , whereas all other space -characters will be ignored. The details of the matching algorithm are -described in the JavaCC documentation in the web pages. - -As a corollary, one must define as tokens anything within which -characters such as white space characters must not be present. In the -above example, if was defined as a grammar production rather than -a lexical token as shown below this paragraph, then "xyz 123" would -have been recognized as a legitimate (wrongly). - -void Id() : -{} -{ - <["a"-"z","A"-"Z"]> ( <["a"-"z","A"-"Z","0"-"9"]> )* -} - -Note that in the above definition of non-terminal Id, it is made up of -a sequence of single character tokens (note the location of <...>s), -and hence white space is allowed between these characters. - ---------------------------------------------------------------------- diff --git a/examples/Simple/idlist/err b/examples/Simple/idlist/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Simple/idlist/in b/examples/Simple/idlist/in deleted file mode 100644 index 2c94760..0000000 --- a/examples/Simple/idlist/in +++ /dev/null @@ -1,2 +0,0 @@ -abc xyz123 A B C - aaa \ No newline at end of file diff --git a/examples/Simple/idlist/out b/examples/Simple/idlist/out deleted file mode 100644 index 93720f3..0000000 --- a/examples/Simple/idlist/out +++ /dev/null @@ -1,6 +0,0 @@ -abc -xyz123 -A -B -C -aaa diff --git a/examples/Simple/idlist/ref b/examples/Simple/idlist/ref deleted file mode 100644 index 93720f3..0000000 --- a/examples/Simple/idlist/ref +++ /dev/null @@ -1,6 +0,0 @@ -abc -xyz123 -A -B -C -aaa diff --git a/examples/Simple/pom.xml b/examples/Simple/pom.xml deleted file mode 100644 index d058a32..0000000 --- a/examples/Simple/pom.xml +++ /dev/null @@ -1,256 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - simple - jar - - JavaCC Java code generator / examples / Simple - - - - - - org.codehaus.mojo - exec-maven-plugin - - - simple1 - test - - java - - - simple1.Simple1 - - ${project.basedir}/simple1/in - ${project.basedir}/simple1/out - ${project.basedir}/simple1/err - - - - - simple2 - test - - java - - - simple2.Simple2 - - ${project.basedir}/simple2/in - ${project.basedir}/simple2/out - ${project.basedir}/simple2/err - - - - - simple3 - test - - java - - - simple3.Simple3 - - ${project.basedir}/simple3/in - ${project.basedir}/simple3/out - ${project.basedir}/simple3/err - - - - - xlator - test - - java - - - xlator.NL_Xlator - - ${project.basedir}/xlator/in - ${project.basedir}/xlator/out - ${project.basedir}/xlator/err - - - - - idlist - test - - java - - - idlist.IdList - - ${project.basedir}/idlist/in - ${project.basedir}/idlist/out - ${project.basedir}/idlist/err - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - compare-simple1 - test - - run - - - - - - - - - - - - - - - - - compare-simple3 - test - - run - - - - - - - - - - - - - - - - compare-xlator - test - - run - - - - - - - - - - - - - - - - compare-idlist - test - - run - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/Simple/simple1/err b/examples/Simple/simple1/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Simple/simple1/in b/examples/Simple/simple1/in deleted file mode 100644 index 21c7b02..0000000 --- a/examples/Simple/simple1/in +++ /dev/null @@ -1 +0,0 @@ -{{{{{}}}}} \ No newline at end of file diff --git a/examples/Simple/simple1/out b/examples/Simple/simple1/out deleted file mode 100644 index e99f59e..0000000 --- a/examples/Simple/simple1/out +++ /dev/null @@ -1 +0,0 @@ -matched diff --git a/examples/Simple/simple1/ref b/examples/Simple/simple1/ref deleted file mode 100644 index e99f59e..0000000 --- a/examples/Simple/simple1/ref +++ /dev/null @@ -1 +0,0 @@ -matched diff --git a/examples/Simple/simple2/err b/examples/Simple/simple2/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Simple/simple2/in b/examples/Simple/simple2/in deleted file mode 100644 index 241bb29..0000000 --- a/examples/Simple/simple2/in +++ /dev/null @@ -1,2 +0,0 @@ -{{ } -} diff --git a/examples/Simple/simple2/out b/examples/Simple/simple2/out deleted file mode 100644 index 8d8b554..0000000 --- a/examples/Simple/simple2/out +++ /dev/null @@ -1,12 +0,0 @@ -Call: 0: Input-87 (pa) - Call: 2: MatchedBraces-94 (pa) - Consumed token: <5 / "{">, @ 1:1 (in jj_consume_token()) (pa) - Call: 4: MatchedBraces-94 (pa) - Consumed token: <5 / "{">, @ 1:2 (in jj_consume_token()) (pa) - Consumed token: <6 / "}">, @ 1:5 (in jj_consume_token()) (pa) - Return: 4: MatchedBraces-94 (pa) - Consumed token: <6 / "}">, @ 2:1 (in jj_consume_token()) (pa) - Return: 2: MatchedBraces-94 (pa) - Consumed token: <0 / >, @ 2:3 (in jj_consume_token()) (pa) -Return: 0: Input-87 (pa) -matched diff --git a/examples/Simple/simple2/ref b/examples/Simple/simple2/ref deleted file mode 100644 index e813aac..0000000 --- a/examples/Simple/simple2/ref +++ /dev/null @@ -1,12 +0,0 @@ -Call: Input - Call: MatchedBraces - Consumed token: <"{" at line 1 column 1> - Call: MatchedBraces - Consumed token: <"{" at line 1 column 2> - Consumed token: <"}" at line 1 column 5> - Return: MatchedBraces - Consumed token: <"}" at line 2 column 1> - Return: MatchedBraces - Consumed token: < at line 2 column 3> -Return: Input -matched diff --git a/examples/Simple/simple3/err b/examples/Simple/simple3/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Simple/simple3/in b/examples/Simple/simple3/in deleted file mode 100644 index 21c7b02..0000000 --- a/examples/Simple/simple3/in +++ /dev/null @@ -1 +0,0 @@ -{{{{{}}}}} \ No newline at end of file diff --git a/examples/Simple/simple3/out b/examples/Simple/simple3/out deleted file mode 100644 index 75bedbb..0000000 --- a/examples/Simple/simple3/out +++ /dev/null @@ -1,2 +0,0 @@ -The levels of nesting is 5 -matched diff --git a/examples/Simple/simple3/ref b/examples/Simple/simple3/ref deleted file mode 100644 index 75bedbb..0000000 --- a/examples/Simple/simple3/ref +++ /dev/null @@ -1,2 +0,0 @@ -The levels of nesting is 5 -matched diff --git a/examples/Simple/src/main/javacc/IdList.jj b/examples/Simple/src/main/javacc/IdList.jj deleted file mode 100644 index 45dab3a..0000000 --- a/examples/Simple/src/main/javacc/IdList.jj +++ /dev/null @@ -1,91 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -PARSER_BEGIN(IdList) -package idlist; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** ID lister. */ -public class IdList { - - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; input = new FileInputStream(args[0]); - prevOutput = output; output = new PrintStream(args[1]); - prevError = error; error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - IdList parser = new IdList(System.in); - parser.Input(); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(IdList) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -TOKEN : -{ - < Id: ["a"-"z","A"-"Z"] ( ["a"-"z","A"-"Z","0"-"9"] )* > { System.out.println(matchedToken.toString()); } -} - -/** Top level production. */ -void Input() : -{} -{ - ( )+ -} diff --git a/examples/Simple/src/main/javacc/NL_Xlator.jj b/examples/Simple/src/main/javacc/NL_Xlator.jj deleted file mode 100644 index cf62c41..0000000 --- a/examples/Simple/src/main/javacc/NL_Xlator.jj +++ /dev/null @@ -1,195 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -PARSER_BEGIN(NL_Xlator) -package xlator; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** New line translator. */ -public class NL_Xlator { - - /** Main entry point. */ - public static void main(String args[]) throws FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; input = new FileInputStream(args[0]); - prevOutput = output; output = new PrintStream(args[1]); - prevError = error; error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - NL_Xlator parser = new NL_Xlator(System.in); - parser.ExpressionList(); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(NL_Xlator) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -TOKEN : -{ - < ID: ["a"-"z","A"-"Z","_"] ( ["a"-"z","A"-"Z","_","0"-"9"] )* > -| - < NUM: ( ["0"-"9"] )+ > -} - -/** Top level production. */ -void ExpressionList() : -{ - String s; -} -{ - { - System.out.println("Please type in an expression followed by a \";\" or ^D to quit:"); - System.out.println(""); - } - ( s=Expression() ";" - { - System.out.println(s); - System.out.println(""); - System.out.println("Please type in another expression followed by a \";\" or ^D to quit:"); - System.out.println(""); - } - )* - -} - -/** An Expression. */ -String Expression() : -{ - java.util.Vector termimage = new java.util.Vector(); - String s; -} -{ - s=Term() - { - termimage.addElement(s); - } - ( "+" s=Term() - { - termimage.addElement(s); - } - )* - { - if (termimage.size() == 1) { - return (String)termimage.elementAt(0); - } else { - s = "the sum of " + (String)termimage.elementAt(0); - for (int i = 1; i < termimage.size()-1; i++) { - s += ", " + (String)termimage.elementAt(i); - } - if (termimage.size() > 2) { - s += ","; - } - s += " and " + (String)termimage.elementAt(termimage.size()-1); - return s; - } - } -} - -/** A Term. */ -String Term() : -{ - java.util.Vector factorimage = new java.util.Vector(); - String s; -} -{ - s=Factor() - { - factorimage.addElement(s); - } - ( "*" s=Factor() - { - factorimage.addElement(s); - } - )* - { - if (factorimage.size() == 1) { - return (String)factorimage.elementAt(0); - } else { - s = "the product of " + (String)factorimage.elementAt(0); - for (int i = 1; i < factorimage.size()-1; i++) { - s += ", " + (String)factorimage.elementAt(i); - } - if (factorimage.size() > 2) { - s += ","; - } - s += " and " + (String)factorimage.elementAt(factorimage.size()-1); - return s; - } - } -} - -/** A Factor. */ -String Factor() : -{ - Token t; - String s; -} -{ - t= - { - return t.image; - } -| - t= - { - return t.image; - } -| - "(" s=Expression() ")" - { - return s; - } -} diff --git a/examples/Simple/src/main/javacc/Simple1.jj b/examples/Simple/src/main/javacc/Simple1.jj deleted file mode 100644 index e93a239..0000000 --- a/examples/Simple/src/main/javacc/Simple1.jj +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - LOOKAHEAD = 1; - CHOICE_AMBIGUITY_CHECK = 2; - OTHER_AMBIGUITY_CHECK = 1; - STATIC = true; - DEBUG_PARSER = false; - DEBUG_LOOKAHEAD = false; - DEBUG_TOKEN_MANAGER = false; - ERROR_REPORTING = true; - JAVA_UNICODE_ESCAPE = false; - UNICODE_INPUT = false; - IGNORE_CASE = false; - USER_TOKEN_MANAGER = false; - USER_CHAR_STREAM = false; - BUILD_PARSER = true; - BUILD_TOKEN_MANAGER = true; - SANITY_CHECK = true; - FORCE_LA_CHECK = false; -} - -PARSER_BEGIN(Simple1) -package simple1; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - - -/** Simple brace matcher. */ -public class Simple1 { - - /** Main entry point. */ - public static void main(String args[]) throws ParseException, FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; - input = new FileInputStream(args[0]); - prevOutput = output; - output = new PrintStream(args[1]); - prevError = error; - error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - Simple1 parser = new Simple1(input); - parser.Input(); - output.println("matched"); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(Simple1) - -/** Root production. */ -void Input() : -{} -{ - MatchedBraces() ("\n"|"\r")* -} - -/** Brace matching production. */ -void MatchedBraces() : -{} -{ - "{" [ MatchedBraces() ] "}" -} diff --git a/examples/Simple/src/main/javacc/Simple2.jj b/examples/Simple/src/main/javacc/Simple2.jj deleted file mode 100644 index 9735451..0000000 --- a/examples/Simple/src/main/javacc/Simple2.jj +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - options { - DEBUG_PARSER=true; - } - -PARSER_BEGIN(Simple2) -package simple2; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - - -/** Simple brace matcher. */ -public class Simple2 { - - /** Main entry point. */ - public static void main(String args[]) throws ParseException, FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; input = new FileInputStream(args[0]); - prevOutput = output; output = new PrintStream(args[1]); - prevError = error; error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - Simple2 parser = new Simple2(input); - parser.Input(); - output.println("matched"); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(Simple2) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -/** Root production. */ -void Input() : -{} -{ - MatchedBraces() -} - -/** Brace matching production. */ -void MatchedBraces() : -{} -{ - "{" [ MatchedBraces() ] "}" -} diff --git a/examples/Simple/src/main/javacc/Simple3.jj b/examples/Simple/src/main/javacc/Simple3.jj deleted file mode 100644 index 99654b2..0000000 --- a/examples/Simple/src/main/javacc/Simple3.jj +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -PARSER_BEGIN(Simple3) -package simple3; - - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -/** Simple brace matcher. */ -public class Simple3 { - - /** Main entry point. */ - public static void main(String args[]) throws ParseException, FileNotFoundException { - InputStream input = System.in; - PrintStream output = System.out; - PrintStream error = System.err; - InputStream prevInput = null; - PrintStream prevOutput = null; - PrintStream prevError = null; - if (args.length == 3) { - prevInput = input; input = new FileInputStream(args[0]); - prevOutput = output; output = new PrintStream(args[1]); - prevError = error; error = new PrintStream(args[2]); - System.setIn(input); - System.setOut(output); - System.setErr(error); - } - try { - Simple3 parser = new Simple3(System.in); - parser.Input(); - output.println("matched"); - } catch (Exception e) { - error.println(e.getMessage()); - } finally { - if (prevInput != null) System.setIn(prevInput); - if (prevOutput != null) System.setOut(prevOutput); - if (prevError != null) System.setErr(prevError); - } - } - -} - -PARSER_END(Simple3) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -TOKEN : -{ - -| -} - -/** Root production. */ -void Input() : -{ int count; } -{ - count=MatchedBraces() - { System.out.println("The levels of nesting is " + count); } -} - -/** Brace counting production. */ -int MatchedBraces() : -{ int nested_count=0; } -{ - [ nested_count=MatchedBraces() ] - { return ++nested_count; } -} diff --git a/examples/Simple/xlator/err b/examples/Simple/xlator/err deleted file mode 100644 index e69de29..0000000 diff --git a/examples/Simple/xlator/in b/examples/Simple/xlator/in deleted file mode 100644 index f0dae33..0000000 --- a/examples/Simple/xlator/in +++ /dev/null @@ -1 +0,0 @@ -AbCDE; diff --git a/examples/Simple/xlator/out b/examples/Simple/xlator/out deleted file mode 100644 index 3d4f20b..0000000 --- a/examples/Simple/xlator/out +++ /dev/null @@ -1,6 +0,0 @@ -Please type in an expression followed by a ";" or ^D to quit: - -AbCDE - -Please type in another expression followed by a ";" or ^D to quit: - diff --git a/examples/Simple/xlator/ref b/examples/Simple/xlator/ref deleted file mode 100644 index 3d4f20b..0000000 --- a/examples/Simple/xlator/ref +++ /dev/null @@ -1,6 +0,0 @@ -Please type in an expression followed by a ";" or ^D to quit: - -AbCDE - -Please type in another expression followed by a ";" or ^D to quit: - diff --git a/examples/Transformer/README b/examples/Transformer/README deleted file mode 100644 index 87b1082..0000000 --- a/examples/Transformer/README +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -The example in this directory takes an extension of Java as input and -converts it into proper Java. The purpose of this example is to -illustrate: - -1. The use of the "next" field of tokens. - -2. To illustrate how one can use JJTree to build a parse tree for a - small part of the input and ignore the rest of the file. - -3. Combine 1 and 2 to process the portion for which tree nodes are - created and leave the rest of the file unchanged. - -The Java language extension handled by the grammar (ToyJava.jjt) -allows catch and finally specifications at the end of method blocks. -So the following is allowed (as an example): - - void foo() { - ... - } catch (Exception e) { - ... - } - -The grammar file ToyJava.jjt is a modification of Java1.1.jj. Note -how we have changed the SKIP tokens to SPECIAL_TOKENS so that the -output file is identical to the input file. - -To try this out, type: - - jjtree ToyJava.jjt - javacc ToyJava.jj - javac *.java - java ToyParser divide.toy divide.java - -And then compare divide.java to divide.toy. diff --git a/examples/Transformer/divide.in b/examples/Transformer/divide.in deleted file mode 100644 index 0796d1b..0000000 --- a/examples/Transformer/divide.in +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -class Test { - - int divide(int x, int y) { - return x/y; - } catch (ArithmeticException e) { - return Integer.MAX_VALUE; - } - -} diff --git a/examples/Transformer/divide.out b/examples/Transformer/divide.out deleted file mode 100644 index ebab03e..0000000 --- a/examples/Transformer/divide.out +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -class Test { - - int divide(int x, int y) { try { - return x/y; - } catch (ArithmeticException e) { - return Integer.MAX_VALUE; - } } - -} diff --git a/examples/Transformer/divide.ref b/examples/Transformer/divide.ref deleted file mode 100644 index ebab03e..0000000 --- a/examples/Transformer/divide.ref +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -class Test { - - int divide(int x, int y) { try { - return x/y; - } catch (ArithmeticException e) { - return Integer.MAX_VALUE; - } } - -} diff --git a/examples/Transformer/pom.xml b/examples/Transformer/pom.xml deleted file mode 100644 index 968429a..0000000 --- a/examples/Transformer/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - transformer - jar - - JavaCC Java code generator / examples / Transformer - - - - - - org.codehaus.mojo - exec-maven-plugin - - - divide - test - - java - - - ToyParser - - ${project.basedir}/divide.in - ${project.basedir}/divide.out - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - compare-divide - test - - run - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/examples/Transformer/src/main/java/ASTCompilationUnit.java b/examples/Transformer/src/main/java/ASTCompilationUnit.java deleted file mode 100644 index 492d11d..0000000 --- a/examples/Transformer/src/main/java/ASTCompilationUnit.java +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -/* JJT: 0.2.2 */ - -import java.io.*; - -public class ASTCompilationUnit extends Node { - ASTCompilationUnit(int id) { - super(id); - } - - -// Manually inserted code begins here - - public void process (PrintWriter ostr) { - Token t = begin; - ASTSpecialBlock bnode; - for (int i = 0; i < jjtGetNumChildren(); i++) { - bnode = (ASTSpecialBlock)jjtGetChild(i); - do { - print(t, ostr); - t = t.next; - } while (t != bnode.begin); - bnode.process(ostr); - t = bnode.end.next; - } - while (t != null) { - print(t, ostr); - t = t.next; - } - } - -} diff --git a/examples/Transformer/src/main/java/ASTSpecialBlock.java b/examples/Transformer/src/main/java/ASTSpecialBlock.java deleted file mode 100644 index b0c26dd..0000000 --- a/examples/Transformer/src/main/java/ASTSpecialBlock.java +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -/* JJT: 0.2.2 */ - -import java.io.*; - -public class ASTSpecialBlock extends Node { - ASTSpecialBlock(int id) { - super(id); - } - - -// Manually inserted code begins here - - public void process (PrintWriter ostr) { - Token t = begin; // t corresponds to the "{" of the special block. - t.image = "{ try {"; - while (t != end) { - print(t, ostr); - t = t.next; - } - // t now corresponds to the last "}" of the special block. - t.image = "} }"; - print(t, ostr); - } - -} diff --git a/examples/Transformer/src/main/java/Node.java b/examples/Transformer/src/main/java/Node.java deleted file mode 100644 index 800f51f..0000000 --- a/examples/Transformer/src/main/java/Node.java +++ /dev/null @@ -1,154 +0,0 @@ -import java.io.PrintWriter; - -/* Generated By:JavaCC: Do not edit this line. SimpleNode.java Version 8.0.0 */ -public class Node implements Tree { - - protected Node parent; - protected Node[] children; - protected int id; - protected Object value; - protected ToyParser parser; - - public Node(int i) { - id = i; - } - - public Node(ToyParser p, int i) { - this(i); - parser = p; - } - - @Override - public void jjtOpen() {} - - @Override - public void jjtClose() {} - - @Override - public void jjtSetParent(Node n) { - parent = n; - } - - @Override - public Node jjtGetParent() { - return parent; - } - - @Override - public void jjtAddChild(Node n, int i) { - if (children == null) { - children = new Node[i + 1]; - } else if (i >= children.length) { - Node[] c = new Node[i + 1]; - System.arraycopy(children, 0, c, 0, children.length); - children = c; - } - children[i] = n; - } - - @Override - public Node jjtGetChild(int i) { - return children[i]; - } - - @Override - public Node[] jjtGetChildren() { - return children; - } - - @Override - public int jjtGetNumChildren() { - return (children == null) ? 0 : children.length; - } - - public void jjtSetValue(Object value) { - this.value = value; - } - - public Object jjtGetValue() { - return value; - } - - public String toString() { - return ToyParserTreeConstants.jjtNodeName[id]; - } - - public String toString(String prefix) { - return prefix + toString(); - } - - /* - * Override this method if you want to customize how the node dumps out its - * children. - */ - - public void dump(String prefix) { - System.out.println(toString(prefix)); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - Node n = (Node) children[i]; - if (n != null) { - n.dump(prefix + " "); - } - } - } - } - - @Override - public int getId() { - return id; - } - // Manually inserted code begins here - - public Token begin; - public Token end; - - public void setFirstToken(Token t) { - begin = t; - } - - public void setLastToken(Token t) { - end = t; - } - - public void process(PrintWriter ostr) { - System.out.println("Error - this should not be called"); - throw new Error(); - } - - // The following method prints token t, as well as all preceding - // special tokens (essentially, white space and comments). - - protected void print(Token t, PrintWriter ostr) { - Token tt = t.specialToken; - if (tt != null) { - while (tt.specialToken != null) - tt = tt.specialToken; - while (tt != null) { - ostr.print(addUnicodeEscapes(tt.image)); - tt = tt.next; - } - } - ostr.print(addUnicodeEscapes(t.image)); - } - - private String addUnicodeEscapes(String str) { - String retval = ""; - char ch; - for (int i = 0; i < str.length(); i++) { - ch = str.charAt(i); - if ((ch < 0x20 || ch > 0x7e) && ch != '\t' && ch != '\n' && ch != '\r' && ch != '\f') { - String s = "0000" + Integer.toString(ch, 16); - retval += "\\u" + s.substring(s.length() - 4, s.length()); - } else { - retval += ch; - } - } - return retval; - } -} - -/* - * JavaCC - OriginalChecksum=ead71c6a9048255593cc597892617232 (do not edit this - * line) - */ diff --git a/examples/Transformer/src/main/jjtree/ToyJava.jjt b/examples/Transformer/src/main/jjtree/ToyJava.jjt deleted file mode 100644 index fb80276..0000000 --- a/examples/Transformer/src/main/jjtree/ToyJava.jjt +++ /dev/null @@ -1,1076 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI = true; - NODE_DEFAULT_VOID = true; - JAVA_UNICODE_ESCAPE = true; -} - -PARSER_BEGIN(ToyParser) - -import java.io.*; - -public class ToyParser { - - public static void main(String args[]) throws Exception { - ToyParser parser; - ASTCompilationUnit node; - if (args.length == 2) { - System.out.println("Toy Preprocessor: Reading from file " + args[0] + " . . ."); - try { - parser = new ToyParser(new FileInputStream(args[0])); - } catch (FileNotFoundException e) { - System.out.println("Toy Preprocessor: File " + args[0] + " not found."); - return; - } - } else { - System.out.println("Toy Preprocessor: Usage is \"java ToyParser inputfile outputfile\""); - return; - } - try { - node = parser.CompilationUnit(); - PrintWriter ostr = new PrintWriter(new FileWriter(args[1])); - node.process(ostr); - ostr.close(); - System.out.println("Toy Preprocessor: Transformation completed successfully."); - } catch (ParseException e) { - System.out.println("Toy Preprocessor: Encountered errors during parse."); - } catch (IOException e) { - System.out.println("Toy Preprocessor: Could not create file " + args[1]); - } - } - -} - -PARSER_END(ToyParser) - - -SPECIAL_TOKEN : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -SPECIAL_TOKEN : /* COMMENTS */ -{ - -| -| -} - -TOKEN : /* RESERVED WORDS AND LITERALS */ -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -TOKEN : /* LITERALS */ -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -| - < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? (["f","F","d","D"])? - | "." (["0"-"9"])+ ()? (["f","F","d","D"])? - | (["0"-"9"])+ (["f","F","d","D"])? - | (["0"-"9"])+ ()? ["f","F","d","D"] - > -| - < #EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ > -| - < CHARACTER_LITERAL: - "'" - ( (~["'","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - ) - "'" - > -| - < STRING_LITERAL: - "\"" - ( (~["\"","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - )* - "\"" - > -} - -TOKEN : /* IDENTIFIERS */ -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} - -TOKEN : /* SEPARATORS */ -{ - < LPAREN: "(" > -| < RPAREN: ")" > -| < LBRACE: "{" > -| < RBRACE: "}" > -| < LBRACKET: "[" > -| < RBRACKET: "]" > -| < SEMICOLON: ";" > -| < COMMA: "," > -| < DOT: "." > -} - -TOKEN : /* OPERATORS */ -{ - < ASSIGN: "=" > -| < GT: ">" > -| < LT: "<" > -| < BANG: "!" > -| < TILDE: "~" > -| < HOOK: "?" > -| < COLON: ":" > -| < EQ: "==" > -| < LE: "<=" > -| < GE: ">=" > -| < NE: "!=" > -| < SC_OR: "||" > -| < SC_AND: "&&" > -| < INCR: "++" > -| < DECR: "--" > -| < PLUS: "+" > -| < MINUS: "-" > -| < STAR: "*" > -| < SLASH: "/" > -| < BIT_AND: "&" > -| < BIT_OR: "|" > -| < XOR: "^" > -| < REM: "%" > -| < LSHIFT: "<<" > -| < RSIGNEDSHIFT: ">>" > -| < RUNSIGNEDSHIFT: ">>>" > -| < PLUSASSIGN: "+=" > -| < MINUSASSIGN: "-=" > -| < STARASSIGN: "*=" > -| < SLASHASSIGN: "/=" > -| < ANDASSIGN: "&=" > -| < ORASSIGN: "|=" > -| < XORASSIGN: "^=" > -| < REMASSIGN: "%=" > -| < LSHIFTASSIGN: "<<=" > -| < RSIGNEDSHIFTASSIGN: ">>=" > -| < RUNSIGNEDSHIFTASSIGN: ">>>=" > -} - - -/***************************************** - * THE JAVA LANGUAGE GRAMMAR STARTS HERE * - *****************************************/ - -/* - * Program structuring syntax follows. - */ - -ASTCompilationUnit CompilationUnit() #CompilationUnit : -{} -{ - { - jjtThis.setFirstToken(getToken(1)); - } - [ PackageDeclaration() ] - ( ImportDeclaration() )* - ( TypeDeclaration() )* - - { - return jjtThis; - } -} - -void PackageDeclaration() : -{} -{ - "package" Name() ";" -} - -void ImportDeclaration() : -{} -{ - "import" Name() [ "." "*" ] ";" -} - -void TypeDeclaration() : -{} -{ - LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() -| - InterfaceDeclaration() -| - ";" -} - - -/* - * Declaration syntax follows. - */ - -void ClassDeclaration() : -{} -{ - ( "abstract" | "final" | "public" )* - UnmodifiedClassDeclaration() -} - -void UnmodifiedClassDeclaration() : -{} -{ - "class" [ "extends" Name() ] [ "implements" NameList() ] - ClassBody() -} - -void ClassBody() : -{} -{ - "{" ( ClassBodyDeclaration() )* "}" -} - -void NestedClassDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedClassDeclaration() -} - -void ClassBodyDeclaration() : -{} -{ - LOOKAHEAD(2) - Initializer() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( [ "public" | "protected" | "private" ] Name() "(" ) - ConstructorDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -// This production is to determine lookahead only. -void MethodDeclarationLookahead() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() "(" -} - -void InterfaceDeclaration() : -{} -{ - ( "abstract" | "public" )* - UnmodifiedInterfaceDeclaration() -} - -void NestedInterfaceDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedInterfaceDeclaration() -} - -void UnmodifiedInterfaceDeclaration() : -{} -{ - "interface" [ "extends" NameList() ] - "{" ( InterfaceMemberDeclaration() )* "}" -} - -void InterfaceMemberDeclaration() : -{} -{ - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -void FieldDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "final" | "transient" | "volatile" )* - Type() VariableDeclarator() ( "," VariableDeclarator() )* ";" -} - -void VariableDeclarator() : -{} -{ - VariableDeclaratorId() [ "=" VariableInitializer() ] -} - -void VariableDeclaratorId() : -{} -{ - ( "[" "]" )* -} - -void VariableInitializer() : -{} -{ - ArrayInitializer() -| - Expression() -} - -void ArrayInitializer() : -{} -{ - "{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}" -} - -void MethodDeclaration() : - { - Token t; - } -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() MethodDeclarator() [ "throws" NameList() ] - ( - { - t = getToken(1); - } - Block() - [ - ( - ( - ( "catch" "(" FormalParameter() ")" Block() )+ - [ "finally" Block() ] - | - "finally" Block() - ) - { - jjtThis.setFirstToken(t); - jjtThis.setLastToken(getToken(0)); - } - ) #SpecialBlock - ] - | - ";" - ) -} - -void MethodDeclarator() : -{} -{ - FormalParameters() ( "[" "]" )* -} - -void FormalParameters() : -{} -{ - "(" [ FormalParameter() ( "," FormalParameter() )* ] ")" -} - -void FormalParameter() : -{} -{ - [ "final" ] Type() VariableDeclaratorId() -} - -void ConstructorDeclaration() : -{} -{ - [ "public" | "protected" | "private" ] - FormalParameters() [ "throws" NameList() ] - "{" - [ LOOKAHEAD(ExplicitConstructorInvocation()) ExplicitConstructorInvocation() ] - ( BlockStatement() )* - "}" -} - -void ExplicitConstructorInvocation() : -{} -{ - LOOKAHEAD("this" Arguments() ";") - "this" Arguments() ";" -| - [ LOOKAHEAD(2) PrimaryExpression() "." ] "super" Arguments() ";" -} - -void Initializer() : -{} -{ - [ "static" ] Block() -} - - -/* - * Type, name and expression syntax follows. - */ - -void Type() : -{} -{ - ( PrimitiveType() | Name() ) ( "[" "]" )* -} - -void PrimitiveType() : -{} -{ - "boolean" -| - "char" -| - "byte" -| - "short" -| - "int" -| - "long" -| - "float" -| - "double" -} - -void ResultType() : -{} -{ - "void" -| - Type() -} - -void Name() : -/* - * A lookahead of 2 is required below since "Name" can be followed - * by a ".*" when used in the context of an "ImportDeclaration". - */ -{} -{ - - ( LOOKAHEAD(2) "." - )* -} - -void NameList() : -{} -{ - Name() - ( "," Name() - )* -} - - -/* - * Expression syntax follows. - */ - -void Expression() : -{} -{ - LOOKAHEAD( PrimaryExpression() AssignmentOperator() ) - Assignment() -| - ConditionalExpression() -} - -void Assignment() : -{} -{ - PrimaryExpression() AssignmentOperator() Expression() -} - -void AssignmentOperator() : -{} -{ - "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | ">>>=" | "&=" | "^=" | "|=" -} - -void ConditionalExpression() : -{} -{ - ConditionalOrExpression() [ "?" Expression() ":" ConditionalExpression() ] -} - -void ConditionalOrExpression() : -{} -{ - ConditionalAndExpression() ( "||" ConditionalAndExpression() )* -} - -void ConditionalAndExpression() : -{} -{ - InclusiveOrExpression() ( "&&" InclusiveOrExpression() )* -} - -void InclusiveOrExpression() : -{} -{ - ExclusiveOrExpression() ( "|" ExclusiveOrExpression() )* -} - -void ExclusiveOrExpression() : -{} -{ - AndExpression() ( "^" AndExpression() )* -} - -void AndExpression() : -{} -{ - EqualityExpression() ( "&" EqualityExpression() )* -} - -void EqualityExpression() : -{} -{ - InstanceOfExpression() ( ( "==" | "!=" ) InstanceOfExpression() )* -} - -void InstanceOfExpression() : -{} -{ - RelationalExpression() [ "instanceof" Type() ] -} - -void RelationalExpression() : -{} -{ - ShiftExpression() ( ( "<" | ">" | "<=" | ">=" ) ShiftExpression() )* -} - -void ShiftExpression() : -{} -{ - AdditiveExpression() ( ( "<<" | ">>" | ">>>" ) AdditiveExpression() )* -} - -void AdditiveExpression() : -{} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -void MultiplicativeExpression() : -{} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -void UnaryExpression() : -{} -{ - ( "+" | "-" ) UnaryExpression() -| - PreIncrementExpression() -| - PreDecrementExpression() -| - UnaryExpressionNotPlusMinus() -} - -void PreIncrementExpression() : -{} -{ - "++" PrimaryExpression() -} - -void PreDecrementExpression() : -{} -{ - "--" PrimaryExpression() -} - -void UnaryExpressionNotPlusMinus() : -{} -{ - ( "~" | "!" ) UnaryExpression() -| - LOOKAHEAD( CastLookahead() ) - CastExpression() -| - PostfixExpression() -} - -// This production is to determine lookahead only. The LOOKAHEAD specifications -// below are not used, but they are there just to indicate that we know about -// this. -void CastLookahead() : -{} -{ - LOOKAHEAD(2) - "(" PrimitiveType() -| - LOOKAHEAD("(" Name() "[") - "(" Name() "[" "]" -| - "(" Name() ")" ( "~" | "!" | "(" | | "this" | "super" | "new" | Literal() ) -} - -void PostfixExpression() : -{} -{ - PrimaryExpression() [ "++" | "--" ] -} - -void CastExpression() : -{} -{ - LOOKAHEAD("(" PrimitiveType()) - "(" Type() ")" UnaryExpression() -| - LOOKAHEAD("(" Name()) - "(" Type() ")" UnaryExpressionNotPlusMinus() -} - -void PrimaryExpression() : -{} -{ - PrimaryPrefix() ( LOOKAHEAD(2) PrimarySuffix() )* -} - -void PrimaryPrefix() : -{} -{ - Literal() -| - Name() -| - "this" -| - "super" "." -| - "(" Expression() ")" -| - AllocationExpression() -} - -void PrimarySuffix() : -{} -{ - LOOKAHEAD(2) - "." "this" -| - LOOKAHEAD(2) - "." "class" -| - LOOKAHEAD(2) - "." AllocationExpression() -| - "[" Expression() "]" -| - "." -| - Arguments() -} - -void Literal() : -{} -{ - -| - -| - -| - -| - BooleanLiteral() -| - NullLiteral() -} - -void BooleanLiteral() : -{} -{ - "true" -| - "false" -} - -void NullLiteral() : -{} -{ - "null" -} - -void Arguments() : -{} -{ - "(" [ ArgumentList() ] ")" -} - -void ArgumentList() : -{} -{ - Expression() ( "," Expression() )* -} - -void AllocationExpression() : -{} -{ - LOOKAHEAD(2) - "new" PrimitiveType() ArrayDimensions() [ ArrayInitializer() ] -| - "new" Name() - ( - ArrayDimensions() [ ArrayInitializer() ] - | - Arguments() [ ClassBody() ] - ) -} - -/* - * The second LOOKAHEAD specification below is to parse to PrimarySuffix - * if there is an expression between the "[...]". - */ -void ArrayDimensions() : -{} -{ - ( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )* -} - - -/* - * Statement syntax follows. - */ - -void Statement() : -{} -{ - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - EmptyStatement() -| - StatementExpression() ";" -| - SwitchStatement() -| - IfStatement() -| - WhileStatement() -| - DoStatement() -| - ForStatement() -| - BreakStatement() -| - ContinueStatement() -| - ReturnStatement() -| - ThrowStatement() -| - SynchronizedStatement() -| - TryStatement() -} - -void LabeledStatement() : -{} -{ - ":" Statement() -} - -void Block() : -{} -{ - "{" ( BlockStatement() )* "}" -} - -void BlockStatement() : -{} -{ - LOOKAHEAD([ "final" ] Type() ) - LocalVariableDeclaration() ";" -| - Statement() -| - UnmodifiedClassDeclaration() -| - UnmodifiedInterfaceDeclaration() -} - -void LocalVariableDeclaration() : -{} -{ - [ "final" ] Type() VariableDeclarator() ( "," VariableDeclarator() )* -} - -void EmptyStatement() : -{} -{ - ";" -} - -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * Java expansions for StatementExpression. - */ -{} -{ - PreIncrementExpression() -| - PreDecrementExpression() -| - LOOKAHEAD( PrimaryExpression() AssignmentOperator() ) - Assignment() -| - PostfixExpression() -} - -void SwitchStatement() : -{} -{ - "switch" "(" Expression() ")" "{" - ( SwitchLabel() ( BlockStatement() )* )* - "}" -} - -void SwitchLabel() : -{} -{ - "case" Expression() ":" -| - "default" ":" -} - -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -void DoStatement() : -{} -{ - "do" Statement() "while" "(" Expression() ")" ";" -} - -void ForStatement() : -{} -{ - "for" "(" [ ForInit() ] ";" [ Expression() ] ";" [ ForUpdate() ] ")" Statement() -} - -void ForInit() : -{} -{ - LOOKAHEAD( [ "final" ] Type() ) - LocalVariableDeclaration() -| - StatementExpressionList() -} - -void StatementExpressionList() : -{} -{ - StatementExpression() ( "," StatementExpression() )* -} - -void ForUpdate() : -{} -{ - StatementExpressionList() -} - -void BreakStatement() : -{} -{ - "break" [ ] ";" -} - -void ContinueStatement() : -{} -{ - "continue" [ ] ";" -} - -void ReturnStatement() : -{} -{ - "return" [ Expression() ] ";" -} - -void ThrowStatement() : -{} -{ - "throw" Expression() ";" -} - -void SynchronizedStatement() : -{} -{ - "synchronized" "(" Expression() ")" Block() -} - -void TryStatement() : -/* - * Semantic check required here to make sure that at least one - * finally/catch is present. - */ -{} -{ - "try" Block() - ( "catch" "(" FormalParameter() ")" Block() )* - [ "finally" Block() ] -} diff --git a/examples/VTransformer/Main.err b/examples/VTransformer/Main.err deleted file mode 100644 index d8abe74..0000000 --- a/examples/VTransformer/Main.err +++ /dev/null @@ -1 +0,0 @@ -Thank you. diff --git a/examples/VTransformer/Main.in b/examples/VTransformer/Main.in deleted file mode 100644 index 8df49d9..0000000 --- a/examples/VTransformer/Main.in +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -package VTransformer; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -public class Main -{ - public static void main(String args[]) throws FileNotFoundException { - InputStream is = System.in; - PrintStream os = System.out; - PrintStream es = System.err; - if (args != null) { - if (args.length == 3) { - is = new FileInputStream(args[0]); - os = new PrintStream(args[1]); - es = new PrintStream(args[2]); - } - } - System.err.println("Reading from standard input..."); - JavaParser p = new JavaParser(is); - try { - ASTCompilationUnit cu = p.CompilationUnit(); - JavaParserVisitor visitor = new AddAcceptVisitor(os); - cu.jjtAccept(visitor, null); - es.println("Thank you."); - } catch (Exception e) { - es.println("Oops."); - es.println(e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/examples/VTransformer/Main.out b/examples/VTransformer/Main.out deleted file mode 100644 index eaffe8a..0000000 --- a/examples/VTransformer/Main.out +++ /dev/null @@ -1,42 +0,0 @@ -*/ - - -package VTransformer; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -public class Main -{ - /** Accept the visitor. **/ - public Object jjtAccept(JavaParserVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - public static void main(String args[]) throws FileNotFoundException { - InputStream is = System.in; - PrintStream os = System.out; - PrintStream es = System.err; - if (args != null) { - if (args.length == 3) { - is = new FileInputStream(args[0]); - os = new PrintStream(args[1]); - es = new PrintStream(args[2]); - } - } - System.err.println("Reading from standard input..."); - JavaParser p = new JavaParser(is); - try { - ASTCompilationUnit cu = p.CompilationUnit(); - JavaParserVisitor visitor = new AddAcceptVisitor(os); - cu.jjtAccept(visitor, null); - es.println("Thank you."); - } catch (Exception e) { - es.println("Oops."); - es.println(e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/examples/VTransformer/README b/examples/VTransformer/README deleted file mode 100644 index 4cb8ef6..0000000 --- a/examples/VTransformer/README +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -This directory contains an example of using the Visitor design pattern -with JJTree. Like the Transformer example, it shows how a Java -program can be processed into a slightly different form. - -In this case the input code is transformed so that each class has a -jjtAccept() method inserted. This might be useful for updating node -files created with an earlier version of JJTree so that they can be -used with the Visitor support. - -Here is an overview of the source files: - -Java1.1.jjt - - This JJTree source file has been slightly modified from the Java 1.1 - grammar distributed in the JavaGrammars examples directory. Here - are the main differences: - - 1) Removed the main method from the parser class; - - 2) Added a couple of JJTree options; - - 3) Made the CompilationUnit production return a root AST node; - - 4) Made white space SPECIAL_TOKENs rather than SKIPs; - - These changes illustrate how a JavaCC grammar can be used with - JJTree with very little modification. In particular, there are no - node annotations -- instead each production in the grammar is - represented as a node. - -Main.java - - Simply calls the parser to create the AST, creates a Visitor, and - then asks the root node to accept the visitor. - -SimpleNode.java - - This is modified from the automatically generated file. SimpleNodes - now maintain their first and last tokens so that the input can be - reconstituted. The jjtOpen() and jjtClose() methods are used as - hooks to collect and store these tokens. The NODE_USES_PARSER - option is specified so that the parser object is available to these - methods. - -UnparseVisitor.java - - This is a generally useful Visitor that simply unparses the nodes - that it visits. It is intended to be a superclass for - transformation-specific Visitors such as AddAcceptVisitor. - -AddAcceptVisitor.java - - This is a Visitor for a particular transformation. It extends - UnparseVisitor and overrides methods for those nodes that require - special treatment. In this case, only the visit method for - ClassBodyDeclaration nodes needs to be overridden. - - The visitor determines whether the node currently being visited is - the first child of its parent, and if so it inserts the new text. - It makes an attempt to indent the new text at the same level as the - current node. - - -Here's how to build the transformer: - -1) Run the JJTree on the grammar. It will generate many node files -because the MULTI option is set. - -trane% jjtree Java1.1.jjt -Java Compiler Compiler Version 2.0 (Tree Builder) -Copyright (c) 1996-1999 Sun Microsystems, Inc. -Copyright (c) 1997-1999 Metamata, Inc. -(type "jjtree" with no arguments for help) -Reading from file Java1.1.jjt . . . -File "Node.java" does not exist. Will create one. -File "ASTCompilationUnit.java" does not exist. Will create one. -File "ASTPackageDeclaration.java" does not exist. Will create one. - ... lots more nodes generated here -File "ASTSynchronizedStatement.java" does not exist. Will create one. -File "ASTTryStatement.java" does not exist. Will create one. -Annotated grammar generated successfully in Java1.1.jj -trane% - -2) Run JavaCC on the generated grammar. - -trane% javacc Java1.1.jj -Java Compiler Compiler Version 2.0 (Parser Generator) -Copyright (c) 1996-1999 Sun Microsystems, Inc. -Copyright (c) 1997-1999 Metamata, Inc. -(type "javacc" with no arguments for help) -Reading from file Java1.1.jj . . . -File "TokenMgrError.java" does not exist. Will create one. -File "ParseException.java" does not exist. Will create one. -File "Token.java" does not exist. Will create one. -File "ASCII_UCodeESC_CharStream.java" does not exist. Will create one. -Parser generated successfully. -trane% - -3) Ensure that your class path is set up correctly. The examples -directory (above VTransformer) should be in your class path. - -4) Compile the Java files - -trane% javac Main.java - -5) And finally run it. It works as a filter now, but it would be -straightforward to make it take file names as arguments. The -example below shows how to apply the filter on Main.java itself. - -trane% java Main < Main.java > Main.new -Reading from standard input... -Thank you. -trane% diff --git a/examples/VTransformer/pom.xml b/examples/VTransformer/pom.xml deleted file mode 100644 index b3bf283..0000000 --- a/examples/VTransformer/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - examples - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.examples - vtransformer - jar - - JavaCC Java code generator / examples / VTransformer - - - - - - org.codehaus.mojo - exec-maven-plugin - - - VTransformer - test - - java - - - VTransformer.Main - - ${project.basedir}/Main.in - ${project.basedir}/Main.out - ${project.basedir}/Main.err - - - - - - - - - \ No newline at end of file diff --git a/examples/VTransformer/src/main/java/VTransformer/AddAcceptVisitor.java b/examples/VTransformer/src/main/java/VTransformer/AddAcceptVisitor.java deleted file mode 100644 index c96edc8..0000000 --- a/examples/VTransformer/src/main/java/VTransformer/AddAcceptVisitor.java +++ /dev/null @@ -1,65 +0,0 @@ -package VTransformer; -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -//package VTransformer; - -import java.io.PrintStream; - -public class AddAcceptVisitor extends UnparseVisitor -{ - - public AddAcceptVisitor(PrintStream o) - { - super(o); - } - - - public Object visit(ASTClassBodyDeclaration node, Object data) - { - /* Are we the first child of our parent? */ - if (node == node.jjtGetParent().jjtGetChild(0)) { - - /** Attempt to make the new code match the indentation of the - node. */ - StringBuffer pre = new StringBuffer(""); - for (int i = 1; i < node.getFirstToken().beginColumn; ++i) { - pre.append(' '); - } - - out.println(pre + ""); - out.println(pre + "/** Accept the visitor. **/"); - out.println(pre + "public Object jjtAccept(JavaParserVisitor visitor, Object data) {"); - out.println(pre + " return visitor.visit(this, data);"); - out.println(pre + "}"); - } - return super.visit(node, data); - } - -} diff --git a/examples/VTransformer/src/main/java/VTransformer/Main.java b/examples/VTransformer/src/main/java/VTransformer/Main.java deleted file mode 100644 index 403858a..0000000 --- a/examples/VTransformer/src/main/java/VTransformer/Main.java +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -//package VTransformer; - -package VTransformer; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.PrintStream; - -public class Main -{ - public static void main(String args[]) throws FileNotFoundException { - InputStream is = System.in; - PrintStream os = System.out; - PrintStream es = System.err; - if (args != null) { - if (args.length == 3) { - is = new FileInputStream(args[0]); - os = new PrintStream(args[1]); - es = new PrintStream(args[2]); - } - } - System.err.println("Reading from standard input..."); - JavaParser p = new JavaParser(is); - try { - ASTCompilationUnit cu = p.CompilationUnit(); - JavaParserVisitor visitor = new AddAcceptVisitor(os); - cu.jjtAccept(visitor, null); - es.println("Thank you."); - } catch (Exception e) { - es.println("Oops."); - es.println(e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/examples/VTransformer/src/main/java/VTransformer/Node.java b/examples/VTransformer/src/main/java/VTransformer/Node.java deleted file mode 100644 index 9befd95..0000000 --- a/examples/VTransformer/src/main/java/VTransformer/Node.java +++ /dev/null @@ -1,156 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -package VTransformer; - -public class Node implements Tree { - protected Node parent; - protected Node[] children; - protected int id; - protected JavaParser parser; - - protected Token first, last; - - public Node(int i) { - id = i; - } - - public Node(JavaParser p, int i) { - this(i); - parser = p; - } - - public static Node jjtCreate(JavaParser p, int id) { - return new Node(p, id); - } - - @Override - public int getId() { - return id; - } - - @Override - public void jjtOpen() { - first = parser.getToken(1); // new - } - - @Override - public void jjtClose() { - last = parser.getToken(0); // new - } - - public Token getFirstToken() { - return first; - } // new - - public Token getLastToken() { - return last; - } // new - - @Override - public void jjtSetParent(Node n) { - parent = n; - } - - @Override - public Node jjtGetParent() { - return parent; - } - - @Override - public void jjtAddChild(Node n, int i) { - if (children == null) { - children = new Node[i + 1]; - } else if (i >= children.length) { - Node c[] = new Node[i + 1]; - System.arraycopy(children, 0, c, 0, children.length); - children = c; - } - children[i] = n; - } - - @Override - public Node jjtGetChild(int i) { - return children[i]; - } - - @Override - public Node[] jjtGetChildren() { - return children; - } - - @Override - public int jjtGetNumChildren() { - return (children == null) ? 0 : children.length; - } - - /** Accept the visitor. **/ - @Override - public Object jjtAccept(JavaParserVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - /** Accept the visitor. **/ - public Object childrenAccept(JavaParserVisitor visitor, Object data) { - if (children != null) { - for (int i = 0; i < children.length; ++i) { - children[i].jjtAccept(visitor, data); - } - } - return data; - } - - /* You can override these two methods in subclasses of SimpleNode to - customize the way the node appears when the tree is dumped. If - your output uses more than one line you should override - toString(String), otherwise overriding toString() is probably all - you need to do. */ - - public String toString() { - return JavaParserTreeConstants.jjtNodeName[id]; - } - - public String toString(String prefix) { - return prefix + toString(); - } - - /* Override this method if you want to customize how the node dumps - out its children. */ - - public void dump(String prefix) { - System.out.println(toString(prefix)); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - Node n = (Node) children[i]; - if (n != null) { - n.dump(prefix + " "); - } - } - } - } -} diff --git a/examples/VTransformer/src/main/java/VTransformer/UnparseVisitor.java b/examples/VTransformer/src/main/java/VTransformer/UnparseVisitor.java deleted file mode 100644 index df1ffc3..0000000 --- a/examples/VTransformer/src/main/java/VTransformer/UnparseVisitor.java +++ /dev/null @@ -1,527 +0,0 @@ -package VTransformer; -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -//package VTransformer; - -import java.io.PrintStream; - -public class UnparseVisitor implements JavaParserVisitor -{ - - protected PrintStream out; - - - public UnparseVisitor(PrintStream o) - { - out = o; - } - - - public Object print(Node node, Object data) { - Token t1 = node.getFirstToken(); - Token t = new Token(); - t.next = t1; - - Node n; - for (int ord = 0; ord < node.jjtGetNumChildren(); ord++) { - n = (Node)node.jjtGetChild(ord); - while (true) { - t = t.next; - if (t == n.getFirstToken()) break; - print(t); - } - n.jjtAccept(this, data); - t = n.getLastToken(); - } - - while (t != node.getLastToken()) { - t = t.next; - print(t); - } - return data; - } - - - protected void print(Token t) { - Token tt = t.specialToken; - if (tt != null) { - while (tt.specialToken != null) tt = tt.specialToken; - while (tt != null) { - out.print(addUnicodeEscapes(tt.image)); - tt = tt.next; - } - } - out.print(addUnicodeEscapes(t.image)); - } - - - private String addUnicodeEscapes(String str) { - String retval = ""; - char ch; - for (int i = 0; i < str.length(); i++) { - ch = str.charAt(i); - if ((ch < 0x20 || ch > 0x7e) && - ch != '\t' && ch != '\n' && ch != '\r' && ch != '\f') { - String s = "0000" + Integer.toString(ch, 16); - retval += "\\u" + s.substring(s.length() - 4, s.length()); - } else { - retval += ch; - } - } - return retval; - } - - - public Object visit(Node node, Object data) - { - return print(node, data); - } - - public Object visit(ASTCompilationUnit node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPackageDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTImportDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTTypeDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTClassDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTUnmodifiedClassDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTClassBody node, Object data) - { - return print(node, data); - } - - public Object visit(ASTNestedClassDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTClassBodyDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTMethodDeclarationLookahead node, Object data) - { - return print(node, data); - } - - public Object visit(ASTInterfaceDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTNestedInterfaceDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTUnmodifiedInterfaceDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTInterfaceMemberDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTFieldDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTVariableDeclarator node, Object data) - { - return print(node, data); - } - - public Object visit(ASTVariableDeclaratorId node, Object data) - { - return print(node, data); - } - - public Object visit(ASTVariableInitializer node, Object data) - { - return print(node, data); - } - - public Object visit(ASTArrayInitializer node, Object data) - { - return print(node, data); - } - - public Object visit(ASTMethodDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTMethodDeclarator node, Object data) - { - return print(node, data); - } - - public Object visit(ASTFormalParameters node, Object data) - { - return print(node, data); - } - - public Object visit(ASTFormalParameter node, Object data) - { - return print(node, data); - } - - public Object visit(ASTConstructorDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTExplicitConstructorInvocation node, Object data) - { - return print(node, data); - } - - public Object visit(ASTInitializer node, Object data) - { - return print(node, data); - } - - public Object visit(ASTType node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPrimitiveType node, Object data) - { - return print(node, data); - } - - public Object visit(ASTResultType node, Object data) - { - return print(node, data); - } - - public Object visit(ASTName node, Object data) - { - return print(node, data); - } - - public Object visit(ASTNameList node, Object data) - { - return print(node, data); - } - - public Object visit(ASTExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTAssignmentOperator node, Object data) - { - return print(node, data); - } - - public Object visit(ASTConditionalExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTConditionalOrExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTConditionalAndExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTInclusiveOrExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTExclusiveOrExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTAndExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTEqualityExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTInstanceOfExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTRelationalExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTShiftExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTAdditiveExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTMultiplicativeExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTUnaryExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPreIncrementExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPreDecrementExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTUnaryExpressionNotPlusMinus node, Object data) - { - return print(node, data); - } - - public Object visit(ASTCastLookahead node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPostfixExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTCastExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPrimaryExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPrimaryPrefix node, Object data) - { - return print(node, data); - } - - public Object visit(ASTPrimarySuffix node, Object data) - { - return print(node, data); - } - - public Object visit(ASTLiteral node, Object data) - { - return print(node, data); - } - - public Object visit(ASTBooleanLiteral node, Object data) - { - return print(node, data); - } - - public Object visit(ASTNullLiteral node, Object data) - { - return print(node, data); - } - - public Object visit(ASTArguments node, Object data) - { - return print(node, data); - } - - public Object visit(ASTArgumentList node, Object data) - { - return print(node, data); - } - - public Object visit(ASTAllocationExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTArrayDimsAndInits node, Object data) - { - return print(node, data); - } - - public Object visit(ASTStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTLabeledStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTBlock node, Object data) - { - return print(node, data); - } - - public Object visit(ASTBlockStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTLocalVariableDeclaration node, Object data) - { - return print(node, data); - } - - public Object visit(ASTEmptyStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTStatementExpression node, Object data) - { - return print(node, data); - } - - public Object visit(ASTSwitchStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTSwitchLabel node, Object data) - { - return print(node, data); - } - - public Object visit(ASTIfStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTWhileStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTDoStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTForStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTForInit node, Object data) - { - return print(node, data); - } - - public Object visit(ASTStatementExpressionList node, Object data) - { - return print(node, data); - } - - public Object visit(ASTForUpdate node, Object data) - { - return print(node, data); - } - - public Object visit(ASTBreakStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTContinueStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTReturnStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTThrowStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTSynchronizedStatement node, Object data) - { - return print(node, data); - } - - public Object visit(ASTTryStatement node, Object data) - { - return print(node, data); - } - -} diff --git a/examples/VTransformer/src/main/jjtree/Java1.1.jjt b/examples/VTransformer/src/main/jjtree/Java1.1.jjt deleted file mode 100644 index 452e20b..0000000 --- a/examples/VTransformer/src/main/jjtree/Java1.1.jjt +++ /dev/null @@ -1,1075 +0,0 @@ -/* Copyright (c) 2006, Sun Microsystems, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Sun Microsystems, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - - -options { - JAVA_UNICODE_ESCAPE = true; - - STATIC=false; - - SINGLE_TREE_FILE = false; // as some node files are customized - - MULTI=true; - VISITOR=true; - NODE_USES_PARSER=true; - NODE_FACTORY = true; -} - -PARSER_BEGIN(JavaParser) - -package VTransformer; - -public class JavaParser {} - -PARSER_END(JavaParser) - - -/* WHITE SPACE */ - -SPECIAL_TOKEN : -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -/* COMMENTS */ - -MORE : -{ - "//" : IN_SINGLE_LINE_COMMENT -| - <"/**" ~["/"]> { input_stream.backup(1); } : IN_FORMAL_COMMENT -| - "/*" : IN_MULTI_LINE_COMMENT -} - - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -SPECIAL_TOKEN : -{ - : DEFAULT -} - - -MORE : -{ - < ~[] > -} - -/* RESERVED WORDS AND LITERALS */ - -TOKEN : -{ - < ABSTRACT: "abstract" > -| < BOOLEAN: "boolean" > -| < BREAK: "break" > -| < BYTE: "byte" > -| < CASE: "case" > -| < CATCH: "catch" > -| < CHAR: "char" > -| < CLASS: "class" > -| < CONST: "const" > -| < CONTINUE: "continue" > -| < _DEFAULT: "default" > -| < DO: "do" > -| < DOUBLE: "double" > -| < ELSE: "else" > -| < EXTENDS: "extends" > -| < FALSE: "false" > -| < FINAL: "final" > -| < FINALLY: "finally" > -| < FLOAT: "float" > -| < FOR: "for" > -| < GOTO: "goto" > -| < IF: "if" > -| < IMPLEMENTS: "implements" > -| < IMPORT: "import" > -| < INSTANCEOF: "instanceof" > -| < INT: "int" > -| < INTERFACE: "interface" > -| < LONG: "long" > -| < NATIVE: "native" > -| < NEW: "new" > -| < NULL: "null" > -| < PACKAGE: "package"> -| < PRIVATE: "private" > -| < PROTECTED: "protected" > -| < PUBLIC: "public" > -| < RETURN: "return" > -| < SHORT: "short" > -| < STATIC: "static" > -| < SUPER: "super" > -| < SWITCH: "switch" > -| < SYNCHRONIZED: "synchronized" > -| < THIS: "this" > -| < THROW: "throw" > -| < THROWS: "throws" > -| < TRANSIENT: "transient" > -| < TRUE: "true" > -| < TRY: "try" > -| < VOID: "void" > -| < VOLATILE: "volatile" > -| < WHILE: "while" > -} - -/* LITERALS */ - -TOKEN : -{ - < INTEGER_LITERAL: - (["l","L"])? - | (["l","L"])? - | (["l","L"])? - > -| - < #DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* > -| - < #HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > -| - < #OCTAL_LITERAL: "0" (["0"-"7"])* > -| - < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? (["f","F","d","D"])? - | "." (["0"-"9"])+ ()? (["f","F","d","D"])? - | (["0"-"9"])+ (["f","F","d","D"])? - | (["0"-"9"])+ ()? ["f","F","d","D"] - > -| - < #EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ > -| - < CHARACTER_LITERAL: - "'" - ( (~["'","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - ) - "'" - > -| - < STRING_LITERAL: - "\"" - ( (~["\"","\\","\n","\r"]) - | ("\\" - ( ["n","t","b","r","f","\\","'","\""] - | ["0"-"7"] ( ["0"-"7"] )? - | ["0"-"3"] ["0"-"7"] ["0"-"7"] - ) - ) - )* - "\"" - > -} - -/* IDENTIFIERS */ - -TOKEN : -{ - < IDENTIFIER: (|)* > -| - < #LETTER: - [ - "\u0024", - "\u0041"-"\u005a", - "\u005f", - "\u0061"-"\u007a", - "\u00c0"-"\u00d6", - "\u00d8"-"\u00f6", - "\u00f8"-"\u00ff", - "\u0100"-"\u1fff", - "\u3040"-"\u318f", - "\u3300"-"\u337f", - "\u3400"-"\u3d2d", - "\u4e00"-"\u9fff", - "\uf900"-"\ufaff" - ] - > -| - < #DIGIT: - [ - "\u0030"-"\u0039", - "\u0660"-"\u0669", - "\u06f0"-"\u06f9", - "\u0966"-"\u096f", - "\u09e6"-"\u09ef", - "\u0a66"-"\u0a6f", - "\u0ae6"-"\u0aef", - "\u0b66"-"\u0b6f", - "\u0be7"-"\u0bef", - "\u0c66"-"\u0c6f", - "\u0ce6"-"\u0cef", - "\u0d66"-"\u0d6f", - "\u0e50"-"\u0e59", - "\u0ed0"-"\u0ed9", - "\u1040"-"\u1049" - ] - > -} - -/* SEPARATORS */ - -TOKEN : -{ - < LPAREN: "(" > -| < RPAREN: ")" > -| < LBRACE: "{" > -| < RBRACE: "}" > -| < LBRACKET: "[" > -| < RBRACKET: "]" > -| < SEMICOLON: ";" > -| < COMMA: "," > -| < DOT: "." > -} - -/* OPERATORS */ - -TOKEN : -{ - < ASSIGN: "=" > -| < GT: ">" > -| < LT: "<" > -| < BANG: "!" > -| < TILDE: "~" > -| < HOOK: "?" > -| < COLON: ":" > -| < EQ: "==" > -| < LE: "<=" > -| < GE: ">=" > -| < NE: "!=" > -| < SC_OR: "||" > -| < SC_AND: "&&" > -| < INCR: "++" > -| < DECR: "--" > -| < PLUS: "+" > -| < MINUS: "-" > -| < STAR: "*" > -| < SLASH: "/" > -| < BIT_AND: "&" > -| < BIT_OR: "|" > -| < XOR: "^" > -| < REM: "%" > -| < LSHIFT: "<<" > -| < RSIGNEDSHIFT: ">>" > -| < RUNSIGNEDSHIFT: ">>>" > -| < PLUSASSIGN: "+=" > -| < MINUSASSIGN: "-=" > -| < STARASSIGN: "*=" > -| < SLASHASSIGN: "/=" > -| < ANDASSIGN: "&=" > -| < ORASSIGN: "|=" > -| < XORASSIGN: "^=" > -| < REMASSIGN: "%=" > -| < LSHIFTASSIGN: "<<=" > -| < RSIGNEDSHIFTASSIGN: ">>=" > -| < RUNSIGNEDSHIFTASSIGN: ">>>=" > -} - - -/***************************************** - * THE JAVA LANGUAGE GRAMMAR STARTS HERE * - *****************************************/ - -/* - * Program structuring syntax follows. - */ - -ASTCompilationUnit CompilationUnit() : -{} -{ - [ PackageDeclaration() ] - ( ImportDeclaration() )* - ( TypeDeclaration() )* - - { - return jjtThis; - } -} - -void PackageDeclaration() : -{} -{ - "package" Name() ";" -} - -void ImportDeclaration() : -{} -{ - "import" Name() [ "." "*" ] ";" -} - -void TypeDeclaration() : -{} -{ - LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" ) - ClassDeclaration() -| - InterfaceDeclaration() -| - ";" -} - - -/* - * Declaration syntax follows. - */ - -void ClassDeclaration() : -{} -{ - ( "abstract" | "final" | "public" )* - UnmodifiedClassDeclaration() -} - -void UnmodifiedClassDeclaration() : -{} -{ - "class" [ "extends" Name() ] [ "implements" NameList() ] - ClassBody() -} - -void ClassBody() : -{} -{ - "{" ( ClassBodyDeclaration() )* "}" -} - -void NestedClassDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedClassDeclaration() -} - -void ClassBodyDeclaration() : -{} -{ - LOOKAHEAD(2) - Initializer() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( [ "public" | "protected" | "private" ] Name() "(" ) - ConstructorDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -// This production is to determine lookahead only. -void MethodDeclarationLookahead() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() "(" -} - -void InterfaceDeclaration() : -{} -{ - ( "abstract" | "public" )* - UnmodifiedInterfaceDeclaration() -} - -void NestedInterfaceDeclaration() : -{} -{ - ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* - UnmodifiedInterfaceDeclaration() -} - -void UnmodifiedInterfaceDeclaration() : -{} -{ - "interface" [ "extends" NameList() ] - "{" ( InterfaceMemberDeclaration() )* "}" -} - -void InterfaceMemberDeclaration() : -{} -{ - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "class" ) - NestedClassDeclaration() -| - LOOKAHEAD( ( "static" | "abstract" | "final" | "public" | "protected" | "private" )* "interface" ) - NestedInterfaceDeclaration() -| - LOOKAHEAD( MethodDeclarationLookahead() ) - MethodDeclaration() -| - FieldDeclaration() -} - -void FieldDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "final" | "transient" | "volatile" )* - Type() VariableDeclarator() ( "," VariableDeclarator() )* ";" -} - -void VariableDeclarator() : -{} -{ - VariableDeclaratorId() [ "=" VariableInitializer() ] -} - -void VariableDeclaratorId() : -{} -{ - ( "[" "]" )* -} - -void VariableInitializer() : -{} -{ - ArrayInitializer() -| - Expression() -} - -void ArrayInitializer() : -{} -{ - "{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}" -} - -void MethodDeclaration() : -{} -{ - ( "public" | "protected" | "private" | "static" | "abstract" | "final" | "native" | "synchronized" )* - ResultType() MethodDeclarator() [ "throws" NameList() ] - ( Block() | ";" ) -} - -void MethodDeclarator() : -{} -{ - FormalParameters() ( "[" "]" )* -} - -void FormalParameters() : -{} -{ - "(" [ FormalParameter() ( "," FormalParameter() )* ] ")" -} - -void FormalParameter() : -{} -{ - [ "final" ] Type() VariableDeclaratorId() -} - -void ConstructorDeclaration() : -{} -{ - [ "public" | "protected" | "private" ] - FormalParameters() [ "throws" NameList() ] - "{" - [ LOOKAHEAD(ExplicitConstructorInvocation()) ExplicitConstructorInvocation() ] - ( BlockStatement() )* - "}" -} - -void ExplicitConstructorInvocation() : -{} -{ - LOOKAHEAD("this" Arguments() ";") - "this" Arguments() ";" -| - [ LOOKAHEAD(2) PrimaryExpression() "." ] "super" Arguments() ";" -} - -void Initializer() : -{} -{ - [ "static" ] Block() -} - - -/* - * Type, name and expression syntax follows. - */ - -void Type() : -{} -{ - ( PrimitiveType() | Name() ) ( "[" "]" )* -} - -void PrimitiveType() : -{} -{ - "boolean" -| - "char" -| - "byte" -| - "short" -| - "int" -| - "long" -| - "float" -| - "double" -} - -void ResultType() : -{} -{ - "void" -| - Type() -} - -void Name() : -/* - * A lookahead of 2 is required below since "Name" can be followed - * by a ".*" when used in the context of an "ImportDeclaration". - */ -{} -{ - - ( LOOKAHEAD(2) "." - )* -} - -void NameList() : -{} -{ - Name() - ( "," Name() - )* -} - - -/* - * Expression syntax follows. - */ - -void Expression() : -/* - * This expansion has been written this way instead of: - * Assignment() | ConditionalExpression() - * for performance reasons. - * However, it is a weakening of the grammar for it allows the LHS of - * assignments to be any conditional expression whereas it can only be - * a primary expression. Consider adding a semantic predicate to work - * around this. - */ -{} -{ - ConditionalExpression() - [ - AssignmentOperator() Expression() - ] -} - -void AssignmentOperator() : -{} -{ - "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | ">>>=" | "&=" | "^=" | "|=" -} - -void ConditionalExpression() : -{} -{ - ConditionalOrExpression() [ "?" Expression() ":" ConditionalExpression() ] -} - -void ConditionalOrExpression() : -{} -{ - ConditionalAndExpression() ( "||" ConditionalAndExpression() )* -} - -void ConditionalAndExpression() : -{} -{ - InclusiveOrExpression() ( "&&" InclusiveOrExpression() )* -} - -void InclusiveOrExpression() : -{} -{ - ExclusiveOrExpression() ( "|" ExclusiveOrExpression() )* -} - -void ExclusiveOrExpression() : -{} -{ - AndExpression() ( "^" AndExpression() )* -} - -void AndExpression() : -{} -{ - EqualityExpression() ( "&" EqualityExpression() )* -} - -void EqualityExpression() : -{} -{ - InstanceOfExpression() ( ( "==" | "!=" ) InstanceOfExpression() )* -} - -void InstanceOfExpression() : -{} -{ - RelationalExpression() [ "instanceof" Type() ] -} - -void RelationalExpression() : -{} -{ - ShiftExpression() ( ( "<" | ">" | "<=" | ">=" ) ShiftExpression() )* -} - -void ShiftExpression() : -{} -{ - AdditiveExpression() ( ( "<<" | ">>" | ">>>" ) AdditiveExpression() )* -} - -void AdditiveExpression() : -{} -{ - MultiplicativeExpression() ( ( "+" | "-" ) MultiplicativeExpression() )* -} - -void MultiplicativeExpression() : -{} -{ - UnaryExpression() ( ( "*" | "/" | "%" ) UnaryExpression() )* -} - -void UnaryExpression() : -{} -{ - ( "+" | "-" ) UnaryExpression() -| - PreIncrementExpression() -| - PreDecrementExpression() -| - UnaryExpressionNotPlusMinus() -} - -void PreIncrementExpression() : -{} -{ - "++" PrimaryExpression() -} - -void PreDecrementExpression() : -{} -{ - "--" PrimaryExpression() -} - -void UnaryExpressionNotPlusMinus() : -{} -{ - ( "~" | "!" ) UnaryExpression() -| - LOOKAHEAD( CastLookahead() ) - CastExpression() -| - PostfixExpression() -} - -// This production is to determine lookahead only. The LOOKAHEAD specifications -// below are not used, but they are there just to indicate that we know about -// this. -void CastLookahead() : -{} -{ - LOOKAHEAD(2) - "(" PrimitiveType() -| - LOOKAHEAD("(" Name() "[") - "(" Name() "[" "]" -| - "(" Name() ")" ( "~" | "!" | "(" | | "this" | "super" | "new" | Literal() ) -} - -void PostfixExpression() : -{} -{ - PrimaryExpression() [ "++" | "--" ] -} - -void CastExpression() : -{} -{ - LOOKAHEAD("(" PrimitiveType()) - "(" Type() ")" UnaryExpression() -| - LOOKAHEAD("(" Name()) - "(" Type() ")" UnaryExpressionNotPlusMinus() -} - -void PrimaryExpression() : -{} -{ - PrimaryPrefix() ( LOOKAHEAD(2) PrimarySuffix() )* -} - -void PrimaryPrefix() : -{} -{ - Literal() -| - "this" -| - "super" "." -| - "(" Expression() ")" -| - AllocationExpression() -| - LOOKAHEAD( ResultType() "." "class" ) - ResultType() "." "class" -| - Name() -} - -void PrimarySuffix() : -{} -{ - LOOKAHEAD(2) - "." "this" -| - LOOKAHEAD(2) - "." AllocationExpression() -| - "[" Expression() "]" -| - "." -| - Arguments() -} - -void Literal() : -{} -{ - -| - -| - -| - -| - BooleanLiteral() -| - NullLiteral() -} - -void BooleanLiteral() : -{} -{ - "true" -| - "false" -} - -void NullLiteral() : -{} -{ - "null" -} - -void Arguments() : -{} -{ - "(" [ ArgumentList() ] ")" -} - -void ArgumentList() : -{} -{ - Expression() ( "," Expression() )* -} - -void AllocationExpression() : -{} -{ - LOOKAHEAD(2) - "new" PrimitiveType() ArrayDimsAndInits() -| - "new" Name() - ( - ArrayDimsAndInits() - | - Arguments() [ ClassBody() ] - ) -} - -/* - * The second LOOKAHEAD specification below is to parse to PrimarySuffix - * if there is an expression between the "[...]". - */ -void ArrayDimsAndInits() : -{} -{ - LOOKAHEAD(2) - ( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )* -| - ( "[" "]" )+ ArrayInitializer() -} - - -/* - * Statement syntax follows. - */ - -void Statement() : -{} -{ - LOOKAHEAD(2) - LabeledStatement() -| - Block() -| - EmptyStatement() -| - StatementExpression() ";" -| - SwitchStatement() -| - IfStatement() -| - WhileStatement() -| - DoStatement() -| - ForStatement() -| - BreakStatement() -| - ContinueStatement() -| - ReturnStatement() -| - ThrowStatement() -| - SynchronizedStatement() -| - TryStatement() -} - -void LabeledStatement() : -{} -{ - ":" Statement() -} - -void Block() : -{} -{ - "{" ( BlockStatement() )* "}" -} - -void BlockStatement() : -{} -{ - LOOKAHEAD([ "final" ] Type() ) - LocalVariableDeclaration() ";" -| - Statement() -| - UnmodifiedClassDeclaration() -} - -void LocalVariableDeclaration() : -{} -{ - [ "final" ] Type() VariableDeclarator() ( "," VariableDeclarator() )* -} - -void EmptyStatement() : -{} -{ - ";" -} - -void StatementExpression() : -/* - * The last expansion of this production accepts more than the legal - * Java expansions for StatementExpression. This expansion does not - * use PostfixExpression for performance reasons. - */ -{} -{ - PreIncrementExpression() -| - PreDecrementExpression() -| - PrimaryExpression() - [ - "++" - | - "--" - | - AssignmentOperator() Expression() - ] -} - -void SwitchStatement() : -{} -{ - "switch" "(" Expression() ")" "{" - ( SwitchLabel() ( BlockStatement() )* )* - "}" -} - -void SwitchLabel() : -{} -{ - "case" Expression() ":" -| - "default" ":" -} - -void IfStatement() : -/* - * The disambiguating algorithm of JavaCC automatically binds dangling - * else's to the innermost if statement. The LOOKAHEAD specification - * is to tell JavaCC that we know what we are doing. - */ -{} -{ - "if" "(" Expression() ")" Statement() [ LOOKAHEAD(1) "else" Statement() ] -} - -void WhileStatement() : -{} -{ - "while" "(" Expression() ")" Statement() -} - -void DoStatement() : -{} -{ - "do" Statement() "while" "(" Expression() ")" ";" -} - -void ForStatement() : -{} -{ - "for" "(" [ ForInit() ] ";" [ Expression() ] ";" [ ForUpdate() ] ")" Statement() -} - -void ForInit() : -{} -{ - LOOKAHEAD( [ "final" ] Type() ) - LocalVariableDeclaration() -| - StatementExpressionList() -} - -void StatementExpressionList() : -{} -{ - StatementExpression() ( "," StatementExpression() )* -} - -void ForUpdate() : -{} -{ - StatementExpressionList() -} - -void BreakStatement() : -{} -{ - "break" [ ] ";" -} - -void ContinueStatement() : -{} -{ - "continue" [ ] ";" -} - -void ReturnStatement() : -{} -{ - "return" [ Expression() ] ";" -} - -void ThrowStatement() : -{} -{ - "throw" Expression() ";" -} - -void SynchronizedStatement() : -{} -{ - "synchronized" "(" Expression() ")" Block() -} - -void TryStatement() : -/* - * Semantic check required here to make sure that at least one - * finally/catch is present. - */ -{} -{ - "try" Block() - ( "catch" "(" FormalParameter() ")" Block() )* - [ "finally" Block() ] -} diff --git a/examples/invoker.properties b/examples/invoker.properties deleted file mode 100644 index 650db68..0000000 --- a/examples/invoker.properties +++ /dev/null @@ -1,10 +0,0 @@ -# A comma or space separated list of goals/phases to execute, -# may specify an empty list to execute the default goal of the IT project. -# Environment variables used by maven plugins can be added here - -# "normal" install & run goals are defined in ../it/pom.xml; -# may be temporary specifically changed here -#invoker.goals = install run - -# may uncomment this for temporary specific debugging -#invoker.debug = true \ No newline at end of file diff --git a/examples/pom.xml b/examples/pom.xml deleted file mode 100644 index 9b474ad..0000000 --- a/examples/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - 1.1.0-SNAPSHOT - it - ../it - - - examples - pom - - JavaCC Java code generator / examples - - - CORBA-IDL - CustomTemplate - GUIParsing - Gwt - Interpreter - JavaCC - JJTree - MailProcessing - Lookahead - Obfuscator - Simple - Transformer - VTransformer - - - - - - - skip-test-java-examples - - true - true - true - - - - - doNotFailOnError-check-java-examples - - false - false - false - - - - - - diff --git a/grammars/README.md b/grammars/README.md deleted file mode 100644 index 43a4c2f..0000000 --- a/grammars/README.md +++ /dev/null @@ -1,6 +0,0 @@ -In this directory lie some grammars shared by contributors, usually under src/main/javacc; -feel free to enhance them and share them back. - -They are considered as a subset of integration tests (they should at least generate properly). - -Some examples have been ported between Java and C++ and C#, with the goal to be fully equivalent. \ No newline at end of file diff --git a/grammars/asn1/pom.xml b/grammars/asn1/pom.xml deleted file mode 100644 index c6cab25..0000000 --- a/grammars/asn1/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - grammars - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.grammars - asn1 - jar - - JavaCC Java code generator / grammars / asn1 - - \ No newline at end of file diff --git a/grammars/asn1/src/main/javacc/AsnParser.jj b/grammars/asn1/src/main/javacc/AsnParser.jj deleted file mode 100644 index 4fc74db..0000000 --- a/grammars/asn1/src/main/javacc/AsnParser.jj +++ /dev/null @@ -1,719 +0,0 @@ -/* - * - * ASN.1 grammar for JavaCC - * - * Contributed by Helena Sarin (hsarin@lucent.com) - * - * Derived in part from the following work: snacc - a freeware ASN.1 to C or C++ compiler, v 1.3, - * yacc/lex source code ( parse-asn1.y, lex-asn1.l), - * the free software, which is covered by GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or later - * - * I tested it against several ASN.1 files used by CMIP; - * Additional work is reguired to fully support SNMP MIBs parsing - * - * Please let me know if you use this grammar: i'm using it to develop ASN.1/IDL compiler - * - */ - -options { -SANITY_CHECK=true; -DEBUG_PARSER=false; -DEBUG_TOKEN_MANAGER=false; -} - -PARSER_BEGIN(AsnParser) - -import java.util.*; - -public class AsnParser { - - - public static void main(String args[]) throws ParseException { - - AsnParser parser; - parser = new AsnParser(System.in); - try { - parser.Input(); - System.out.println("ASN.1 file parsed successfully."); - } - catch(ParseException e){ - System.out.println(e.toString()); - } - } - - private static String usefulTypes[] = { - "GraphicString", "NumericString", "PrintableString", - "TeletexString", "T61String", "VideotexString", "IA5String", - "VisibleString", "ISO646String", "GeneralizedTime", "UniversalString", "BMPString" }; -} - -PARSER_END(AsnParser) - -SKIP : -{ - " " -| "\t" -| "\n" -| "\r" -} - -SPECIAL_TOKEN : -{ - "--" : WithinASNComment -} - - SPECIAL_TOKEN : -{ - <("--" | "\n" | "\r" | "\r\n" )> : DEFAULT -} - - MORE : -{ - <~[]> -} - -TOKEN : -{ - -} - -TOKEN : -{ - -} - -TOKEN : -{ - -} - -TOKEN : -{ - -} - -TOKEN : -{ - -} - -TOKEN : -{ - -} - -TOKEN : -{ - -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -} - -TOKEN : -{ - -} - - -TOKEN : -{ - -} - -void Input() : {} -{ - (ModuleDefinition())* -} - -void ModuleDefinition() : {} -{ - ModuleIdentifier() [TagDefault()] ModuleBody() -} - -void TagDefault() : {} -{ - ( | ) -} - -void ModuleIdentifier() : { } -{ - modulereference() [AssignedIdentifier()] -} - -void AssignedIdentifier() : {} -{ - ObjectIdentifierValue() -} - -void ModuleBody() : {} -{ - [Exports()] [Imports()] [AssignmentList()] -} - -void Exports() : {} -{ - [SymbolsExported()] -} - -void SymbolsExported() : {} -{ - ExportSymbolList() -} - -void ExportSymbolList() : {} -{ - Symbol() ( Symbol())* -} - -void Imports() : {} -{ - [SymbolsImported()] -} - -void SymbolsImported() : {} -{ - SymbolsFromModuleList() -} - -void SymbolsFromModuleList() : {} -{ - SymbolsFromModule() (SymbolsFromModule())* -} - -void SymbolsFromModule() : { String module; } -{ - SymbolList() ModuleIdentifier() -} - -void SymbolList() : {} -{ - Symbol() ( Symbol())* -} - -void Symbol() : {} -{ - typereference() - | identifier() - | DefinedMacroName() -} - -void AssignmentList() : {} -{ - Assignment() [] ( Assignment() [] )* -} - -void Assignment() : {} -{ - LOOKAHEAD(2) MacroDefinition() | TypeAssignment() | ValueAssignment() -} - -void MacroDefinition() : { } -{ - ( | | typereference()) - MacroBody() -} - -JAVACODE -void MacroBody() { - Token tok; - int nesting = 1; - while (true) { - tok = getToken(1); - if (tok.kind == END_TKN) { - break; - } - tok = getNextToken(); - } -} - -void MacroReference() : {} -{ - typereference() | DefinedMacroName() -} - -void TypeAssignment() : { } -{ - typereference() GlobalType() -} - -void GlobalType() : { } -{ - Type() | DefinedMacroType() -} - -void Type() : { } -{ - (LOOKAHEAD(2) BuiltinType() | DefinedType()) [LOOKAHEAD(2) SubtypeSpec()] -} - -void DefinedType() : { } -{ - [LOOKAHEAD(2) modulereference() ] typereference() -} - -void BuiltinType() : {} -{ - IntegerType() -| BitStringType() -| LOOKAHEAD(2) SetOrSequenceType() -| SetOrSequenceOfType() -| ChoiceType() -| SelectionType() -| TaggedType() -| AnyType() -| EnumeratedType() -| -| -| -| -| -| -} - -void EnumeratedType() : {} -{ - NamedNumberList() -} - -void IntegerType() : {} -{ - [ NamedNumberList() ] -} - -void BitStringType() : {} -{ - [ NamedNumberList() ] -} - -void NamedNumberList() : { } -{ - NamedNumber() ( NamedNumber())* -} - -void NamedNumber() : { } -{ - identifier() ( SignedNumber() | DefinedValue()) - -} - -void SignedNumber() : { } -{ - [ ] ( | ) -} - -void SetOrSequenceOfType() : { } -{ - ( | ) [[] SizeConstraint() []] - Type() -} - -void SetOrSequenceType() : { } -{ - ( | ) [ ElementTypeList() ] -} - -void ChoiceType() : { } -{ - ElementTypeList() -} - -void ElementTypeList() : {} -{ - ElementType() ( ElementType())* -} - -void ElementType() : {} -{ - ( NamedType() [ ( ) | ( NamedValue() ) ] ) -| ComponentsType() -} - -void ComponentsType() : { } -{ - Type() - -} - -void NamedType() : { } -{ - [LOOKAHEAD(2) identifier()] Type() -} - -void SelectionType() : {} -{ - identifier() Type() -} - -void TaggedType() : { } -{ - Tag() [ | ] Type() -} - -void Tag() : {} -{ - [Class()] ClassNumber() -} - -void ClassNumber() : {} -{ - number() | DefinedValue() -} - -void Class() : {} -{ - | | -} - -void AnyType() : {} -{ - - [ identifier() ] -} - -void SubtypeSpec() : {} -{ - SubtypeValueSetList() -} - -void SubtypeValueSetList() : {} -{ - SubtypeValueSet() ( SubtypeValueSet())* -} - -void SubtypeValueSet() : {} -{ - ( - ValueRange() | ContainedSubtype() | PermittedAlphabet() | SizeConstraint() | InnerTypeConstraints() ) -} - - -void ContainedSubtype() : {} -{ - Type() -} - -void SingleValue() : {} -{ - Value() -} - -void ValueRange() : {} -{ - ( Value() | ) [ [ ] [ ] (Value() | ) ] -} - -void SizeConstraint() : {} -{ - SubtypeSpec() -} - -void PermittedAlphabet() : {} -{ - SubtypeSpec() -} - -void InnerTypeConstraints() : {} -{ - (( SingleTypeConstraint() ) | ( MultipleTypeConstraints())) -} - -void SingleTypeConstraint() : {} -{ - SubtypeSpec() -} - -void MultipleTypeConstraints() : {} -{ - [ ] TypeConstraints() -} - -void TypeConstraints() : {} -{ - NamedConstraint() ( NamedConstraint())* -} - -void NamedConstraint() : {} -{ - [identifier() ] Constraint() -} - -void Constraint() : {} -{ - [ValueConstraint()] [PresenceConstraint()] -} - -void ValueConstraint() : {} -{ - SubtypeSpec() -} - -void PresenceConstraint() : {} -{ - | | -} - - - -void ValueAssignment() : { } -{ - identifier() - GlobalType() [ LOOKAHEAD(2) identifier() [] ] [ BuiltinValue() ] - -} - -void Value() : {} -{ - LOOKAHEAD(2) BuiltinValue() | DefinedValue() -} - -void DefinedValue() : {} -{ - [ modulereference() ] identifier() -} - -void BuiltinValue() : {} -{ - BooleanValue() -| NullValue() -| SpecialRealValue() -| SignedNumber() -| HexString() -| BinaryString() -| CharString() -| CompoundValue() -} - -void CompoundValue() : {} -{ - ( ObjIdComponentList() | skip_to_matching_brace() ) -} - -JAVACODE -void skip_to_matching_brace() { - Token tok; - int nesting = 1; - while (true) { - tok = getToken(1); - if (tok.kind == LEFTBRACE_TKN) nesting++; - if (tok.kind == RIGHTBRACE_TKN) { - nesting--; - if (nesting == 0) break; - } - tok = getNextToken(); - } -} - -void BooleanValue() : {} -{ - | -} - -void SpecialRealValue() : {} -{ - | -} - -void NullValue() : {} -{ - -} - -void NamedValue() : {} -{ - [ LOOKAHEAD(2) identifier() ] Value() -} - -void ObjectIdentifierValue() : {} -{ - ObjIdComponentList() -} - -void ObjIdComponentList() : {} -{ - ObjIdComponent() (ObjIdComponent())* -} - -void ObjIdComponent() : {} -{ - ( NumberForm() | NameAndNumberForm()) -} - -void NumberForm() : {} -{ - number() -} - - -void NameAndNumberForm() : {} -{ - identifier() [ (NumberForm() | DefinedValue()) ] -} - -void BinaryString() : {} -{ - -} - -void HexString() : {} -{ - -} - -void CharString() : {} -{ - -} - -void number() : { } -{ - | -} - -void identifier() : {} -{ - -} - -void modulereference() : {} -{ - -} - -void typereference() : {} -{ - -} - -void DefinedMacroType() : {} -{ - TextualConventionMacroType() -| SnmpObjectTypeMacroType() -} - -void DefinedMacroName() : {} -{ - -| -} - -void SnmpObjectTypeMacroType() : {} -{ - Type() SnmpAccess() SnmpStatus() [SnmpDescrPart()] [SnmpReferPart()] - [SnmpIndexPart()] [SnmpDefValPart()] -} - -void SnmpAccess() : {} -{ - identifier() -} - -void SnmpStatus() : {} -{ - identifier() -} - -void SnmpDescrPart() : {} -{ - -} - -void SnmpReferPart() : {} -{ - -} - -void SnmpIndexPart() : {} -{ - TypeOrValueList() -} - -void TypeOrValueList() : {} -{ - TypeOrValue() ( TypeOrValue())* -} - -void TypeOrValue() : {} -{ - LOOKAHEAD(3) Type() | Value() -} - -void SnmpDefValPart() : {} -{ - Value() -} - -void TextualConventionMacroType() : {} -{ - [DisplayHint()] SnmpStatus() [SnmpDescrPart()] [SnmpReferPart()] Type() -} - -void DisplayHint() : {} -{ - -} diff --git a/grammars/c/main.c b/grammars/c/main.c deleted file mode 100644 index ea59fc4..0000000 --- a/grammars/c/main.c +++ /dev/null @@ -1,3 +0,0 @@ -int main(int argc, char** argv) { - return 0; -} diff --git a/grammars/c/pom.xml b/grammars/c/pom.xml deleted file mode 100644 index cd40ad8..0000000 --- a/grammars/c/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - 1.1.0-SNAPSHOT - grammars - - - org.javacc.generator.java.grammars - c - jar - - JavaCC Java code generator / grammars / c - - - - - - org.codehaus.mojo - exec-maven-plugin - - - test - - java - - - - - CParser - - ${project.basedir}/main.c - - - - - - - \ No newline at end of file diff --git a/grammars/c/src/main/javacc/CParser.jj b/grammars/c/src/main/javacc/CParser.jj deleted file mode 100644 index 5aced75..0000000 --- a/grammars/c/src/main/javacc/CParser.jj +++ /dev/null @@ -1,599 +0,0 @@ -/* - - C grammar defintion for use with JavaCC - Contributed by Doug South (dsouth@squirrel.com.au) 21/3/97 - - This parser assumes that the C source file has been preprocessed : all - #includes have been included and all macros have been expanded. I accomplish - this with "gcc -P -E > ". - - There is a problem with compiler specific types, such as __signed, __const, - __inline__, etc. These types can be added as typedef types before the parser - is run on a file. See main() for an example. I have also found a strange little - compiler specific "type" if you can call it that. It is __attribute__, but it - does not seem to be used as a type. I found that just deleting the __attribute__ - and the following "offensive" code works. - - This grammar also prints out all the types defined while parsing the file. This - is done via a call to printTypes() when the parser is complete. If you do not want - this, just comment out the printTypes() method call in the production rule - TranslationUnit(), which BTW is the root node for parsing a C source file. - - I have not in anyway extensively tested this grammar, in fact it is barely tested, - but I imagine it is better to have a starting point for a C grammar other than from - scratch. It has not been optimized in anyway, my main aim was to get a parser that - works. Lookahead may not be optimum at choice points and may even be insufficient at - times. I choose to err on the side of not optimum if I made a choice at all. - - If you use this grammar, I would appreciate hearing from you. I will try to maintain - this grammar to the best of my ability, but at this point in time, this is only a side - hobby (unless someone wants to pay me for doing JavaCC work!). In that regards, I am - interested in hearing bugs and comments. - - TODO: - - Insert the appropriate code to enable C source trees from this grammar. - -============================================= -3/2/06: Modified by Tom Copeland -- STRING_LITERAL now handles embedded escaped newlines, thanks to J.Chris Findlay for the patch -- Works with JavaCC 4.0 -- Preprocessor directives are now simply SKIP'd, so no need to run C files through GCC first - - */ -options { - DEBUG_PARSER=true; -} -PARSER_BEGIN(CParser) - -import java.util.*; - - public class CParser{ - - // Hastable for storing typedef types - private static Set types = new HashSet(); - - // Stack for determining when the parser - // is parsing a typdef definition. - private static Stack typedefParsingStack = new Stack(); - - // Returns true if the given string is - // a typedef type. - private static boolean isType(String type){ - return types.contains(type); - } - - // Add a typedef type to those already defined - private static void addType(String type){ - types.add(type); - } - - // Prints out all the types used in parsing the c source - private static void printTypes(){ - for (Iterator i = types.iterator(); i.hasNext();) { - System.out.println(i.next()); - } - } - - // Run the parser - public static void main ( String args [ ] ) { - CParser parser ; - - // Hack to include type "special types" - types.add("__signed__"); - types.add("__const"); - types.add("__inline__"); - types.add("__signed"); - - if(args.length == 0){ - System.out.println("C Parser Version 0.1Alpha: Reading from standard input . . ."); - parser = new CParser(System.in); - } - else if(args.length == 1){ - System.out.println("C Parser Version 0.1Alpha: Reading from file " + args[0] + " . . ." ); - try { - parser = new CParser(new java.io.FileInputStream(args[0])); - } - catch(java.io.FileNotFoundException e){ - System.out.println("C Parser Version 0.1: File " + args[0] + " not found."); - return ; - } - } - else { - System.out.println("C Parser Version 0.1Alpha: Usage is one of:"); - System.out.println(" java CParser < inputfile"); - System.out.println("OR"); - System.out.println(" java CParser inputfile"); - return ; - } - try { - parser.TranslationUnit(); - System.out.println("C Parser Version 0.1Alpha: Java program parsed successfully."); - } - catch(ParseException e){ - System.out.println("C Parser Version 0.1Alpha: Encountered errors during parse."); - e.printStackTrace(); - } - } - } - -PARSER_END(CParser) - -SKIP : { - " " -| "\t" -| "\n" -| "\r" -| <"//" (~["\n","\r"])* ("\n" | "\r" | "\r\n")> -| <"/*" (~["*"])* "*" ("*" | ~["*","/"] (~["*"])* "*")* "/"> -| "#" : PREPROCESSOR_OUTPUT -} - - SKIP: -{ - "\n" : DEFAULT -} - - MORE: -{ - "\\\n" - | - "\\\r\n" - | - < ~[] > -} - - -TOKEN : { - (["l","L"])? | (["l","L"])? | (["l","L"])?> -| <#DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])*> -| <#HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+> -| <#OCTAL_LITERAL: "0" (["0"-"7"])*> -| )? (["f","F","d","D"])? | "." (["0"-"9"])+ ()? (["f","F","d","D"])? | (["0"-"9"])+ (["f","F","d","D"])? | (["0"-"9"])+ ()? ["f","F","d","D"]> -| <#EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+> -| -| -} - -TOKEN : { - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - -} - -TOKEN : { - ( | )*> -| <#LETTER: ["$","A"-"Z","_","a"-"z"]> -| <#DIGIT: ["0"-"9"]> -} - -void TranslationUnit() : {} -{ - (ExternalDeclaration())+ - {printTypes();} -} - -void ExternalDeclaration() : {} -{ - ( LOOKAHEAD( FunctionDefinition() ) FunctionDefinition() | Declaration()) -} - -void FunctionDefinition() : {} -{ - [LOOKAHEAD(DeclarationSpecifiers()) DeclarationSpecifiers()] Declarator() [ DeclarationList() ] - CompoundStatement() -} - -void Declaration() : {} -{ - DeclarationSpecifiers() [ InitDeclaratorList() ] ";" -} - -void DeclarationList() : {} -{ - ( LOOKAHEAD(Declaration()) Declaration() )+ -} - -void DeclarationSpecifiers() : {} -{ - StorageClassSpecifier() [ LOOKAHEAD(DeclarationSpecifiers()) - DeclarationSpecifiers() ] | - TypeSpecifier() [ LOOKAHEAD(DeclarationSpecifiers()) - DeclarationSpecifiers() ] | - TypeQualifier() [ LOOKAHEAD(DeclarationSpecifiers()) - DeclarationSpecifiers() ] -} - -void StorageClassSpecifier() : {} -{ - ( | | | | - { - typedefParsingStack.push(Boolean.TRUE); - } ) -} - -void TypeSpecifier() : {} -{ - ( | | | | | | | | - | StructOrUnionSpecifier() | EnumSpecifier() | LOOKAHEAD( { isType(getToken(1).image) } )TypedefName() ) -} - -void TypeQualifier() : {} -{ - ( | ) -} - -void StructOrUnionSpecifier() : {} -{ - { - typedefParsingStack.push(Boolean.FALSE); - } - - StructOrUnion() ( LOOKAHEAD(3) [ ] "{" StructDeclarationList() "}" | ) - - { - typedefParsingStack.pop(); - } -} - -void StructOrUnion() : {} -{ - ( | ) -} - -void StructDeclarationList() : {} -{ - (StructDeclaration())+ -} - -void InitDeclaratorList() : {} -{ - InitDeclarator() ("," InitDeclarator())* - { - // Finished with a typedefDeclaration?? - if(!(typedefParsingStack.empty()) && ((Boolean)typedefParsingStack.peek()).booleanValue()){ - typedefParsingStack.pop(); - } - } -} - -void InitDeclarator() : {} -{ - Declarator() [ "=" Initializer() ] -} - -void StructDeclaration() : {} -{ - SpecifierQualifierList() StructDeclaratorList() ";" -} - -void SpecifierQualifierList() : {} -{ - TypeSpecifier() [ LOOKAHEAD(SpecifierQualifierList()) - SpecifierQualifierList() ]| - TypeQualifier() [ LOOKAHEAD(SpecifierQualifierList()) - SpecifierQualifierList() ] -} - -void StructDeclaratorList() : {} -{ - StructDeclarator() ( "," StructDeclarator() )* -} - -void StructDeclarator() : {} -{ - ( LOOKAHEAD(3) Declarator() | [ Declarator() ] ":" ConstantExpression() ) -} - -void EnumSpecifier() : {} -{ - ( LOOKAHEAD(3) [ ] "{" EnumeratorList() "}" | ) -} - -void EnumeratorList() : {} -{ - Enumerator() ("," Enumerator())* -} - -void Enumerator() : {} -{ - [ "=" ConstantExpression() ] -} - -void Declarator() : {} -{ - [ Pointer() ] DirectDeclarator() -} - -void DirectDeclarator() : { Token t;} -{ - ( t = - - { if(!(typedefParsingStack.empty()) && ((Boolean)typedefParsingStack.peek()).booleanValue()){ - addType(t.image); - } - } - | "(" Declarator() ")" ) - - { typedefParsingStack.push( Boolean.FALSE ); } - - ( "[" [ ConstantExpression() ] "]" | - LOOKAHEAD(3) "(" ParameterTypeList() ")" | - "(" [ IdentifierList() ] ")" )* - { typedefParsingStack.pop(); } -} - -void Pointer() : {} -{ - "*" [ TypeQualifierList() ] [ Pointer() ] -} - -void TypeQualifierList() : {} -{ - (TypeQualifier())+ -} - -void ParameterTypeList() : {} -{ - ParameterList() ["," "..." ] -} - -void ParameterList() : {} -{ - ParameterDeclaration() (LOOKAHEAD(2) "," ParameterDeclaration())* -} - -void ParameterDeclaration() : {} -{ - DeclarationSpecifiers() ( LOOKAHEAD(Declarator()) Declarator() | [ AbstractDeclarator() ] ) -} - -void IdentifierList() : {} -{ - ("," )* -} - -void Initializer() : {} -{ - ( AssignmentExpression() | - "{" InitializerList() [","] "}" ) -} - -void InitializerList() : {} -{ - Initializer() (LOOKAHEAD(2) "," Initializer())* -} - -void TypeName() : {} -{ - SpecifierQualifierList() [ AbstractDeclarator() ] - -} - -void AbstractDeclarator() : {} -{ - ( LOOKAHEAD(3) Pointer() | - [Pointer()] DirectAbstractDeclarator() ) -} - -void DirectAbstractDeclarator() : {} -{ - ( LOOKAHEAD(2) "(" AbstractDeclarator() ")" | - "[" [ConstantExpression()] "]" | - "(" [ParameterTypeList()] ")" ) - - ( "[" [ ConstantExpression() ] "]" | "(" [ ParameterTypeList() ] ")" )* -} - -void TypedefName() : {} -{ - -} - -void Statement() : {} -{ - ( LOOKAHEAD(2) LabeledStatement() | - ExpressionStatement() | - CompoundStatement() | - SelectionStatement() | - IterationStatement() | - JumpStatement() ) -} - -void LabeledStatement() : {} -{ - ( ":" Statement() | - ConstantExpression() ":" Statement() | - ":" Statement() ) -} - -void ExpressionStatement() : {} -{ - [ Expression() ] ";" -} - -void CompoundStatement() : {} -{ - "{" [ LOOKAHEAD(DeclarationList()) DeclarationList() ] - [ StatementList() ] - "}" -} - -void StatementList() : {} -{ - (Statement())+ -} - -void SelectionStatement() : {} -{ - ( "(" Expression() ")" Statement() [ LOOKAHEAD(2) Statement() ] | - "(" Expression() ")" Statement() ) -} - -void IterationStatement() : {} -{ - ( "(" Expression() ")" Statement() | - Statement() "(" Expression() ")" ";" | - "(" [ Expression() ] ";" [ Expression() ] ";" [ Expression() ] ")" Statement() ) -} - -void JumpStatement() : {} -{ - ( ";" | - ";" | - ";" | - [ Expression() ] ";" ) -} - -void Expression() : {} -{ - AssignmentExpression() ( "," AssignmentExpression() )* -} - -void AssignmentExpression() : {} -{ - LOOKAHEAD(UnaryExpression() AssignmentOperator()) UnaryExpression() AssignmentOperator() AssignmentExpression() | - LOOKAHEAD(3) ConditionalExpression() -} - -void AssignmentOperator() : {} -{ - ( "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | "&=" | "^=" | "|=" ) -} - -void ConditionalExpression() : {} -{ - LogicalORExpression() [ "?" Expression() ":" ConditionalExpression() ] -} - -void ConstantExpression() : {} -{ - ConditionalExpression() -} - -void LogicalORExpression() : {} -{ - LogicalANDExpression() [ "||" LogicalORExpression() ] -} - -void LogicalANDExpression() : {} -{ - InclusiveORExpression() [ "&&" LogicalANDExpression() ] -} - -void InclusiveORExpression() : {} -{ - ExclusiveORExpression() [ "|" InclusiveORExpression() ] -} - -void ExclusiveORExpression() : {} -{ - ANDExpression() [ "^" ExclusiveORExpression() ] -} - -void ANDExpression() : {} -{ - EqualityExpression() [ "&" ANDExpression() ] -} - -void EqualityExpression() : {} -{ - RelationalExpression() [ ( "==" | "!=" ) EqualityExpression() ] -} - -void RelationalExpression() : {} -{ - ShiftExpression() [ ( "<" | ">" | "<=" | ">=" ) RelationalExpression() ] -} - -void ShiftExpression() : {} -{ - AdditiveExpression() [ ( "<<" | ">>" ) ShiftExpression() ] -} - -void AdditiveExpression() : {} -{ - MultiplicativeExpression() [ ( "+" | "-" ) AdditiveExpression() ] -} - -void MultiplicativeExpression() : {} -{ - CastExpression() [ ( "*" | "/" | "%" ) MultiplicativeExpression() ] -} - -void CastExpression() : {} -{ - ( LOOKAHEAD("(" TypeName() ")" CastExpression() ) "(" TypeName() ")" CastExpression() | - UnaryExpression() ) -} - -void UnaryExpression() : {} -{ - ( LOOKAHEAD(3) PostfixExpression() | - "++" UnaryExpression() | - "--" UnaryExpression() | - UnaryOperator() CastExpression() | - ( LOOKAHEAD(UnaryExpression() ) UnaryExpression() | "(" TypeName() ")" ) ) -} - -void UnaryOperator() : {} -{ - ( "&" | "*" | "+" | "-" | "~" | "!" ) -} - -void PostfixExpression() : {} -{ - PrimaryExpression() ( "[" Expression() "]" | - "(" [ LOOKAHEAD(ArgumentExpressionList() ) ArgumentExpressionList() ] ")" | - "." | - "->" | - "++" | - "--" )* -} - -void PrimaryExpression() : {} -{ - ( | - Constant() | - "(" Expression() ")" ) -} - -void ArgumentExpressionList() : {} -{ - AssignmentExpression() ( "," AssignmentExpression() )* -} - -void Constant() : {} -{ - | | | -} - diff --git a/grammars/chemical/pom.xml b/grammars/chemical/pom.xml deleted file mode 100644 index 0f73380..0000000 --- a/grammars/chemical/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - grammars - 1.1.0-SNAPSHOT - - - org.javacc.generator.java.grammars - chemical - jar - - JavaCC Java code generator / grammars / chemical - - \ No newline at end of file diff --git a/grammars/chemical/src/main/javacc/ChemNumber.jj b/grammars/chemical/src/main/javacc/ChemNumber.jj deleted file mode 100644 index a338ac7..0000000 --- a/grammars/chemical/src/main/javacc/ChemNumber.jj +++ /dev/null @@ -1,174 +0,0 @@ -options { - STATIC=false; - OPTIMIZE_TOKEN_MANAGER=true; - FORCE_LA_CHECK=true; -} - -PARSER_BEGIN(ChemNumber) - -import java.io.StringReader; - -/** - * A class partly generated by JavaCC which translates - * ancient greek style "prefixs" to an integer. - * - * Released under the LGPL by the University of Manchester 2003 - * - * @author Stephen Tomkinson - */ -public class ChemNumber { - private static int currentNumber; - - /** - * Converts the ancient greek style "prefix" string into an int. - * - * @throws ParseException Any error which occur in the parsing get wrapped - * up in a ParseException and thrown. - */ - public static int fromString (String stringToParse) throws ParseException - { - currentNumber = 0; - - StringReader stringReader = new StringReader (stringToParse.toLowerCase() + "\n"); - ChemNumber parser = new ChemNumber (stringReader); - parser.wholeNumber(); - - return currentNumber; - } - - /** - * A very basic usage of the program in which the first argument from the command line gets - * translated and printed out. - */ - public static void main (String args[]) - { - try - { - System.out.println ("Returned: " + fromString(args[0])); - } - catch (Throwable t) - { - System.out.println (t); - } - } -} - -PARSER_END(ChemNumber) - -/** - * The obligatory EOL character. - */ -TOKEN : -{ - < EOL: "\n" > -} - -/** - * Initial small numbers. - */ -TOKEN : -{ - < METH: "meth" > -| < ETH: "eth" > -| < PROP: "prop" > -| < BUT: "but" > -} - -/** - * Other special cases. - */ -TOKEN : -{ - < UNDEC: "undec" > -| < EICOS: "eicos" | "icos" > -| < HENICOS: "henicos" > -} - -/** - * Usual numbers for base 10 numbering. - */ -TOKEN : -{ - < HEN: "hen" > -| < DO: "do" > -| < TRI: "tri" > -| < TETR: "tetra" > -| < PENT: "pent" > -| < HEX: "hex" > -| < HEPT: "hept" > -| < OCT: "oct" > -| < NON: "non" > -} - -/** - * Positional aides which give the magnitude of the the base numbers. - * Equivalent to "...ty" and "...hundred" in English. - */ -TOKEN : -{ - < DEC: "dec" > -| < COS: "cos" > -| < CONT: "cont" > -} - -/** Skip the "a" letter for greek numbers since the rules for when to use an "a" are very complicated. */ -SKIP : -{ - < A : "a" > -} - -/** The build up of a complete number from 1 - 99 */ -void wholeNumber() : -{} -{ - ( specialCase() | allBaseNumbers() [tensWithUnits() | tensNoUnits()] ) - -} - -/** Deal with special cases where the rules don't apply. */ -void specialCase() : -{} -{ - < METH > {currentNumber = 1;} -| < ETH > {currentNumber = 2;} -| < PROP > {currentNumber = 3;} -| < BUT > {currentNumber = 4;} -| < UNDEC > {currentNumber = 11;} -| < EICOS > {currentNumber = 20;} -| < HENICOS > {currentNumber = 21;} -} - -/** The usual numbers .*/ -void allBaseNumbers() : -{} -{ - < HEN > {currentNumber = 1;} -| < DO > {currentNumber = 2;} -| < TRI > {currentNumber = 3;} -| < TETR > {currentNumber = 4;} -| < PENT > {currentNumber = 5;} -| < HEX > {currentNumber = 6;} -| < HEPT > {currentNumber = 7;} -| < OCT > {currentNumber = 8;} -| < NON > {currentNumber = 9;} -} - -/** Deal with fragments referring to the positioning of the base numbers (denoting their magnitude) */ -void tensNoUnits() : -{} -{ - { currentNumber += 10; } -| { currentNumber += 20; } -| { currentNumber *= 10; } -} - -/** Deals with numbers above 30 where the base numbers set appear twice, i.e. in the tens and the units. */ -void tensWithUnits() : -{ - int tempBackup; -} -{ - { tempBackup = currentNumber; } - allBaseNumbers() - { currentNumber *= 10; currentNumber += tempBackup; } -} diff --git a/grammars/cobol/pom.xml b/grammars/cobol/pom.xml deleted file mode 100644 index c17d06b..0000000 --- a/grammars/cobol/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - 4.0.0 - - - org.javacc.generator.java - 1.1.0-SNAPSHOT - grammars - - - org.javacc.generator.java.grammars - cobol - jar - - JavaCC Java code generator / grammars / cobol - - - - - - org.codehaus.mojo - exec-maven-plugin - - - test - - java - - - - - CobolParser - - ${project.basedir}/src/main/test/VARS.cob - - - - - - - \ No newline at end of file diff --git a/grammars/cobol/src/main/javacc/Cobol.jj b/grammars/cobol/src/main/javacc/Cobol.jj deleted file mode 100644 index 97b073c..0000000 --- a/grammars/cobol/src/main/javacc/Cobol.jj +++ /dev/null @@ -1,2882 +0,0 @@ -/** - * This is an experimental COBOL-85 grammar for JavaCC. - *

References used for this grammar : - *

    - *
  1. Ralf Lämmel & Chris Verhoef : VS COBOL II grammar Version 1.0.3 - *
  2. Fujitsu Cobol compiler reference - *
  3. Compaq-HP Non-stop Cobol reference - *
- *

This grammar is released under the GNU Library Public License (LGPL). - *

Bernard Pinon, august 2002
- *

Thierry Blind, september 2009
- * @see http://www.gnu.org/licenses/lgpl.html - * @see http://www.cwi.nl/ - * @see http://www.wins.uva.nl/ - * @author Thierry Blind (initial work from Bernard Pinon) - * @author Marc Mazas - * - *

History: - *

    - *
  • 9-aug-2002 [BP] make changes to comply with JTB : - *
      - *
    1. Changed Integer() to IntegerConstant() to avoid conflicts with java.lang.Integer - *
    2. Removed Java code to make the grammar bare bone - *
    3. Fixed Identification Division entries - *
    - *
  • 8-aug-2002 [BP] fixed several bugs : - *
      - *
    1. INSTALLATION section - *
    2. wrong spelling in keywords - *
    3. DOT missing in FD/SD entries - *
    4. wrong regular expressions for levels - *
    5. possibility to have repeated string literals, e.g. "AA" "BB" -> "AABB" - *
    6. optimized data division by placing the most common clauses first - *
    7. DOT missing in exit statement - *
    8. confusion between Identifier and QualifiedDataName (to be checked) - *
    9. fixed NumericConstant to use Integer instead of INTEGER - *
    10. Correcting AdvancingPhrase so LINE is optional - *
    11. Fixed problems with abbreviated conditions - *
    12. Fixed Add statement - *
    - *
  • 01-sept-2009 : - *
      - *
    1. corrected picture values and enhanced linkage section - *
    2. corrected relational operators, arithmetic expressions and conditions - *
    3. corrected perform, evaluate and call clauses - *
    4. corrected cobol word, litteral, identifier, comment declarations - *
    5. created Iterables*() variants for some clauses - *
    6. added function support from cobol 2000 - *
    7. added LOOKAHEAD() instructions, with reorderings, to remove parser ambiguities - *
    8. ... and many many corrections, new clauses and new tokens relative to cobol 85 and (some from) cobol 2000 - *
    - *
  • mar-2025 : - *
      - *
    1. splitted MemoryUsage, for MSVC C++ compiler error C1061: compiler limit: blocks nested too deeply - *
    - *
- */ - -/** - * Cobol is not case sensitive. It is not LL(1) neither... - */ - -options { - IGNORE_CASE = true; - //FORCE_LA_CHECK = true; - LOOKAHEAD = 3; - //DEBUG_PARSER = true; - //DEBUG_LOOKAHEAD = true; - STATIC = false; -} - -/** - * The parser class. - */ - -PARSER_BEGIN(CobolParser) -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -public class CobolParser { - public static void main(String args[]) { - CobolParser parser; - if(args.length == 0){ - System.out.println("Cobol Parser: Reading from standard input . . ."); - parser = new CobolParser(System.in); - } - else - if(args.length == 1){ - System.out.println("Cobol Parser: Reading from file " + args[0] + " . . ." ); - try { - parser = new CobolParser(new FileInputStream(args[0])); - } catch(java.io.FileNotFoundException e) { - System.out.println("Cobol Parser: File " + args[0] + " not found."); - return ; - } - } else { - System.out.println("Cobol Parser: Usage is one of:"); - System.out.println(" java CParser < inputfile"); - System.out.println("OR"); - System.out.println(" java CParser inputfile"); - return ; - } - try { - parser.CompilationUnit(); - System.out.println("Cobol Parser: Cobol program parsed successfully."); - } catch(ParseException e){ - System.out.println("Cobol Parser: Encountered errors during parse."); - e.printStackTrace(); - } - } -} - -PARSER_END(CobolParser) - -//////////////////////////////////////////////////////////////////////////////// -// Lexical structure -//////////////////////////////////////////////////////////////////////////////// - -SPECIAL_TOKEN : -{ - < EOL: "\n" > -| < SPACECHAR: ( " " | "\t" | "\f" | ";" | "\r" )+ > -} - -SPECIAL_TOKEN : -{ - < COMMENT: ( "*>" | "|" ) (~["\n","\r"])* > -| < PREPROC_COMMENT: "*|" (~["\n","\r"])* > -| < SPACE_SEPARATOR : ( | )+ > -| < COMMA_SEPARATOR : "," > -} - -TOKEN : -{ - // TODO : Could be simplified by ? - < DOT : > -} - -//////////////////////////////////////////////////////////////////////////////// -// RESERVED WORDS. Looks like an excerpt of the dictionary of data processing. -// It is very hard to find significative identifiers in COBOL that are not -// reserved... -//////////////////////////////////////////////////////////////////////////////// - -TOKEN : -{ -/* A */ - < ACCEPT: "accept" > -| < ACCESS: "access" > -| < ADD: "add" > -| < ADDRESS: "address" > // extension to support pointers -| < ADVANCING: "advancing" > -| < AFTER: "after" > -| < ALL: "all" > -| < ALPHABET: "alphabet" > -| < ALPHABETIC: "alphabetic" > -| < ALPHABETIC_LOWER: "alphabetic-lower" > -| < ALPHABETIC_UPPER: "alphabetic-upper" > -| < ALPHANUMERIC: "alphanumeric" > -| < ALPHANUMERIC_EDITED: "alphanumeric-edited" > -| < ALSO: "also" > -| < ALTER: "alter" > -| < ALTERNATE: "alternate" > -| < AND: "and" > -| < ANY: "any" > -| < APPROXIMATE: "approximate" > // tandem extension -| < ARE: "are" > -| < AREA: "area" > -| < AREAS: "areas" > -| < ASCENDING: "ascending" > -| < ASSIGN: "assign" > -| < AT: "at" > -| < AUTHOR: "author" > -/* B */ -| < BEFORE: "before" > -| < BEGINNING: "beginning" > // extension -| < BINARY: "binary" > -| < BLANK: "blank" > -| < BLOCK: "block" > -| < BOTTOM: "bottom" > -| < BY: "by" > -/* C */ -| < CALL: "call" > -| < CALL_CONVENTION: "call-convention" > -| < CANCEL: "cancel" > -| < CD: "cd" > -| < CF: "cf" > -| < CH: "ch" > -| < CHARACTER: "character" > -| < CHARACTERS: "characters" > -| < CLASS: "class" > -| < CLOCK_UNITS: "clock-units" > -| < CLOSE: "close" > -//| < COBOL: "cobol" > -| < CODE: "code" > -| < CODE_SET: "code-set" > -| < COLLATING: "collating" > -| < COLUMN: "column" > -| < COMMA: "comma" > -| < COMMON: "common" > -| < COMMUNICATION: "communication" > -| < COMP: "comp" > -| < COMP_1: "comp-1" > // extension in many dialects -| < COMP_2: "comp-2" > // extension in many dialects -| < COMP_3: "comp-3" > // extension in many dialects -| < COMP_4: "comp-4" > // extension in many dialects -| < COMPUTATIONAL: "computational" > -| < COMPUTATIONAL_1: "computational-1" > // extension -| < COMPUTATIONAL_2: "computational-2" > // extension -| < COMPUTATIONAL_3: "computational-3" > // extension -| < COMPUTATIONAL_4: "computational-4" > // extension -| < COMPUTE: "compute" > -| < CONFIGURATION: "configuration" > -| < CONTAINS: "contains" > -| < CONTENT: "content" > -| < CONTINUE: "continue" > -| < CONTROL: "control" > -| < CONTROLS: "controls" > -| < CONVERTING: "converting" > -| < COPY: "copy" > -| < CORR: "corr" > -| < CORRESPONDING: "corresponding" > -| < COUNT: "count" > -| < CURRENCY: "currency" > -/* D */ -| < DATA: "data" > -| < DATE: "date" > -| < DATE_COMPILED: "date-compiled" > -| < DATE_WRITTEN: "date-written" > -| < DAY: "day" > -| < DAY_OF_WEEK: "day-of-week" > -| < DBCS: "dbcs" > // extension to support double bytes characters -| < DE: "de" > -| < DEBUG_CONTENTS: "debug-contents" > -| < DEBUG_ITEM: "debug-item" > -| < DEBUG_LINE: "debug-line" > -| < DEBUG_NAME: "debug-name" > -| < DEBUG_SUB_1: "debug-sub-1" > -| < DEBUG_SUB_2: "debug-sub-2" > -| < DEBUG_SUB_3: "debug-sub-3" > -| < DEBUGGING: "debugging" > -| < DECIMAL_POINT: "decimal-point" > -| < DECLARATIVES: "declaratives" > -| < DELETE: "delete" > -| < DELIMITED: "delimited" > -| < DELIMITER: "delimiter" > -| < DEPENDING: "depending" > -| < DESCENDING: "descending" > -| < DESCRIPTOR: "descriptor" > -| < DESTINATION: "destination" > -| < DETAIL: "detail" > -| < DISABLE: "disable" > -| < DISPLAY: "display" > -| < DISPLAY_1: "display-1" > // extension -| < DIVIDE: "divide" > -| < DIVISION: "division" > -| < DOWN: "down" > -| < DUPLICATES: "duplicates" > -| < DYNAMIC: "dynamic" > -/* E */ -| < EGCS: "egcs" > // extension -| < EGI: "egi" > -| < ELSE: "else" > -| < EMI: "emi" > -| < ENABLE: "enable" > -| < END: "end" > -| < END_ADD: "end-add" > -| < END_CALL: "end-call" > -| < END_COMPUTE: "end-compute" > -| < END_DELETE: "end-delete" > -| < END_DIVIDE: "end-divide" > -| < END_EVALUATE: "end-evaluate" > -| < END_IF: "end-if" > -| < END_MULTIPLY: "end-multiply" > -| < END_OF_PAGE: "end-of-page" > -| < END_PERFORM: "end-perform" > -| < END_READ: "end-read" > -| < END_RECEIVE: "end-receive" > -| < END_RETURN: "end-return" > -| < END_REWRITE: "end-rewrite" > -| < END_SEARCH: "end-search" > -| < END_START: "end-start" > -| < END_STRING: "end-string" > -| < END_SUBTRACT: "end-subtract" > -| < END_UNSTRING: "end-unstring" > -| < END_WRITE: "end-write" > -| < ENDING: "endinf" > -| < ENTER: "enter" > // not present in all COBOLs, use CALL instead -| < ENTRY: "entry" > -| < ENVIRONMENT: "environment" > -| < EOP: "eop" > -| < EQUAL: "equal" > -| < ERROR: "error" > -| < ESI: "esi" > -| < EVALUATE: "evaluate" > -| < EVERY: "every" > -| < EXCEPTION: "exception" > -/* | < EXCLUSIVE: "exclusive" > tandem extension */ -| < EXIT: "exit" > -| < EXTEND: "extend" > -| < EXTERNAL: "external" > -/* F */ -| < FALSE: "false" > -| < FD: "fd" > -| < FILE: "file" > -| < FILE_CONTROL: "file-control" > -| < FILLER: "filler" > -| < FINAL: "final" > -| < FIRST: "first" > -| < FOOTING: "footing" > -| < FOR: "for" > -| < FROM: "from" > -| < FUNCTION: "function" > -/* G */ -| < GENERATE: "generate" > -| < GOBACK: "goback" > // extension -| < GENERIC: "generic" > // tandem extension -| < GIVING: "giving" > -| < GLOBAL: "global" > -| < GO: "go" > -| < GREATER: "greater" > -| < GROUP: "group" > -/* H */ -| < HEADING: "heading" > -| < HIGH_VALUE: "high-value" > -| < HIGH_VALUES: "high-values" > -/* I */ -| < I_O: "i-o" > -| < I_O_CONTROL: "i-o-control" > -| < ID: "id" > // extension, synonym for IDENTIFICATION -| < IDENTIFICATION: "identification" > -| < IDENTIFIED: "identified" > -| < IF: "if" > -| < IMPLICIT: "implicit" > -| < IN: "in" > -| < INDEX: "index" > -| < INDEXED: "indexed" > -| < INDICATE: "indicate" > -| < INITIAL: "initial" > -| < INITIALIZE: "initialize" > -| < INITIATE: "initiate" > -| < INPUT: "input" > -| < INPUT_OUTPUT: "input-output" > -| < INSPECT: "inspect" > -| < INSTALLATION: "installation" > -| < INTO: "into" > -| < INVALID: "invalid" > -| < IS: "is" > -/* J */ -| < JUST: "just" > -| < JUSTIFIED: "justified" > -| < JUSTIFY: "justify" > -/* K */ -| < KANJI: "kanji" > // extension to support Kanji characters (japanese) -| < KEY: "key" > -/* L */ -| < LABEL: "label" > -| < LAST: "last" > -| < LEADING: "leading" > -| < LEFT: "left" > -| < LENGTH: "length" > -| < LESS: "less" > -| < LIMIT: "limit" > -| < LIMITS: "limits" > -| < LINAGE: "linage" > -| < LINAGE_COUNTER: "linage_counter" > -| < LINE: "line" > -| < LINES: "lines" > -| < LINE_COUNTER: "line-counter" > -| < LINKAGE: "linkage" > -| < LOCK: "lock" > -| < LOCKFILE: "lockfile" > // tandem extension -| < LOW_VALUE: "low-value" > -| < LOW_VALUES: "low-values" > -/* M */ -| < MEMORY: "memory" > -| < MERGE: "merge" > -| < MESSAGE: "message" > -| < MODE: "mode" > -| < MODULES: "modules" > -| < MORE_LABELS: "more-labels" > // IBM extension -| < MOVE: "move" > -| < MULTIPLE: "multiple" > -| < MULTIPLY: "multiply" > -/* N */ -| < NATIVE: "native" > -| < NEGATIVE: "negative" > -| < NEXT: "next" > -| < NO: "no" > -| < NOT: "not" > -| < NULL: "null" > // tandem & IBM extension -| < NULLS: "nulls" > // tandem & IBM extension -| < NUMBER: "number" > -| < NUMERIC: "numeric" > -| < NUMERIC_EDITED: "numeric-edited" > -/* O */ -| < OBJECT_COMPUTER: "object-computer" > -| < OCCURS: "occurs" > -| < OF: "of" > -| < OFF: "off" > -| < OMITTED: "omitted" > -| < ON: "on" > -| < OPEN: "open" > -| < OPTIONAL: "optional" > -| < OR: "or" > -| < ORDER: "order" > -| < ORGANIZATION: "organization" > -| < OTHER: "other" > -| < OUTPUT: "output" > -| < OVERFLOW: "overflow" > -/* P */ -| < PACKED_DECIMAL: "packed-decimal" > -| < PADDING: "padding" > -| < PAGE: "page" > -| < PAGE_COUNTER: "page-counter" > -| < PASSWORD: "password" > -| < PERFORM: "perform" > -| < PF: "pf" > -| < PH: "ph" > -| < PIC: "pic" > -| < PICTURE: "picture" > -| < PLUS: "plus" > -| < POINTER: "pointer" > -| < POSITION: "position" > -| < POSITIVE: "positive" > -| < PRINTING: "printing" > -| < PROCEDURE: "procedure" > -| < PROCEDURES: "procedures" > -| < PROCEDURE_POINTER: "procedure-pointer" > -| < PROCEED: "proceed" > -| < PROGRAM: "program" > -| < PROGRAM_ID: "program-id" > -| < PROGRAM_STATUS: "program-status" > // tandem extension -| < PROMPT: "prompt" > // tandem extension -| < PROTECTED: "protected" > // tandem extension -| < PURGE: "purge" > -/* Q */ -| < QUEUE: "queue" > -| < QUOTE: "quote" > -| < QUOTES: "quotes" > -/* R */ -| < RANDOM: "random" > -| < RD: "rd" > -| < READ: "read" > -| < RECEIVE: "receive" > -| < RECEIVE_CONTROL: "receive-control" > // tandem extension -| < RECORD: "record" > -| < RECORDING: "recording" > // probably IBM extension -| < RECORDS: "records" > -| < REDEFINES: "redefines" > -| < REEL: "reel" > -| < REFERENCE: "reference" > -| < REFERENCES: "references" > -| < RELATIVE: "relative" > -| < RELEASE: "release" > -| < REMAINDER: "remainder" > -| < REMOVAL: "removal" > -| < RENAMES: "renames" > -| < REPLACE: "replace" > -| < REPLACING: "replacing" > -| < REPLY: "reply" > // tandem extension -| < REPORT: "report" > -| < REPORTING: "reporting" > -| < REPORTS: "reports" > -| < RERUN: "rerun" > -| < RESERVE: "reserve" > -| < RESET: "reset" > -| < RETURN: "return" > // IBM extension - does not do what expected ;-) -| < RETURN_CODE: "return-code" > // special register IBM -| < RETURNED: "returned" > -| < RETURNING: "returning" > -| < REVERSED: "reversed" > -| < REWIND: "rewind" > -| < REWRITE: "rewrite" > -| < RF: "rf" > -| < RH: "rh" > -| < RIGHT: "right" > -| < ROUNDED: "rounded" > -| < RUN: "run" > -/* S */ -| < SAME: "same" > -| < SD: "sd" > -| < SEARCH: "search" > -| < SECTION: "section" > -| < SECURITY: "security" > -| < SEGMENT: "segment" > -| < SEGMENT_LIMIT: "segment-limit" > -| < SELECT: "select" > -| < SEND: "send" > -| < SENTENCE: "sentence" > -| < SEPARATE: "separate" > -| < SEQUENCE: "sequence" > -| < SEQUENTIAL: "sequential" > -| < SET: "set" > -| < SHARED: "shared" > // tandem extension, should be in C2000 -| < SHIFT_IN: "shift-in" > // IBM special register -| < SHIFT_OUT: "shift-out" > // IBM special register -| < SIGN: "sign" > -| < SIZE: "size" > -| < SORT: "sort" > -| < SORT_CONTROL: "sort-control" > // IBM special register -| < SORT_CORE_SIZE: "sort-core-size" > // IBM special register -| < SORT_FILE_SIZE: "sort-file-size" > // IBM special register -| < SORT_MERGE: "sort-merge" > -| < SORT_MESSAGE: "sort-message" > // IBM special register -| < SORT_MODE_SIZE: "sort-mode-size" > // IBM special register -| < SORT_RETURN: "sort-return" > // IBM special register -| < SOURCE: "source" > -| < SOURCE_COMPUTER: "source-computer" > -| < SPACE: "space" > -| < SPACES: "spaces" > -| < SPECIAL_NAMES: "special-names" > -| < STANDARD: "standard" > -| < STANDARD_1: "standard-1" > -| < STANDARD_2: "standard-2" > -| < START: "start" > -| < STATUS: "status" > -| < STDCALL: "stdcall" > -| < STOP: "stop" > -| < STRING: "string" > -| < SUB_QUEUE_1: "sub-queue-1" > -| < SUB_QUEUE_2: "sub-queue-2" > -| < SUB_QUEUE_3: "sub-queue-3" > -| < SUBTRACT: "subtract" > -| < SUM: "sum" > -| < SUPPRESS: "suppress" > -| < SYMBOLIC: "symbolic" > -| < SYNC: "sync" > -| < SYNCHRONIZED: "synchronized" > -/* T */ -| < TABLE: "table" > -| < TALLY: "tally" > // IBM special register -| < TALLYING: "tallying" > -| < TAPE: "tape" > -| < TERMINAL: "terminal" > -| < TERMINATE: "terminate" > -| < TEST: "test" > -| < TEXT: "text" > -| < THAN: "than" > -| < THEN: "then" > -| < THROUGH: "through" > -| < THRU: "thru" > -| < TIME: "time" > -| < TIMES: "times" > -| < TO: "to" > -| < TOP: "top" > -| < TRAILING: "trailing" > -| < TRUE: "true" > -| < TYPE: "type" > -/* U */ -| < UNIT: "unit" > -| < UNLOCK: "unlock" > // tandem extension -| < UNLOCKFILE: "unlockfile" > // tandem again -| < UNLOCKRECORD: "unlockrecord" > // guess what -| < UNSTRING: "unstring" > -| < UNTIL: "until" > -| < UP: "up" > -| < UPON: "upon" > -| < USAGE: "usage" > -| < USE: "use" > -| < USING: "using" > -/* V */ -| < VALUE: "value" > -| < VALUES: "values" > -| < VARYING: "varying" > -/* W */ -| < WHEN: "when" > -| < WHEN_COMPILED: "when-compiled" > // IBM special register -| < WITH: "with" > -| < WORDS: "words" > -| < WORKING_STORAGE: "working-storage" > -| < WRITE: "write" > -/* Z */ -| < ZERO: "zero" > -| < ZEROS: "zeros" > -| < ZEROES: "zeroes" > -/* Newly added */ -| < ALPHANUMERIC_HASHTABLE: "alphanumeric-hashtable" > -| < BINARY_BYTE: "binary-byte" > -| < BINARY_DOUBLE: "binary-double" > -| < BINARY_LONG: "binary-long" > -| < BINARY_M: "binary-m" > -| < BINARY_REV: "binary-rev" > -| < BINARY_SHORT: "binary-short" > -| < BIT: "bit" > -| < COMPONENT: "component" > -| < COMPUTATIONAL_2_A: "computational-2-a" > -| < COMPUTATIONAL_1_A: "computational-1-a" > -| < COMPUTATIONAL_1_E: "computational-1-e" > -| < COMPUTATIONAL_1_M: "computational-1-m" > -| < COMPUTATIONAL_1_MVS: "computational-1-mvs" > -| < COMPUTATIONAL_1_REV: "computational-1-rev" > -| < COMPUTATIONAL_2_E: "computational-2-e" > -| < COMPUTATIONAL_2_M: "computational-2-m" > -| < COMPUTATIONAL_2_MVS: "computational-2-mvs" > -| < COMPUTATIONAL_2_REV: "computational-2-rev" > -| < COMPUTATIONAL_3_A: "computational-3-a" > -| < COMPUTATIONAL_3_M: "computational-3-m" > -| < COMPUTATIONAL_4_M: "computational-4-m" > -| < COMPUTATIONAL_5: "computational-5" > -| < COMPUTATIONAL_5_M: "computational-5-m" > -| < COMPUTATIONAL_6: "computational-6" > -| < COMPUTATIONAL_A: "computational-a" > -| < COMPUTATIONAL_B: "computational-b" > -| < COMPUTATIONAL_D: "computational-d" > -| < COMPUTATIONAL_M: "computational-m" > -| < COMPUTATIONAL_N: "computational-n" > -| < COMPUTATIONAL_P: "computational-p" > -| < COMPUTATIONAL_S: "computational-s" > -| < COMPUTATIONAL_X: "computational-x" > -| < COMPUTATIONAL_X_REV: "computational-x-rev" > -| < COMP_1_A: "comp-1-a" > -| < COMP_1_E: "comp-1-e" > -| < COMP_1_M: "comp-1-m" > -| < COMP_1_MVS: "comp-1-mvs" > -| < COMP_1_REV: "comp-1-rev" > -| < COMP_2_A: "comp-2-a" > -| < COMP_2_E: "comp-2-e" > -| < COMP_2_M: "comp-2-m" > -| < COMP_2_MVS: "comp-2-mvs" > -| < COMP_2_REV: "comp-2-rev" > -| < COMP_3_A: "comp-3-a" > -| < COMP_3_M: "comp-3-m" > -| < COMP_4_M: "comp-4-m" > -| < COMP_5: "comp-5" > -| < COMP_5_M: "comp-5-m" > -| < COMP_6: "comp-6" > -| < COMP_A: "comp-a" > -| < COMP_B: "comp-b" > -| < COMP_D: "comp-d" > -| < COMP_M: "comp-m" > -| < COMP_N: "comp-n" > -| < COMP_P: "comp-p" > -| < COMP_S: "comp-s" > -| < COMP_X: "comp-x" > -| < COMP_X_REV: "comp-x-rev" > -| < DEFAULT_FONT: "default-font" > -| < DISPLAY_WS: "display-ws" > -| < DOUBLE: "double" > -| < EXTERNAL_FORM: "external-form" > -| < FIXED_FONT: "fixed-font" > -| < FLOAT: "float" > -| < FLOAT_LONG: "float-long" > -| < FLOAT_SHORT: "float-short" > -| < FONT: "font" > -| < HANDLE: "handle" > -| < JBOOLEAN: "jboolean" > -| < JBYTE: "jbyte" > -| < JCHAR: "jchar" > -| < JDOUBLE: "jdouble" > -| < JFLOAT: "jfloat" > -| < JINT: "jint" > -| < JLONG: "jlong" > -| < JPACKED_DECIMAL: "jpacked-decimal" > -| < JSHORT: "jshort" > -| < JSTRING: "jstring" > -| < LARGE_FONT: "large-font" > -| < MEDIUM_FONT: "medium-font" > -| < NATIONAL: "national" > -| < NUMERIC_HASHTABLE: "numeric-hashtable" > -| < OBJECT: "object" > -| < OBJECT_HASHTABLE: "object-hashtable" > -| < PACKED_DECIMAL_A: "packed-decimal-a" > -| < PACKED_DECIMAL_E: "packed-decimal-e" > -| < PACKED_DECIMAL_H: "packed-decimal-h" > -| < PACKED_DECIMAL_I: "packed-decimal-i" > -| < PACKED_DECIMAL_M: "packed-decimal-m" > -| < SIGNED_INT: "signed-int" > -| < SIGNED_LONG: "signed-long" > -| < SIGNED_SHORT: "signed-short" > -| < SMALL_FONT: "small-font" > -| < SQLIND: "sqlind" > -| < THREAD: "thread" > -| < TRADITIONAL_FONT: "traditional-font" > -| < UNSIGNED_INT: "unsigned-int" > -| < UNSIGNED_LONG: "unsigned-long" > -| < UNSIGNED_SHORT: "unsigned-short" > -| < WINDOW: "window" > -} - -TOKEN : -{ - < LEVEL_66: "66" > -| < LEVEL_77: "77" > -| < LEVEL_88: "88" > -| < LEVEL_NUMBER: ( (("0")? ["1"-"9"]) | (["1"-"4"]["0"-"9"]) | "78" ) > -| < INTEGER: (["0"-"9"])+ > -| < MINUSCHAR: "-" > // a.k.a. dash -| < LPARENCHAR: "(" > -| < RPARENCHAR: ")" > -| < COLONCHAR: ":" > -| < DOTCHAR: "." > -| < COMMACHAR: "," > -| < DOUBLEDQUOTECHAR: "\"\"" > -| < QUOTECHAR: "\"" > -| < DOUBLEDAPOSTROPHE: "''" > -| < APOSTROPHE: "'" > -| < PLUSCHAR: "+" > -| < ASTERISKCHAR: "*" > -| < POWEROF: "**" > -| < SLASHCHAR: "/" > -| < DOLLARCHAR: "$" > -| < LESSTHANOREQUAL: "<=" > -| < LESSTHANCHAR: "<" > -| < MORETHANOREQUAL: ">=" > -| < MORETHANCHAR: ">" > -| < EQUALCHAR: "=" > -| < NOTEQUAL: "<>" > -| < HEXNUMBER: ["h","x"] ( ( ( ["0"-"9","a"-"f"] )+ ) - | ( ( ["0"-"9","a"-"f"] )+ ) - ) - > -| < QUOTEDSTRING: ( (~["\""] | )* - | (~["'"] | )* - ) - > - // NB : COBOL_WORD can be defined as an INTEGER (or a LEVEL_66* or a LEVEL_NUMBER) too ! -| < COBOL_WORD: (["a"-"z","0"-"9"])+ ( ( | "_" )+ (["a"-"z","0"-"9"])+ )* > -| < OTHER_CHARS: ~[] > -} - -// Contains at least one alphabetic, max. 30 char -void CobolWord() : -{} -{ - -} - -void QuotedText() : -{} -{ - ( IterableQuotedText() )+ -} - -void IterableQuotedText() : -{} -{ - | | -} - -void IntegerConstant() : -{} -{ - | | | | -} - -void NumericConstant() : -{} -{ - [ | ] ( ( | ) IntegerConstant() | IntegerConstant() [ ( | ) IntegerConstant() ] ) -} - -void LevelNumber() : -{} -{ - -} - -void FigurativeConstant() : -{} -{ - | | - | | - | | - | | - | | - | | -} - -void NonNumericConstant() : -{} -{ - ( QuotedText() - | - ) -} - -void IterableNonNumericConstant() : -{} -{ - ( IterableQuotedText() - | - ) -} - -void Literal() : -{} -{ - [ ] ( NonNumericConstant() - | NumericConstant() - /* | */ - | FigurativeConstant() - ) -} - -void IterableLiteral() : -{} -{ - [ ] ( IterableNonNumericConstant() - | NumericConstant() - /* | */ - | FigurativeConstant() - ) -} - -//////////////////////////////////////////////////////////////////////////////// -// LOGICAL EXPRESSIONS (e.g. in IF statements) -// one of the nice feature of COBOL is to allow for abbeviated conditions -// such as : if X less than 100 and more than 10 then ... -//////////////////////////////////////////////////////////////////////////////// - -void IterableCondition() : -{} -{ - // TODO : This step was created because of the ambiguite of the rule ClassCondition() inside of RelationCondition() : - // CobolWord() CobolWord() === ArithmeticExpression() ClassCondition() - LOOKAHEAD(ArithmeticExpression()) - ArithmeticExpression() - | Condition() -} - -void Condition() : -{} -{ - CombinableCondition() ( ( | ) ( LOOKAHEAD(CombinableCondition()) CombinableCondition() | AbbreviationRest() ) )* -} - -void CombinableCondition() : -{} -{ - [ ] SimpleCondition() -} - -void SimpleCondition() : -{} -{ - LOOKAHEAD(RelationCondition()) - RelationCondition() - | LOOKAHEAD(ArithmeticExpression()) - ArithmeticExpression() - | Condition() -} - -void ClassCondition() : -{} -{ - [ ] [ ] ( | | | | ClassName() | | ) -} - -void RelationCondition() : -{} -{ - ArithmeticExpression() ( LOOKAHEAD(AbbreviationRest()) - AbbreviationRest() - | LOOKAHEAD(SignCondition()) - SignCondition() - | ClassCondition() - ) -} - -void SignCondition() : -{} -{ - [ ] [ ] ( | | | | ) -} - -void RelationalOperator() : -{} -{ - [ ] [ ] ( [ ] [ [ ] ] - | - | [ ] [ [ ] ] - | - | [ ] - | - | - | - | - ) -} - -void AbbreviationLeaf() : -{} -{ - LOOKAHEAD(ArithmeticExpression()) - ArithmeticExpression() - // TODO : Is there another abbreviation rule ? - | AbbreviationLeaf() ( AbbreviationLeaf() )+ -} - -void AbbreviationRest() : -{} -{ - RelationalOperator() AbbreviationLeaf() -} - -//////////////////////////////////////////////////////////////////////////////// -// VARIOUS TYPES OF IDENTIFIERS -//////////////////////////////////////////////////////////////////////////////// - -void ProcedureName() : -{} -{ - ( ParagraphName() [ ( | ) SectionName() ] - | SectionName() // Useless here ... - ) -} - -void Subscript() : -{} -{ - ( ArithmeticExpression() )+ -} - -void FunctionClause() : -{} -{ - FunctionName() [ LOOKAHEAD(Subscript()) Subscript() ] [ LeftmostCharacterPosition() [ Length() ] ] -} - -void Identifier() : -{} -{ - ( QualifiedDataName() ( LOOKAHEAD(Subscript()) Subscript() )* [ LeftmostCharacterPosition() [ Length() ] ] - | [ ( | ) FileName() ] - | - ) -} - -void QualifiedDataName() : -{} -{ - ( DataName() ( ( | ) DataName() )* - [ ( | ) FileName() ] // Useless part here ... - | SpecialRegister() // Useless here ... - ) -} - -void Length() : -{} -{ - ArithmeticExpression() -} - -void LeftmostCharacterPosition() : -{} -{ - ArithmeticExpression() -} - -void Mode() : -{} -{ - CobolWord() -} - -void AlphabetName() : -{} -{ - CobolWord() -} - -void ClassName() : -{} -{ - CobolWord() -} - -void ConditionName() : -{} -{ - CobolWord() -} - -void DataName() : -{} -{ - CobolWord() -} - -void FileName() : -{} -{ - CobolWord() -} - -void IndexName() : -{} -{ - CobolWord() -} - -void MnemonicName() : -{} -{ - CobolWord() -} - -void RecordName() : -{} -{ - Identifier() -} - -void RoutineName() : -{} -{ - CobolWord() -} - -void SymbolicCharacter() : -{} -{ - CobolWord() -} - -void LibraryName() : -{} -{ - CobolWord() -} - -void ProgramName() : -{} -{ - CobolWord() -} - -void SectionName() : -{} -{ - // We force IntegerConstant() recognization here ... - IntegerConstant() | CobolWord() -} - -void ParagraphName() : -{} -{ - // We force IntegerConstant() recognization here ... - IntegerConstant() | CobolWord() -} - -void SystemName() : -{} -{ - CobolWord() -} - -void ComputerName() : -{} -{ - SystemName() -} - -void LanguageName() : -{} -{ - SystemName() -} - -void EnvironmentName() : -{} -{ - SystemName() -} - -void AssignmentName() : -{} -{ - SystemName() -} - -void BasisName() : -{} -{ - ProgramName() -} - -void FunctionName() : -{} -{ - ( CobolWord() - | // To avoid conflicts with token having same name ... - | - | - | - ) -} - -void SpecialRegister() : -{} -{ - (
DataName() - | - | Identifier() - | - | - | - | - | - | - | - | - | - | - | - ) -} - -void CdName() : -{} -{ - CobolWord() -} - -void ConventionName() : -{} -{ - CobolWord() -} - -void HandleComponent() : -{} -{ - CobolWord() -} - -void ImplicitTitle() : -{} -{ - QuotedText() -} - -void LevelName66() : -{} -{ - DataName() -} - -void LevelName77() : -{} -{ - DataName() -} - -void LevelName88() : -{} -{ - ConditionName() -} - -void LevelName() : -{} -{ - [ DataName() | | | ] -} - -//////////////////////////////////////////////////////////////////////////////// -// ARITHMETIC -//////////////////////////////////////////////////////////////////////////////// - -void ArithmeticExpression() : -{} -{ - TimesDiv() ( ( | ) TimesDiv() )* -} - -void TimesDiv() : -{} -{ - Power() ( ( | ) Power() )* -} - -void Power() : -{} -{ - [ ( | ) ] Basis() ( Basis() )* -} - -void Basis() : -{} -{ - // IMPORTANT : From more complex to most specific : - // TODO : Dirty hack : is a valid value ? - ( FunctionClause() | Identifier() | Literal() | | ArithmeticExpression() ) -} - -void CommentLine() : -{} -{ - ( ( NonDotChars() | Literal() )+ [ ] )+ -} - -//////////////////////////////////////////////////////////////////////////////// -// COMPILATION UNIT. -//////////////////////////////////////////////////////////////////////////////// - -void CompilationUnit() : -{} -{ - ProgramUnit() - ( NestedProgramUnit() EndProgramStatement() )* - [ EndProgramStatement() ( CompilationUnit() )* ] - -} - -void ProgramUnit() : -{} -{ - IdentificationDivision() - [ EnvironmentDivision() ] - [ DataDivision() ] - [ ProcedureDivision() ] -} - -void NestedProgramUnit() : -{} -{ - NestedIdentificationDivision() - [ EnvironmentDivision() ] - [ DataDivision() ] - [ ProcedureDivision() ] -} - -void EndProgramStatement() : -{} -{ - ProgramName() -} - -void CopyBookUnit() : -{} -{ - LinkageSectionEntry() - -} - -//////////////////////////////////////////////////////////////////////////////// -// IDENTIFICATION DIVISION. -//////////////////////////////////////////////////////////////////////////////// - -void IdentificationDivision() : -{} -{ - ( | ) - ProgramIdParagraph() - ( IdentificationDivisionParagraph() )* -} - -void NestedIdentificationDivision() : -{} -{ - ( | ) - NestedProgramIdParagraph() - ( IdentificationDivisionParagraph() )* -} - -void IdentificationDivisionParagraph() : -{} -{ - AuthorParagraph() - | InstallationParagraph() - | DateWrittenParagraph() - | DateCompiledParagraph() - | SecurityParagraph() -} - -void ProgramIdParagraph() : -{} -{ - ProgramName() [ [ ] [ ] ] -} - -void NestedProgramIdParagraph() : -{} -{ - ProgramName() - [ [ ] InitialOrCommon() [ ] ] -} - -void InitialOrCommon() : -{} -{ - ( [ ] - | [ ] - ) -} - -void AuthorParagraph() : -{ /* System.out.println("Deprecated keyword : author - use a comment"); */ } -{ - [ CommentLine() ] -} - -void InstallationParagraph() : -{ /* System.out.println("Deprecated keyword : installation - use a comment"); */ } -{ - [ CommentLine() ] -} - -void DateWrittenParagraph() : -{ /* System.out.println("Deprecated keyword : date-written - use a comment"); */ } -{ - [ CommentLine() ] -} - -void DateCompiledParagraph() : -{ /* System.out.println("Deprecated keyword : date-compiled - use a comment"); */ } -{ - [ CommentLine() ] -} - -void SecurityParagraph() : -{ /* System.out.println("Deprecated keyword : security - use a comment"); */ } -{ - [ CommentLine() ] -} - -//////////////////////////////////////////////////////////////////////////////// -// ENVIRONMENT DIVISION. -//////////////////////////////////////////////////////////////////////////////// - -void EnvironmentDivision() : -{} -{ - - ( EnvironmentSection() )* -} - -void EnvironmentSection() : -{} -{ - ConfigurationSection() - | InputOutputSection() -} - -//------------------------------------------------------------------------------ -// CONFIGURATION SECTION -//------------------------------------------------------------------------------ - -void ConfigurationSection() : -{} -{ -
- ( ConfigurationSectionParagraph() )* -} - -void ConfigurationSectionParagraph() : -{} -{ - SourceComputerParagraph() - | ObjectComputerParagraph() - | SpecialNamesParagraph() -} - -void SourceComputerParagraph() : -{} -{ - ComputerName() [ [ ] ] -} - -void ObjectComputerParagraph() : -{} -{ - - ComputerName() ( ObjectComputerClause() )* -} - -void ObjectComputerClause() : -{} -{ - MemorySizeClause() - | CollatingSequenceClause() - | SegmentLimitClause() - | CharacterSetClause() -} - -void MemorySizeClause() : -{ /* System.out.println("Deprecated keyword : memory - use a comment"); */ } -{ - [ ] IntegerConstant() [ | | ] -} - -void CollatingSequenceClause() : -{ /* System.out.println("Deprecated keyword : collating sequence - use a comment"); */ } -{ - [ ] [ ] [ ] AlphabetName() -} - -void SegmentLimitClause() : -{ /* System.out.println("Deprecated keyword : segment unit - use a comment"); */ } -{ - ( | ) [ ] IntegerConstant() -} - -// Tandem ??? -void CharacterSetClause() : -{} -{ - [ CommentLine() ] -} - -void SpecialNamesParagraph() : -{} -{ - - [ ( SpecialNameClause() )+ ] -} - -void SpecialNameClause() : -{} -{ - AlphabetClause() - | ClassClause() - | CurrencySignClause() - | DecimalPointClause() - | SymbolicCharactersClause() - | CallConventionClause() - | EnvironmentNameIsMnemonicNameClause() -} - -void IterableAlphabetPhrase() : -{} -{ - ( | ) IterableLiteral() - | ( IterableLiteral() )+ -} - -void AlphabetClause() : -{} -{ - AlphabetName() [ ] - ( - | - | - | CobolWord() - | ( IterableLiteral() [ IterableAlphabetPhrase() ] )+ - ) -} - -void ClassClause() : -{} -{ - // TODO (SUPPRESS) : Dirty hack : IterableLiteral() --> Identifier() | IterableLiteral() - ClassName() [ ] ( ( Identifier() | IterableLiteral() ) [ ( | ) ( Identifier() | IterableLiteral() ) ] )+ -} - -void CurrencySignClause() : -{} -{ - [ ] [ ] Literal() -} - -void DecimalPointClause() : -{} -{ - [ ] -} - -void SymbolicCharactersClause() : -{} -{ - [ ] ( ( SymbolicCharacter() )+ [ ( | ) ] ( NumericConstant() | )+ )+ [ AlphabetName() ] -} - -void CallConventionClause() : -{} -{ - IntegerConstant() [ ] ConventionName() -} - -void EnvironmentNameIsMnemonicNameClause() : -{} -{ - EnvironmentName() - ( [ ] MnemonicName() [ SpecialNamesParagraphStatusPhrase() ] - | SpecialNamesParagraphStatusPhrase() - ) -} - -void SpecialNamesParagraphStatusPhrase() : -{} -{ - ( [ ] [ ] IterableCondition() [ [ ] [ ] IterableCondition() ] - | [ ] [ ] IterableCondition() [ [ ] [ ] IterableCondition() ] - ) -} - -//------------------------------------------------------------------------------ -// INPUT-OUTPUT SECTION -//------------------------------------------------------------------------------ - -void InputOutputSection() : -{} -{ -
- ( InputOutputSectionParagraph() )* -} - -void InputOutputSectionParagraph() : -{} -{ - FileControlParagraph() - | IOControlParagraph() -} - -void FileControlParagraph() : -{} -{ - ( LOOKAHEAD([ ] FileControlEntry()) [ ] FileControlEntry() )* -} - -void FileControlEntry() : -{} -{ - SelectClause() - ( FileControlClause() )* -} - -void FileControlClause() : -{} -{ - AssignClause() - | ReserveClause() - | OrganizationClause() - | PaddingCharacterClause() - | RecordDelimiterClause() - | AccessModeClause() - | RecordKeyClause() - | AlternateRecordKeyClause() - | FileStatusClause() - | PasswordClause() -} - -void SelectClause() : -{} -{ - ( CommunicationInputClause() )* ( DataName() )* -} - -void CommunicationOutputEntry() : -{} -{ - CdName() [ ] ( CommunicationOutputClause() )* -} - -void CommunicationIOEntry() : -{} -{ - CdName() [ ] [ ] ( CommunicationIOClause() )* ( DataName() )* -} - -void CommunicationInputClause() : -{} -{ - ( |