KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > antlr > Grammar


1 package antlr;
2
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/RIGHTS.html
6  *
7  * $Id: //depot/code/org.antlr/main/main/antlr/Grammar.java#10 $
8  */

9
10 import java.util.Hashtable JavaDoc;
11 import java.util.Enumeration JavaDoc;
12 import java.io.IOException JavaDoc;
13
14 import antlr.collections.impl.BitSet;
15 import antlr.collections.impl.Vector;
16
17 /**A Grammar holds a set of rules (which are stored
18  * in a symbol table). Most of the time a grammar
19  * needs a code generator and an LLkAnalyzer too.
20  */

21 public abstract class Grammar {
22     protected Tool antlrTool;
23     protected CodeGenerator generator;
24     protected LLkGrammarAnalyzer theLLkAnalyzer;
25     protected Hashtable JavaDoc symbols;
26     protected boolean buildAST = false;
27     protected boolean analyzerDebug = false;
28     protected boolean interactive = false;
29     protected String JavaDoc superClass = null;
30
31     /** The token manager associated with the grammar, if any.
32      // The token manager is responsible for maintaining the set of valid tokens, and
33      // is conceptually shared between the lexer and parser. This may be either a
34      // LexerGrammar or a ImportVocabTokenManager.
35      */

36     protected TokenManager tokenManager;
37
38     /** The name of the export vocabulary...used to generate the output
39      * token types interchange file.
40      */

41     protected String JavaDoc exportVocab = null;
42
43     /** The name of the import vocabulary. "Initial conditions"
44      */

45     protected String JavaDoc importVocab = null;
46
47     // Mapping from String keys to Token option values
48
protected Hashtable JavaDoc options;
49     // Vector of RuleSymbol entries
50
protected Vector rules;
51
52     protected Token preambleAction = new CommonToken(Token.INVALID_TYPE, "");
53     protected String JavaDoc className = null;
54     protected String JavaDoc fileName = null;
55     protected Token classMemberAction = new CommonToken(Token.INVALID_TYPE, "");
56     protected boolean hasSyntacticPredicate = false;
57     protected boolean hasUserErrorHandling = false;
58
59     // max lookahead that can be attempted for this parser.
60
protected int maxk = 1;
61
62     // options
63
protected boolean traceRules = false;
64     protected boolean debuggingOutput = false;
65     protected boolean defaultErrorHandler = true;
66
67     protected String JavaDoc comment = null; // javadoc comment
68

69     public Grammar(String JavaDoc className_, Tool tool_, String JavaDoc superClass) {
70         className = className_;
71         antlrTool = tool_;
72         symbols = new Hashtable JavaDoc();
73         options = new Hashtable JavaDoc();
74         rules = new Vector(100);
75         this.superClass = superClass;
76     }
77
78     /** Define a rule */
79     public void define(RuleSymbol rs) {
80         rules.appendElement(rs);
81         // add the symbol to the rules hash table
82
symbols.put(rs.getId(), rs);
83     }
84
85     /** Top-level call to generate the code for this grammar */
86     public abstract void generate() throws IOException JavaDoc;
87
88     protected String JavaDoc getClassName() {
89         return className;
90     }
91
92     /* Does this grammar have a default error handler? */
93     public boolean getDefaultErrorHandler() {
94         return defaultErrorHandler;
95     }
96
97     public String JavaDoc getFilename() {
98         return fileName;
99     }
100
101     /** Get an integer option. Given the name of the option find its
102      * associated integer value. If the associated value is not an integer or
103      * is not in the table, then throw an exception of type NumberFormatException.
104      * @param key The name of the option
105      * @return The value associated with the key.
106      */

107     public int getIntegerOption(String JavaDoc key) throws NumberFormatException JavaDoc {
108         Token t = (Token)options.get(key);
109         if (t == null || t.getType() != ANTLRTokenTypes.INT) {
110             throw new NumberFormatException JavaDoc();
111         }
112         else {
113             return Integer.parseInt(t.getText());
114         }
115     }
116
117     /** Get an option. Given the name of the option find its associated value.
118      * @param key The name of the option
119      * @return The value associated with the key, or null if the key has not been set.
120      */

121     public Token getOption(String JavaDoc key) {
122         return (Token)options.get(key);
123     }
124
125     // Get name of class from which generated parser/lexer inherits
126
protected abstract String JavaDoc getSuperClass();
127
128     public GrammarSymbol getSymbol(String JavaDoc s) {
129         return (GrammarSymbol)symbols.get(s);
130     }
131
132     public Enumeration JavaDoc getSymbols() {
133         return symbols.elements();
134     }
135
136     /** Check the existence of an option in the table
137      * @param key The name of the option
138      * @return true if the option is in the table
139      */

140     public boolean hasOption(String JavaDoc key) {
141         return options.containsKey(key);
142     }
143
144     /** Is a rule symbol defined? (not used for tokens) */
145     public boolean isDefined(String JavaDoc s) {
146         return symbols.containsKey(s);
147     }
148
149     /**Process command line arguments. Implemented in subclasses */
150     public abstract void processArguments(String JavaDoc[] args);
151
152     public void setCodeGenerator(CodeGenerator gen) {
153         generator = gen;
154     }
155
156     public void setFilename(String JavaDoc s) {
157         fileName = s;
158     }
159
160     public void setGrammarAnalyzer(LLkGrammarAnalyzer a) {
161         theLLkAnalyzer = a;
162     }
163
164     /** Set a generic option.
165      * This associates a generic option key with a Token value.
166      * No validation is performed by this method, although users of the value
167      * (code generation and/or analysis) may require certain formats.
168      * The value is stored as a token so that the location of an error
169      * can be reported.
170      * @param key The name of the option.
171      * @param value The value to associate with the key.
172      * @return true if the option was a valid generic grammar option, false o/w
173      */

174     public boolean setOption(String JavaDoc key, Token value) {
175         options.put(key, value);
176         String JavaDoc s = value.getText();
177         int i;
178         if (key.equals("k")) {
179             try {
180                 maxk = getIntegerOption("k");
181                 //System.out.println("setting lookahead to " + maxk);
182
}
183             catch (NumberFormatException JavaDoc e) {
184                 antlrTool.error("option 'k' must be an integer (was " + value.getText() + ")", getFilename(), value.getLine(), value.getColumn());
185             }
186             return true;
187         }
188         if (key.equals("codeGenMakeSwitchThreshold")) {
189             try {
190                 i = getIntegerOption("codeGenMakeSwitchThreshold");
191             }
192             catch (NumberFormatException JavaDoc e) {
193                 antlrTool.error("option 'codeGenMakeSwitchThreshold' must be an integer", getFilename(), value.getLine(), value.getColumn());
194             }
195             return true;
196         }
197         if (key.equals("codeGenBitsetTestThreshold")) {
198             try {
199                 i = getIntegerOption("codeGenBitsetTestThreshold");
200             }
201             catch (NumberFormatException JavaDoc e) {
202                 antlrTool.error("option 'codeGenBitsetTestThreshold' must be an integer", getFilename(), value.getLine(), value.getColumn());
203             }
204             return true;
205         }
206         if (key.equals("defaultErrorHandler")) {
207             if (s.equals("true")) {
208                 defaultErrorHandler = true;
209             }
210             else if (s.equals("false")) {
211                 defaultErrorHandler = false;
212             }
213             else {
214                 antlrTool.error("Value for defaultErrorHandler must be true or false", getFilename(), value.getLine(), value.getColumn());
215             }
216             return true;
217         }
218         if (key.equals("analyzerDebug")) {
219             if (s.equals("true")) {
220                 analyzerDebug = true;
221             }
222             else if (s.equals("false")) {
223                 analyzerDebug = false;
224             }
225             else {
226                 antlrTool.error("option 'analyzerDebug' must be true or false", getFilename(), value.getLine(), value.getColumn());
227             }
228             return true;
229         }
230         if (key.equals("codeGenDebug")) {
231             if (s.equals("true")) {
232                 analyzerDebug = true;
233             }
234             else if (s.equals("false")) {
235                 analyzerDebug = false;
236             }
237             else {
238                 antlrTool.error("option 'codeGenDebug' must be true or false", getFilename(), value.getLine(), value.getColumn());
239             }
240             return true;
241         }
242         if (key.equals("classHeaderSuffix")) {
243             return true;
244         }
245         if (key.equals("namespaceAntlr")) {
246             return true;
247         }
248         if (key.equals("namespaceStd")) {
249             return true;
250         }
251         if (key.equals("genHashLines")) {
252             return true;
253         }
254         return false;
255     }
256
257     public void setTokenManager(TokenManager tokenManager_) {
258         tokenManager = tokenManager_;
259     }
260
261     /** Print out the grammar without actions */
262     public String JavaDoc toString() {
263         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(20000);
264         Enumeration JavaDoc ids = rules.elements();
265         while (ids.hasMoreElements()) {
266             RuleSymbol rs = (RuleSymbol)ids.nextElement();
267             if (!rs.id.equals("mnextToken")) {
268                 buf.append(rs.getBlock().toString());
269                 buf.append("\n\n");
270             }
271         }
272         return buf.toString();
273     }
274
275 }
276
Popular Tags