Tue, 25 May 2010 15:54:51 -0700
6943119: Rebrand source copyright notices
Reviewed-by: darcy
1 /*
2 * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.main;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.net.URL;
32 import java.security.DigestInputStream;
33 import java.security.MessageDigest;
34 import java.util.MissingResourceException;
36 import com.sun.tools.javac.code.Source;
37 import com.sun.tools.javac.file.CacheFSInfo;
38 import com.sun.tools.javac.file.JavacFileManager;
39 import com.sun.tools.javac.jvm.Target;
40 import com.sun.tools.javac.main.JavacOption.Option;
41 import com.sun.tools.javac.main.RecognizedOptions.OptionHelper;
42 import com.sun.tools.javac.util.*;
43 import com.sun.tools.javac.processing.AnnotationProcessingError;
44 import javax.tools.JavaFileManager;
45 import javax.tools.JavaFileObject;
46 import javax.annotation.processing.Processor;
48 /** This class provides a commandline interface to the GJC compiler.
49 *
50 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
51 * you write code that depends on this, you do so at your own risk.
52 * This code and its internal interfaces are subject to change or
53 * deletion without notice.</b>
54 */
55 public class Main {
57 /** The name of the compiler, for use in diagnostics.
58 */
59 String ownName;
61 /** The writer to use for diagnostic output.
62 */
63 PrintWriter out;
65 /**
66 * If true, any command line arg errors will cause an exception.
67 */
68 boolean fatalErrors;
70 /** Result codes.
71 */
72 static final int
73 EXIT_OK = 0, // Compilation completed with no errors.
74 EXIT_ERROR = 1, // Completed but reported errors.
75 EXIT_CMDERR = 2, // Bad command-line arguments
76 EXIT_SYSERR = 3, // System error or resource exhaustion.
77 EXIT_ABNORMAL = 4; // Compiler terminated abnormally
79 private Option[] recognizedOptions = RecognizedOptions.getJavaCompilerOptions(new OptionHelper() {
81 public void setOut(PrintWriter out) {
82 Main.this.out = out;
83 }
85 public void error(String key, Object... args) {
86 Main.this.error(key, args);
87 }
89 public void printVersion() {
90 Log.printLines(out, getLocalizedString("version", ownName, JavaCompiler.version()));
91 }
93 public void printFullVersion() {
94 Log.printLines(out, getLocalizedString("fullVersion", ownName, JavaCompiler.fullVersion()));
95 }
97 public void printHelp() {
98 help();
99 }
101 public void printXhelp() {
102 xhelp();
103 }
105 public void addFile(File f) {
106 if (!filenames.contains(f))
107 filenames.append(f);
108 }
110 public void addClassName(String s) {
111 classnames.append(s);
112 }
114 });
116 /**
117 * Construct a compiler instance.
118 */
119 public Main(String name) {
120 this(name, new PrintWriter(System.err, true));
121 }
123 /**
124 * Construct a compiler instance.
125 */
126 public Main(String name, PrintWriter out) {
127 this.ownName = name;
128 this.out = out;
129 }
130 /** A table of all options that's passed to the JavaCompiler constructor. */
131 private Options options = null;
133 /** The list of source files to process
134 */
135 public ListBuffer<File> filenames = null; // XXX sb protected
137 /** List of class files names passed on the command line
138 */
139 public ListBuffer<String> classnames = null; // XXX sb protected
141 /** Print a string that explains usage.
142 */
143 void help() {
144 Log.printLines(out, getLocalizedString("msg.usage.header", ownName));
145 for (int i=0; i<recognizedOptions.length; i++) {
146 recognizedOptions[i].help(out);
147 }
148 out.println();
149 }
151 /** Print a string that explains usage for X options.
152 */
153 void xhelp() {
154 for (int i=0; i<recognizedOptions.length; i++) {
155 recognizedOptions[i].xhelp(out);
156 }
157 out.println();
158 Log.printLines(out, getLocalizedString("msg.usage.nonstandard.footer"));
159 }
161 /** Report a usage error.
162 */
163 void error(String key, Object... args) {
164 if (fatalErrors) {
165 String msg = getLocalizedString(key, args);
166 throw new PropagatedException(new IllegalStateException(msg));
167 }
168 warning(key, args);
169 Log.printLines(out, getLocalizedString("msg.usage", ownName));
170 }
172 /** Report a warning.
173 */
174 void warning(String key, Object... args) {
175 Log.printLines(out, ownName + ": "
176 + getLocalizedString(key, args));
177 }
179 public Option getOption(String flag) {
180 for (Option option : recognizedOptions) {
181 if (option.matches(flag))
182 return option;
183 }
184 return null;
185 }
187 public void setOptions(Options options) {
188 if (options == null)
189 throw new NullPointerException();
190 this.options = options;
191 }
193 public void setFatalErrors(boolean fatalErrors) {
194 this.fatalErrors = fatalErrors;
195 }
197 /** Process command line arguments: store all command line options
198 * in `options' table and return all source filenames.
199 * @param flags The array of command line arguments.
200 */
201 public List<File> processArgs(String[] flags) { // XXX sb protected
202 int ac = 0;
203 while (ac < flags.length) {
204 String flag = flags[ac];
205 ac++;
207 Option option = null;
209 if (flag.length() > 0) {
210 // quick hack to speed up file processing:
211 // if the option does not begin with '-', there is no need to check
212 // most of the compiler options.
213 int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length-1;
214 for (int j=firstOptionToCheck; j<recognizedOptions.length; j++) {
215 if (recognizedOptions[j].matches(flag)) {
216 option = recognizedOptions[j];
217 break;
218 }
219 }
220 }
222 if (option == null) {
223 error("err.invalid.flag", flag);
224 return null;
225 }
227 if (option.hasArg()) {
228 if (ac == flags.length) {
229 error("err.req.arg", flag);
230 return null;
231 }
232 String operand = flags[ac];
233 ac++;
234 if (option.process(options, flag, operand))
235 return null;
236 } else {
237 if (option.process(options, flag))
238 return null;
239 }
240 }
242 if (!checkDirectory("-d"))
243 return null;
244 if (!checkDirectory("-s"))
245 return null;
247 String sourceString = options.get("-source");
248 Source source = (sourceString != null)
249 ? Source.lookup(sourceString)
250 : Source.DEFAULT;
251 String targetString = options.get("-target");
252 Target target = (targetString != null)
253 ? Target.lookup(targetString)
254 : Target.DEFAULT;
255 // We don't check source/target consistency for CLDC, as J2ME
256 // profiles are not aligned with J2SE targets; moreover, a
257 // single CLDC target may have many profiles. In addition,
258 // this is needed for the continued functioning of the JSR14
259 // prototype.
260 if (Character.isDigit(target.name.charAt(0))) {
261 if (target.compareTo(source.requiredTarget()) < 0) {
262 if (targetString != null) {
263 if (sourceString == null) {
264 warning("warn.target.default.source.conflict",
265 targetString,
266 source.requiredTarget().name);
267 } else {
268 warning("warn.source.target.conflict",
269 sourceString,
270 source.requiredTarget().name);
271 }
272 return null;
273 } else {
274 target = source.requiredTarget();
275 options.put("-target", target.name);
276 }
277 } else {
278 if (targetString == null && !source.allowGenerics()) {
279 target = Target.JDK1_4;
280 options.put("-target", target.name);
281 }
282 }
283 }
284 if (target.hasInvokedynamic()) {
285 options.put("invokedynamic", "invokedynamic");
286 }
288 // handle this here so it works even if no other options given
289 String showClass = options.get("showClass");
290 if (showClass != null) {
291 if (showClass.equals("showClass")) // no value given for option
292 showClass = "com.sun.tools.javac.Main";
293 showClass(showClass);
294 }
296 return filenames.toList();
297 }
298 // where
299 private boolean checkDirectory(String optName) {
300 String value = options.get(optName);
301 if (value == null)
302 return true;
303 File file = new File(value);
304 if (!file.exists()) {
305 error("err.dir.not.found", value);
306 return false;
307 }
308 if (!file.isDirectory()) {
309 error("err.file.not.directory", value);
310 return false;
311 }
312 return true;
313 }
315 /** Programmatic interface for main function.
316 * @param args The command line parameters.
317 */
318 public int compile(String[] args) {
319 Context context = new Context();
320 JavacFileManager.preRegister(context); // can't create it until Log has been set up
321 int result = compile(args, context);
322 if (fileManager instanceof JavacFileManager) {
323 // A fresh context was created above, so jfm must be a JavacFileManager
324 ((JavacFileManager)fileManager).close();
325 }
326 return result;
327 }
329 public int compile(String[] args, Context context) {
330 return compile(args, context, List.<JavaFileObject>nil(), null);
331 }
333 /** Programmatic interface for main function.
334 * @param args The command line parameters.
335 */
336 public int compile(String[] args,
337 Context context,
338 List<JavaFileObject> fileObjects,
339 Iterable<? extends Processor> processors)
340 {
341 if (options == null)
342 options = Options.instance(context); // creates a new one
344 filenames = new ListBuffer<File>();
345 classnames = new ListBuffer<String>();
346 JavaCompiler comp = null;
347 /*
348 * TODO: Logic below about what is an acceptable command line
349 * should be updated to take annotation processing semantics
350 * into account.
351 */
352 try {
353 if (args.length == 0 && fileObjects.isEmpty()) {
354 help();
355 return EXIT_CMDERR;
356 }
358 List<File> files;
359 try {
360 files = processArgs(CommandLine.parse(args));
361 if (files == null) {
362 // null signals an error in options, abort
363 return EXIT_CMDERR;
364 } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
365 // it is allowed to compile nothing if just asking for help or version info
366 if (options.get("-help") != null
367 || options.get("-X") != null
368 || options.get("-version") != null
369 || options.get("-fullversion") != null)
370 return EXIT_OK;
371 error("err.no.source.files");
372 return EXIT_CMDERR;
373 }
374 } catch (java.io.FileNotFoundException e) {
375 Log.printLines(out, ownName + ": " +
376 getLocalizedString("err.file.not.found",
377 e.getMessage()));
378 return EXIT_SYSERR;
379 }
381 boolean forceStdOut = options.get("stdout") != null;
382 if (forceStdOut) {
383 out.flush();
384 out = new PrintWriter(System.out, true);
385 }
387 context.put(Log.outKey, out);
389 // allow System property in following line as a Mustang legacy
390 boolean batchMode = (options.get("nonBatchMode") == null
391 && System.getProperty("nonBatchMode") == null);
392 if (batchMode)
393 CacheFSInfo.preRegister(context);
395 fileManager = context.get(JavaFileManager.class);
397 comp = JavaCompiler.instance(context);
398 if (comp == null) return EXIT_SYSERR;
400 Log log = Log.instance(context);
402 if (!files.isEmpty()) {
403 // add filenames to fileObjects
404 comp = JavaCompiler.instance(context);
405 List<JavaFileObject> otherFiles = List.nil();
406 JavacFileManager dfm = (JavacFileManager)fileManager;
407 for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
408 otherFiles = otherFiles.prepend(fo);
409 for (JavaFileObject fo : otherFiles)
410 fileObjects = fileObjects.prepend(fo);
411 }
412 comp.compile(fileObjects,
413 classnames.toList(),
414 processors);
416 if (log.expectDiagKeys != null) {
417 if (log.expectDiagKeys.size() == 0) {
418 Log.printLines(log.noticeWriter, "all expected diagnostics found");
419 return EXIT_OK;
420 } else {
421 Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
422 return EXIT_ERROR;
423 }
424 }
426 if (comp.errorCount() != 0)
427 return EXIT_ERROR;
428 } catch (IOException ex) {
429 ioMessage(ex);
430 return EXIT_SYSERR;
431 } catch (OutOfMemoryError ex) {
432 resourceMessage(ex);
433 return EXIT_SYSERR;
434 } catch (StackOverflowError ex) {
435 resourceMessage(ex);
436 return EXIT_SYSERR;
437 } catch (FatalError ex) {
438 feMessage(ex);
439 return EXIT_SYSERR;
440 } catch(AnnotationProcessingError ex) {
441 apMessage(ex);
442 return EXIT_SYSERR;
443 } catch (ClientCodeException ex) {
444 // as specified by javax.tools.JavaCompiler#getTask
445 // and javax.tools.JavaCompiler.CompilationTask#call
446 throw new RuntimeException(ex.getCause());
447 } catch (PropagatedException ex) {
448 throw ex.getCause();
449 } catch (Throwable ex) {
450 // Nasty. If we've already reported an error, compensate
451 // for buggy compiler error recovery by swallowing thrown
452 // exceptions.
453 if (comp == null || comp.errorCount() == 0 ||
454 options == null || options.get("dev") != null)
455 bugMessage(ex);
456 return EXIT_ABNORMAL;
457 } finally {
458 if (comp != null) comp.close();
459 filenames = null;
460 options = null;
461 }
462 return EXIT_OK;
463 }
465 /** Print a message reporting an internal error.
466 */
467 void bugMessage(Throwable ex) {
468 Log.printLines(out, getLocalizedString("msg.bug",
469 JavaCompiler.version()));
470 ex.printStackTrace(out);
471 }
473 /** Print a message reporting an fatal error.
474 */
475 void feMessage(Throwable ex) {
476 Log.printLines(out, ex.getMessage());
477 }
479 /** Print a message reporting an input/output error.
480 */
481 void ioMessage(Throwable ex) {
482 Log.printLines(out, getLocalizedString("msg.io"));
483 ex.printStackTrace(out);
484 }
486 /** Print a message reporting an out-of-resources error.
487 */
488 void resourceMessage(Throwable ex) {
489 Log.printLines(out, getLocalizedString("msg.resource"));
490 // System.out.println("(name buffer len = " + Name.names.length + " " + Name.nc);//DEBUG
491 ex.printStackTrace(out);
492 }
494 /** Print a message reporting an uncaught exception from an
495 * annotation processor.
496 */
497 void apMessage(AnnotationProcessingError ex) {
498 Log.printLines(out,
499 getLocalizedString("msg.proc.annotation.uncaught.exception"));
500 ex.getCause().printStackTrace();
501 }
503 /** Display the location and checksum of a class. */
504 void showClass(String className) {
505 out.println("javac: show class: " + className);
506 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
507 if (url == null)
508 out.println(" class not found");
509 else {
510 out.println(" " + url);
511 try {
512 final String algorithm = "MD5";
513 byte[] digest;
514 MessageDigest md = MessageDigest.getInstance(algorithm);
515 DigestInputStream in = new DigestInputStream(url.openStream(), md);
516 try {
517 byte[] buf = new byte[8192];
518 int n;
519 do { n = in.read(buf); } while (n > 0);
520 digest = md.digest();
521 } finally {
522 in.close();
523 }
524 StringBuilder sb = new StringBuilder();
525 for (byte b: digest)
526 sb.append(String.format("%02x", b));
527 out.println(" " + algorithm + " checksum: " + sb);
528 } catch (Exception e) {
529 out.println(" cannot compute digest: " + e);
530 }
531 }
532 }
534 private JavaFileManager fileManager;
536 /* ************************************************************************
537 * Internationalization
538 *************************************************************************/
540 /** Find a localized string in the resource bundle.
541 * @param key The key for the localized string.
542 */
543 public static String getLocalizedString(String key, Object... args) { // FIXME sb private
544 try {
545 if (messages == null)
546 messages = new JavacMessages(javacBundleName);
547 return messages.getLocalizedString("javac." + key, args);
548 }
549 catch (MissingResourceException e) {
550 throw new Error("Fatal Error: Resource for javac is missing", e);
551 }
552 }
554 public static void useRawMessages(boolean enable) {
555 if (enable) {
556 messages = new JavacMessages(javacBundleName) {
557 public String getLocalizedString(String key, Object... args) {
558 return key;
559 }
560 };
561 } else {
562 messages = new JavacMessages(javacBundleName);
563 }
564 }
566 private static final String javacBundleName =
567 "com.sun.tools.javac.resources.javac";
569 private static JavacMessages messages;
570 }