KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > antlr > works > generate > CodeGenerate


1 /*
2
3 [The "BSD licence"]
4 Copyright (c) 2005 Jean Bovet
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions
9 are met:
10
11 1. Redistributions of source code must retain the above copyright
12 notice, this list of conditions and the following disclaimer.
13 2. Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16 3. The name of the author may not be used to endorse or promote products
17 derived from this software without specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 */

31
32 package org.antlr.works.generate;
33
34 import org.antlr.xjlib.appkit.utils.XJAlert;
35 import org.antlr.xjlib.appkit.utils.XJDialogProgress;
36 import org.antlr.xjlib.foundation.XJUtils;
37 import org.antlr.Tool;
38 import org.antlr.tool.ErrorManager;
39 import org.antlr.tool.Grammar;
40 import org.antlr.works.editor.EditorProvider;
41 import org.antlr.works.grammar.EngineGrammar;
42 import org.antlr.works.prefs.AWPrefs;
43 import org.antlr.works.syntax.element.ElementGrammarName;
44 import org.antlr.works.utils.Console;
45 import org.antlr.works.utils.ErrorListener;
46 import org.antlr.works.utils.Utils;
47
48 import javax.swing.*;
49 import java.awt.*;
50 import java.io.File JavaDoc;
51 import java.util.ArrayList JavaDoc;
52 import java.util.List JavaDoc;
53
54 public class CodeGenerate implements Runnable JavaDoc {
55
56     protected String JavaDoc outputPath;
57     protected boolean debug = true;
58
59     protected EditorProvider provider;
60     protected CodeGenerateDelegate delegate;
61     protected ErrorListener errorListener;
62
63     protected long dateOfModificationOnDisk = 0;
64
65     public CodeGenerate(EditorProvider provider, CodeGenerateDelegate delegate) {
66         this.provider = provider;
67         this.delegate = delegate;
68         this.outputPath = AWPrefs.getOutputPath();
69
70         errorListener = new ErrorListener();
71         errorListener.setPrintToConsole(false);
72         errorListener.setForwardListener(ErrorListener.shared());
73     }
74
75     public void setDebug(boolean debug) {
76         this.debug = debug;
77     }
78
79     public void setOutputPath(String JavaDoc path) {
80         this.outputPath = path;
81     }
82
83     public String JavaDoc getOutputPath() {
84         return outputPath;
85     }
86
87     public String JavaDoc getGrammarLanguage() {
88         try {
89             EngineGrammar eg = provider.getEngineGrammar();
90             eg.createGrammars();
91             Grammar g = eg.getParserGrammar();
92             if(g == null) {
93                 g = eg.getLexerGrammar();
94             }
95             if(g != null) {
96                 return (String JavaDoc)g.getOption("language");
97             } else {
98                 return null;
99             }
100         } catch (Exception JavaDoc e) {
101             provider.getConsole().print(e);
102         }
103         return null;
104     }
105
106     public String JavaDoc getGrammarName() {
107         return provider.getEngineGrammar().getName();
108     }
109
110     public String JavaDoc getLastError() {
111         return errorListener.getFirstErrorMessage();
112     }
113
114     public boolean generate() throws Exception JavaDoc {
115         errorListener.clear();
116         ErrorManager.setErrorListener(errorListener);
117
118         String JavaDoc[] params;
119         if(debug)
120             params = new String JavaDoc[] { "-debug", "-o", getOutputPath(), "-lib", provider.getFileFolder(), provider.getFilePath() };
121         else
122             params = new String JavaDoc[] { "-o", getOutputPath(), "-lib", provider.getFileFolder(), provider.getFilePath() };
123
124         Tool antlr = new Tool(Utils.concat(params, AWPrefs.getANTLR3Options()));
125         antlr.process();
126
127         boolean success = !errorListener.hasErrors();
128         if(success) {
129             dateOfModificationOnDisk = provider.getDocument().getDateOfModificationOnDisk();
130         }
131         return success;
132     }
133
134     public static final String JavaDoc LEXER_SUFFIX = "Lexer";
135     public static final String JavaDoc PARSER_SUFFIX = "Parser";
136     public static final String JavaDoc TREEPARSER_SUFFIX = "";
137
138     public String JavaDoc getGeneratedClassName(int type) throws Exception JavaDoc {
139         String JavaDoc name = null;
140         EngineGrammar engine = provider.getEngineGrammar();
141         engine.createGrammars();
142         if(type == ElementGrammarName.LEXER) {
143             Grammar g = engine.getLexerGrammar();
144             if(g == null) return null;
145             name = g.name+LEXER_SUFFIX;
146         } else if(type == ElementGrammarName.PARSER) {
147             Grammar g = engine.getParserGrammar();
148             if(g == null) return null;
149
150             if(engine.getType() == ElementGrammarName.TREEPARSER) {
151                 name = g.name+TREEPARSER_SUFFIX;
152             } else {
153                 name = g.name+PARSER_SUFFIX;
154             }
155         } else if(type == ElementGrammarName.TREEPARSER) {
156             Grammar g = engine.getParserGrammar();
157             if(g == null) return null;
158             if(engine.getType() != ElementGrammarName.TREEPARSER) return null;
159             name = g.name+TREEPARSER_SUFFIX;
160         }
161         return name;
162     }
163
164     public List JavaDoc<String JavaDoc> getGeneratedTextFileNames() throws Exception JavaDoc {
165         List JavaDoc<String JavaDoc> names = new ArrayList JavaDoc<String JavaDoc>();
166
167         String JavaDoc name = getGeneratedTextFileName(ElementGrammarName.LEXER);
168         if(name != null) {
169             names.add(name);
170         }
171
172         name = getGeneratedTextFileName(ElementGrammarName.PARSER);
173         if(name != null) {
174             names.add(name);
175         }
176
177         name = getGeneratedTextFileName(ElementGrammarName.TREEPARSER);
178         if(name != null) {
179             names.add(name);
180         }
181
182         return names;
183     }
184
185     public String JavaDoc getGeneratedTextFileName(int type) throws Exception JavaDoc {
186         String JavaDoc className = getGeneratedClassName(type);
187         if(className == null) return null;
188         return XJUtils.concatPath(getOutputPath(), className+".java");
189     }
190
191     public boolean isGeneratedTextFileExisting(int type) {
192         try {
193             String JavaDoc file = getGeneratedTextFileName(type);
194             if(file == null) return true;
195             return new File JavaDoc(file).exists();
196         } catch (Exception JavaDoc e) {
197             provider.getConsole().print(e);
198         }
199         return false;
200     }
201
202     public boolean isFileModifiedSinceLastGeneration() {
203         return dateOfModificationOnDisk != provider.getDocument().getDateOfModificationOnDisk();
204     }
205
206     public boolean supportsLexer() {
207         int type = provider.getEngineGrammar().getType();
208         return type == ElementGrammarName.COMBINED || type == ElementGrammarName.LEXER;
209     }
210
211     public boolean supportsParser() {
212         int type = provider.getEngineGrammar().getType();
213         return type == ElementGrammarName.COMBINED || type == ElementGrammarName.PARSER || type == ElementGrammarName.TREEPARSER;
214     }
215
216     public String JavaDoc getGeneratedText(int type) throws Exception JavaDoc {
217         return XJUtils.getStringFromFile(getGeneratedTextFileName(type));
218     }
219
220     public void generateInThread(Container parent) {
221         progress = new XJDialogProgress(parent);
222         progress.setInfo("Generating...");
223         progress.setCancellable(false);
224         progress.setIndeterminate(true);
225         progress.display();
226
227         new Thread JavaDoc(this).start();
228     }
229
230     public void generateInThreadDidTerminate() {
231         progress.close();
232         if(generateError != null)
233             XJAlert.display(provider.getWindowContainer(), "Error", "Cannot generate the grammar because:\n"+generateError);
234         else {
235             if(delegate == null || delegate.codeGenerateDisplaySuccess())
236                 XJAlert.display(provider.getWindowContainer(), "Success", "The grammar has been successfully generated in path:\n"+outputPath);
237             else
238                 delegate.codeGenerateDidComplete();
239         }
240     }
241
242     protected String JavaDoc generateError = null;
243     protected XJDialogProgress progress;
244
245     public void run() {
246         generateError = null;
247
248         provider.getConsole().setMode(Console.MODE_VERBOSE);
249
250         try {
251             if(!generate()) {
252                 generateError = getLastError();
253             }
254         } catch (Exception JavaDoc e) {
255             generateError = e.toString();
256             provider.getConsole().print(e);
257         }
258
259         SwingUtilities.invokeLater(new Runnable JavaDoc() {
260             public void run() {
261                 generateInThreadDidTerminate();
262             }
263         });
264     }
265
266 }
267
Popular Tags