Debian Codegraph @

rhino/toolsrc/org/mozilla/javascript/tools/jsc/Main.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.tools.jsc;
6
7 import java.io.*;
8 import java.util.*;
9 import org.mozilla.javascript.*;
10 import org.mozilla.javascript.optimizer.ClassCompiler;
11 import org.mozilla.javascript.tools.SourceReader;
12 import org.mozilla.javascript.tools.ToolErrorReporter;
13
14 /**
15 * @author Norris Boyd
16 */
17 public class Main {
18
19 /**
20 * Main entry point.
21 *
22 * Process arguments as would a normal Java program.
23 * Then set up the execution environment and begin to
24 * compile scripts.
25 */
26 public static void main(String args[])
27 {
28 Main main = new Main();
29 args = main.processOptions(args);
30 if (args == null) {
31 if (main.printHelp) {
32 System.out.println(ToolErrorReporter.getMessage(
33 "msg.jsc.usage", Main.class.getName()));
34 System.exit(0);
35 }
36 System.exit(1);
37 }
38 if (!main.reporter.hasReportedError()) {
39 main.processSource(args);
40 }
41 }
42
43 public Main()
44 {
45 reporter = new ToolErrorReporter(true);
46 compilerEnv = new CompilerEnvirons();
47 compilerEnv.setErrorReporter(reporter);
48 compiler = new ClassCompiler(compilerEnv);
49 }
50
51 /**
52 * Parse arguments.
53 *
54 */
55 public String[] processOptions(String args[])
56 {
57 targetPackage = ""; // default to no package
58 compilerEnv.setGenerateDebugInfo(false); // default to no symbols
59 for (int i=0; i < args.length; i++) {
60 String arg = args[i];
61 if (!arg.startsWith("-")) {
62 int tail = args.length - i;
63 if (targetName != null && tail > 1) {
64 addError("msg.multiple.js.to.file", targetName);
65 return null;
66 }
67 String[] result = new String[tail];
68 for (int j = 0; j != tail; ++j) {
69 result[j] = args[i + j];
70 }
71 return result;
72 }
73 if (arg.equals("-help") || arg.equals("-h")
74 || arg.equals("--help"))
75 {
76 printHelp = true;
77 return null;
78 }
79
80 try {
81 if (arg.equals("-version") && ++i < args.length) {
82 int version = Integer.parseInt(args[i]);
83 compilerEnv.setLanguageVersion(version);
84 continue;
85 }
86 if ((arg.equals("-opt") || arg.equals("-O")) &&
87 ++i < args.length)
88 {
89 int optLevel = Integer.parseInt(args[i]);
90 compilerEnv.setOptimizationLevel(optLevel);
91 continue;
92 }
93 }
94 catch (NumberFormatException e) {
95 badUsage(args[i]);
96 return null;
97 }
98 if (arg.equals("-nosource")) {
99 compilerEnv.setGeneratingSource(false);
100 continue;
101 }
102 if (arg.equals("-debug") || arg.equals("-g")) {
103 compilerEnv.setGenerateDebugInfo(true);
104 continue;
105 }
106 if (arg.equals("-main-method-class") && ++i < args.length) {
107 compiler.setMainMethodClass(args[i]);
108 continue;
109 }
110 if (arg.equals("-encoding") && ++i < args.length) {
111 characterEncoding = args[i];
112 continue;
113 }
114 if (arg.equals("-o") && ++i < args.length) {
115 String name = args[i];
116 int end = name.length();
117 if (end == 0
118 || !Character.isJavaIdentifierStart(name.charAt(0)))
119 {
120 addError("msg.invalid.classfile.name", name);
121 continue;
122 }
123 for (int j = 1; j < end; j++) {
124 char c = name.charAt(j);
125 if (!Character.isJavaIdentifierPart(c)) {
126 if (c == '.') {
127 // check if it is the dot in .class
128 if (j == end - 6 && name.endsWith(".class")) {
129 name = name.substring(0, j);
130 break;
131 }
132 }
133 addError("msg.invalid.classfile.name", name);
134 break;
135 }
136 }
137 targetName = name;
138 continue;
139 }
140 if (arg.equals("-observe-instruction-count")) {
141 compilerEnv.setGenerateObserverCount(true);
142 }
143 if (arg.equals("-package") && ++i < args.length) {
144 String pkg = args[i];
145 int end = pkg.length();
146 for (int j = 0; j != end; ++j) {
147 char c = pkg.charAt(j);
148 if (Character.isJavaIdentifierStart(c)) {
149 for (++j; j != end; ++j) {
150 c = pkg.charAt(j);
151 if (!Character.isJavaIdentifierPart(c)) {
152 break;
153 }
154 }
155 if (j == end) {
156 break;
157 }
158 if (c == '.' && j != end - 1) {
159 continue;
160 }
161 }
162 addError("msg.package.name", targetPackage);
163 return null;
164 }
165 targetPackage = pkg;
166 continue;
167 }
168 if (arg.equals("-extends") && ++i < args.length) {
169 String targetExtends = args[i];
170 Class<?> superClass;
171 try {
172 superClass = Class.forName(targetExtends);
173 } catch (ClassNotFoundException e) {
174 throw new Error(e.toString()); // TODO: better error
175 }
176 compiler.setTargetExtends(superClass);
177 continue;
178 }
179 if (arg.equals("-implements") && ++i < args.length) {
180 // TODO: allow for multiple comma-separated interfaces.
181 String targetImplements = args[i];
182 StringTokenizer st = new StringTokenizer(targetImplements,
183 ",");
184 List<Class<?>> list = new ArrayList<Class<?>>();
185 while (st.hasMoreTokens()) {
186 String className = st.nextToken();
187 try {
188 list.add(Class.forName(className));
189 } catch (ClassNotFoundException e) {
190 throw new Error(e.toString()); // TODO: better error
191 }
192 }
193 Class<?>[] implementsClasses = list.toArray(new Class<?>[list.size()]);
194 compiler.setTargetImplements(implementsClasses);
195 continue;
196 }
197 if (arg.equals("-d") && ++i < args.length) {
198 destinationDir = args[i];
199 continue;
200 }
201 badUsage(arg);
202 return null;
203 }
204 // no file name
205 p(ToolErrorReporter.getMessage("msg.no.file"));
206 return null;
207 }
208 /**
209 * Print a usage message.
210 */
211 private static void badUsage(String s) {
212 System.err.println(ToolErrorReporter.getMessage(
213 "msg.jsc.bad.usage", Main.class.getName(), s));
214 }
215
216 /**
217 * Compile JavaScript source.
218 *
219 */
220 public void processSource(String[] filenames)
221 {
222 for (int i = 0; i != filenames.length; ++i) {
223 String filename = filenames[i];
224 if (!filename.endsWith(".js")) {
225 addError("msg.extension.not.js", filename);
226 return;
227 }
228 File f = new File(filename);
229 String source = readSource(f);
230 if (source == null) return;
231
232 String mainClassName = targetName;
233 if (mainClassName == null) {
234 String name = f.getName();
235 String nojs = name.substring(0, name.length() - 3);
236 mainClassName = getClassName(nojs);
237 }
238 if (targetPackage.length() != 0) {
239 mainClassName = targetPackage+"."+mainClassName;
240 }
241
242 Object[] compiled
243 = compiler.compileToClassFiles(source, filename, 1,
244 mainClassName);
245 if (compiled == null || compiled.length == 0) {
246 return;
247 }
248
249 File targetTopDir = null;
250 if (destinationDir != null) {
251 targetTopDir = new File(destinationDir);
252 } else {
253 String parent = f.getParent();
254 if (parent != null) {
255 targetTopDir = new File(parent);
256 }
257 }
258 for (int j = 0; j != compiled.length; j += 2) {
259 String className = (String)compiled[j];
260 byte[] bytes = (byte[])compiled[j + 1];
261 File outfile = getOutputFile(targetTopDir, className);
262 try {
263 FileOutputStream os = new FileOutputStream(outfile);
264 try {
265 os.write(bytes);
266 } finally {
267 os.close();
268 }
269 } catch (IOException ioe) {
270 addFormatedError(ioe.toString());
271 }
272 }
273 }
274 }
275
276 private String readSource(File f)
277 {
278 String absPath = f.getAbsolutePath();
279 if (!f.isFile()) {
280 addError("msg.jsfile.not.found", absPath);
281 return null;
282 }
283 try {
284 return (String)SourceReader.readFileOrUrl(absPath, true,
285 characterEncoding);
286 } catch (FileNotFoundException ex) {
287 addError("msg.couldnt.open", absPath);
288 } catch (IOException ioe) {
289 addFormatedError(ioe.toString());
290 }
291 return null;
292 }
293
294 private File getOutputFile(File parentDir, String className)
295 {
296 String path = className.replace('.', File.separatorChar);
297 path = path.concat(".class");
298 File f = new File(parentDir, path);
299 String dirPath = f.getParent();
300 if (dirPath != null) {
301 File dir = new File(dirPath);
302 if (!dir.exists()) {
303 dir.mkdirs();
304 }
305 }
306 return f;
307 }
308
309 /**
310 * Verify that class file names are legal Java identifiers. Substitute
311 * illegal characters with underscores, and prepend the name with an
312 * underscore if the file name does not begin with a JavaLetter.
313 */
314
315 String getClassName(String name) {
316 char[] s = new char[name.length()+1];
317 char c;
318 int j = 0;
319
320 if (!Character.isJavaIdentifierStart(name.charAt(0))) {
321 s[j++] = '_';
322 }
323 for (int i=0; i < name.length(); i++, j++) {
324 c = name.charAt(i);
325 if ( Character.isJavaIdentifierPart(c) ) {
326 s[j] = c;
327 } else {
328 s[j] = '_';
329 }
330 }
331 return (new String(s)).trim();
332 }
333
334 private static void p(String s) {
335 System.out.println(s);
336 }
337
338 private void addError(String messageId, String arg)
339 {
340 String msg;
341 if (arg == null) {
342 msg = ToolErrorReporter.getMessage(messageId);
343 } else {
344 msg = ToolErrorReporter.getMessage(messageId, arg);
345 }
346 addFormatedError(msg);
347 }
348
349 private void addFormatedError(String message)
350 {
351 reporter.error(message, null, -1, null, -1);
352 }
353
354 private boolean printHelp;
355 private ToolErrorReporter reporter;
356 private CompilerEnvirons compilerEnv;
357 private ClassCompiler compiler;
358 private String targetName;
359 private String targetPackage;
360 private String destinationDir;
361 private String characterEncoding;
362 }
363