Fri, 14 Jan 2011 09:45:04 +0000
6992698: JSR 292: remove support for transient syntax in polymorphic signature calls
Summary: special syntax to denote indy return type through type parameters should be removed (and cast shall be used instead)
Reviewed-by: jjg, jrose
1 /*
2 * Copyright (c) 1999, 2010, 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;
35 import javax.tools.JavaFileManager;
36 import javax.tools.JavaFileObject;
37 import javax.annotation.processing.Processor;
39 import com.sun.tools.javac.code.Source;
40 import com.sun.tools.javac.file.CacheFSInfo;
41 import com.sun.tools.javac.file.JavacFileManager;
42 import com.sun.tools.javac.jvm.Target;
43 import com.sun.tools.javac.main.JavacOption.Option;
44 import com.sun.tools.javac.main.RecognizedOptions.OptionHelper;
45 import com.sun.tools.javac.util.*;
46 import com.sun.tools.javac.processing.AnnotationProcessingError;
48 import static com.sun.tools.javac.main.OptionName.*;
50 /** This class provides a commandline interface to the GJC compiler.
51 *
52 * <p><b>This is NOT part of any supported API.
53 * If you write code that depends on this, you do so at your own risk.
54 * This code and its internal interfaces are subject to change or
55 * deletion without notice.</b>
56 */
57 public class Main {
59 /** The name of the compiler, for use in diagnostics.
60 */
61 String ownName;
63 /** The writer to use for diagnostic output.
64 */
65 PrintWriter out;
67 /**
68 * If true, any command line arg errors will cause an exception.
69 */
70 boolean fatalErrors;
72 /** Result codes.
73 */
74 static final int
75 EXIT_OK = 0, // Compilation completed with no errors.
76 EXIT_ERROR = 1, // Completed but reported errors.
77 EXIT_CMDERR = 2, // Bad command-line arguments
78 EXIT_SYSERR = 3, // System error or resource exhaustion.
79 EXIT_ABNORMAL = 4; // Compiler terminated abnormally
81 private Option[] recognizedOptions = RecognizedOptions.getJavaCompilerOptions(new OptionHelper() {
83 public void setOut(PrintWriter out) {
84 Main.this.out = out;
85 }
87 public void error(String key, Object... args) {
88 Main.this.error(key, args);
89 }
91 public void printVersion() {
92 Log.printLines(out, getLocalizedString("version", ownName, JavaCompiler.version()));
93 }
95 public void printFullVersion() {
96 Log.printLines(out, getLocalizedString("fullVersion", ownName, JavaCompiler.fullVersion()));
97 }
99 public void printHelp() {
100 help();
101 }
103 public void printXhelp() {
104 xhelp();
105 }
107 public void addFile(File f) {
108 if (!filenames.contains(f))
109 filenames.append(f);
110 }
112 public void addClassName(String s) {
113 classnames.append(s);
114 }
116 });
118 /**
119 * Construct a compiler instance.
120 */
121 public Main(String name) {
122 this(name, new PrintWriter(System.err, true));
123 }
125 /**
126 * Construct a compiler instance.
127 */
128 public Main(String name, PrintWriter out) {
129 this.ownName = name;
130 this.out = out;
131 }
132 /** A table of all options that's passed to the JavaCompiler constructor. */
133 private Options options = null;
135 /** The list of source files to process
136 */
137 public ListBuffer<File> filenames = null; // XXX sb protected
139 /** List of class files names passed on the command line
140 */
141 public ListBuffer<String> classnames = null; // XXX sb protected
143 /** Print a string that explains usage.
144 */
145 void help() {
146 Log.printLines(out, getLocalizedString("msg.usage.header", ownName));
147 for (int i=0; i<recognizedOptions.length; i++) {
148 recognizedOptions[i].help(out);
149 }
150 out.println();
151 }
153 /** Print a string that explains usage for X options.
154 */
155 void xhelp() {
156 for (int i=0; i<recognizedOptions.length; i++) {
157 recognizedOptions[i].xhelp(out);
158 }
159 out.println();
160 Log.printLines(out, getLocalizedString("msg.usage.nonstandard.footer"));
161 }
163 /** Report a usage error.
164 */
165 void error(String key, Object... args) {
166 if (fatalErrors) {
167 String msg = getLocalizedString(key, args);
168 throw new PropagatedException(new IllegalStateException(msg));
169 }
170 warning(key, args);
171 Log.printLines(out, getLocalizedString("msg.usage", ownName));
172 }
174 /** Report a warning.
175 */
176 void warning(String key, Object... args) {
177 Log.printLines(out, ownName + ": "
178 + getLocalizedString(key, args));
179 }
181 public Option getOption(String flag) {
182 for (Option option : recognizedOptions) {
183 if (option.matches(flag))
184 return option;
185 }
186 return null;
187 }
189 public void setOptions(Options options) {
190 if (options == null)
191 throw new NullPointerException();
192 this.options = options;
193 }
195 public void setFatalErrors(boolean fatalErrors) {
196 this.fatalErrors = fatalErrors;
197 }
199 /** Process command line arguments: store all command line options
200 * in `options' table and return all source filenames.
201 * @param flags The array of command line arguments.
202 */
203 public List<File> processArgs(String[] flags) { // XXX sb protected
204 int ac = 0;
205 while (ac < flags.length) {
206 String flag = flags[ac];
207 ac++;
209 Option option = null;
211 if (flag.length() > 0) {
212 // quick hack to speed up file processing:
213 // if the option does not begin with '-', there is no need to check
214 // most of the compiler options.
215 int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length-1;
216 for (int j=firstOptionToCheck; j<recognizedOptions.length; j++) {
217 if (recognizedOptions[j].matches(flag)) {
218 option = recognizedOptions[j];
219 break;
220 }
221 }
222 }
224 if (option == null) {
225 error("err.invalid.flag", flag);
226 return null;
227 }
229 if (option.hasArg()) {
230 if (ac == flags.length) {
231 error("err.req.arg", flag);
232 return null;
233 }
234 String operand = flags[ac];
235 ac++;
236 if (option.process(options, flag, operand))
237 return null;
238 } else {
239 if (option.process(options, flag))
240 return null;
241 }
242 }
244 if (!checkDirectory(D))
245 return null;
246 if (!checkDirectory(S))
247 return null;
249 String sourceString = options.get(SOURCE);
250 Source source = (sourceString != null)
251 ? Source.lookup(sourceString)
252 : Source.DEFAULT;
253 String targetString = options.get(TARGET);
254 Target target = (targetString != null)
255 ? Target.lookup(targetString)
256 : Target.DEFAULT;
257 // We don't check source/target consistency for CLDC, as J2ME
258 // profiles are not aligned with J2SE targets; moreover, a
259 // single CLDC target may have many profiles. In addition,
260 // this is needed for the continued functioning of the JSR14
261 // prototype.
262 if (Character.isDigit(target.name.charAt(0))) {
263 if (target.compareTo(source.requiredTarget()) < 0) {
264 if (targetString != null) {
265 if (sourceString == null) {
266 warning("warn.target.default.source.conflict",
267 targetString,
268 source.requiredTarget().name);
269 } else {
270 warning("warn.source.target.conflict",
271 sourceString,
272 source.requiredTarget().name);
273 }
274 return null;
275 } else {
276 target = source.requiredTarget();
277 options.put("-target", target.name);
278 }
279 } else {
280 if (targetString == null && !source.allowGenerics()) {
281 target = Target.JDK1_4;
282 options.put("-target", target.name);
283 }
284 }
285 }
287 // handle this here so it works even if no other options given
288 String showClass = options.get("showClass");
289 if (showClass != null) {
290 if (showClass.equals("showClass")) // no value given for option
291 showClass = "com.sun.tools.javac.Main";
292 showClass(showClass);
293 }
295 return filenames.toList();
296 }
297 // where
298 private boolean checkDirectory(OptionName optName) {
299 String value = options.get(optName);
300 if (value == null)
301 return true;
302 File file = new File(value);
303 if (!file.exists()) {
304 error("err.dir.not.found", value);
305 return false;
306 }
307 if (!file.isDirectory()) {
308 error("err.file.not.directory", value);
309 return false;
310 }
311 return true;
312 }
314 /** Programmatic interface for main function.
315 * @param args The command line parameters.
316 */
317 public int compile(String[] args) {
318 Context context = new Context();
319 JavacFileManager.preRegister(context); // can't create it until Log has been set up
320 int result = compile(args, context);
321 if (fileManager instanceof JavacFileManager) {
322 // A fresh context was created above, so jfm must be a JavacFileManager
323 ((JavacFileManager)fileManager).close();
324 }
325 return result;
326 }
328 public int compile(String[] args, Context context) {
329 return compile(args, context, List.<JavaFileObject>nil(), null);
330 }
332 /** Programmatic interface for main function.
333 * @param args The command line parameters.
334 */
335 public int compile(String[] args,
336 Context context,
337 List<JavaFileObject> fileObjects,
338 Iterable<? extends Processor> processors)
339 {
340 if (options == null)
341 options = Options.instance(context); // creates a new one
343 filenames = new ListBuffer<File>();
344 classnames = new ListBuffer<String>();
345 JavaCompiler comp = null;
346 /*
347 * TODO: Logic below about what is an acceptable command line
348 * should be updated to take annotation processing semantics
349 * into account.
350 */
351 try {
352 if (args.length == 0 && fileObjects.isEmpty()) {
353 help();
354 return EXIT_CMDERR;
355 }
357 List<File> files;
358 try {
359 files = processArgs(CommandLine.parse(args));
360 if (files == null) {
361 // null signals an error in options, abort
362 return EXIT_CMDERR;
363 } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
364 // it is allowed to compile nothing if just asking for help or version info
365 if (options.isSet(HELP)
366 || options.isSet(X)
367 || options.isSet(VERSION)
368 || options.isSet(FULLVERSION))
369 return EXIT_OK;
370 error("err.no.source.files");
371 return EXIT_CMDERR;
372 }
373 } catch (java.io.FileNotFoundException e) {
374 Log.printLines(out, ownName + ": " +
375 getLocalizedString("err.file.not.found",
376 e.getMessage()));
377 return EXIT_SYSERR;
378 }
380 boolean forceStdOut = options.isSet("stdout");
381 if (forceStdOut) {
382 out.flush();
383 out = new PrintWriter(System.out, true);
384 }
386 context.put(Log.outKey, out);
388 // allow System property in following line as a Mustang legacy
389 boolean batchMode = (options.isUnset("nonBatchMode")
390 && System.getProperty("nonBatchMode") == null);
391 if (batchMode)
392 CacheFSInfo.preRegister(context);
394 fileManager = context.get(JavaFileManager.class);
396 comp = JavaCompiler.instance(context);
397 if (comp == null) return EXIT_SYSERR;
399 Log log = Log.instance(context);
401 if (!files.isEmpty()) {
402 // add filenames to fileObjects
403 comp = JavaCompiler.instance(context);
404 List<JavaFileObject> otherFiles = List.nil();
405 JavacFileManager dfm = (JavacFileManager)fileManager;
406 for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
407 otherFiles = otherFiles.prepend(fo);
408 for (JavaFileObject fo : otherFiles)
409 fileObjects = fileObjects.prepend(fo);
410 }
411 comp.compile(fileObjects,
412 classnames.toList(),
413 processors);
415 if (log.expectDiagKeys != null) {
416 if (log.expectDiagKeys.isEmpty()) {
417 Log.printLines(log.noticeWriter, "all expected diagnostics found");
418 return EXIT_OK;
419 } else {
420 Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
421 return EXIT_ERROR;
422 }
423 }
425 if (comp.errorCount() != 0)
426 return EXIT_ERROR;
427 } catch (IOException ex) {
428 ioMessage(ex);
429 return EXIT_SYSERR;
430 } catch (OutOfMemoryError ex) {
431 resourceMessage(ex);
432 return EXIT_SYSERR;
433 } catch (StackOverflowError ex) {
434 resourceMessage(ex);
435 return EXIT_SYSERR;
436 } catch (FatalError ex) {
437 feMessage(ex);
438 return EXIT_SYSERR;
439 } catch(AnnotationProcessingError ex) {
440 apMessage(ex);
441 return EXIT_SYSERR;
442 } catch (ClientCodeException ex) {
443 // as specified by javax.tools.JavaCompiler#getTask
444 // and javax.tools.JavaCompiler.CompilationTask#call
445 throw new RuntimeException(ex.getCause());
446 } catch (PropagatedException ex) {
447 throw ex.getCause();
448 } catch (Throwable ex) {
449 // Nasty. If we've already reported an error, compensate
450 // for buggy compiler error recovery by swallowing thrown
451 // exceptions.
452 if (comp == null || comp.errorCount() == 0 ||
453 options == null || options.isSet("dev"))
454 bugMessage(ex);
455 return EXIT_ABNORMAL;
456 } finally {
457 if (comp != null) comp.close();
458 filenames = null;
459 options = null;
460 }
461 return EXIT_OK;
462 }
464 /** Print a message reporting an internal error.
465 */
466 void bugMessage(Throwable ex) {
467 Log.printLines(out, getLocalizedString("msg.bug",
468 JavaCompiler.version()));
469 ex.printStackTrace(out);
470 }
472 /** Print a message reporting a fatal error.
473 */
474 void feMessage(Throwable ex) {
475 Log.printLines(out, ex.getMessage());
476 if (ex.getCause() != null && options.isSet("dev")) {
477 ex.getCause().printStackTrace(out);
478 }
479 }
481 /** Print a message reporting an input/output error.
482 */
483 void ioMessage(Throwable ex) {
484 Log.printLines(out, getLocalizedString("msg.io"));
485 ex.printStackTrace(out);
486 }
488 /** Print a message reporting an out-of-resources error.
489 */
490 void resourceMessage(Throwable ex) {
491 Log.printLines(out, getLocalizedString("msg.resource"));
492 // System.out.println("(name buffer len = " + Name.names.length + " " + Name.nc);//DEBUG
493 ex.printStackTrace(out);
494 }
496 /** Print a message reporting an uncaught exception from an
497 * annotation processor.
498 */
499 void apMessage(AnnotationProcessingError ex) {
500 Log.printLines(out,
501 getLocalizedString("msg.proc.annotation.uncaught.exception"));
502 ex.getCause().printStackTrace(out);
503 }
505 /** Display the location and checksum of a class. */
506 void showClass(String className) {
507 out.println("javac: show class: " + className);
508 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
509 if (url == null)
510 out.println(" class not found");
511 else {
512 out.println(" " + url);
513 try {
514 final String algorithm = "MD5";
515 byte[] digest;
516 MessageDigest md = MessageDigest.getInstance(algorithm);
517 DigestInputStream in = new DigestInputStream(url.openStream(), md);
518 try {
519 byte[] buf = new byte[8192];
520 int n;
521 do { n = in.read(buf); } while (n > 0);
522 digest = md.digest();
523 } finally {
524 in.close();
525 }
526 StringBuilder sb = new StringBuilder();
527 for (byte b: digest)
528 sb.append(String.format("%02x", b));
529 out.println(" " + algorithm + " checksum: " + sb);
530 } catch (Exception e) {
531 out.println(" cannot compute digest: " + e);
532 }
533 }
534 }
536 private JavaFileManager fileManager;
538 /* ************************************************************************
539 * Internationalization
540 *************************************************************************/
542 /** Find a localized string in the resource bundle.
543 * @param key The key for the localized string.
544 */
545 public static String getLocalizedString(String key, Object... args) { // FIXME sb private
546 try {
547 if (messages == null)
548 messages = new JavacMessages(javacBundleName);
549 return messages.getLocalizedString("javac." + key, args);
550 }
551 catch (MissingResourceException e) {
552 throw new Error("Fatal Error: Resource for javac is missing", e);
553 }
554 }
556 public static void useRawMessages(boolean enable) {
557 if (enable) {
558 messages = new JavacMessages(javacBundleName) {
559 @Override
560 public String getLocalizedString(String key, Object... args) {
561 return key;
562 }
563 };
564 } else {
565 messages = new JavacMessages(javacBundleName);
566 }
567 }
569 private static final String javacBundleName =
570 "com.sun.tools.javac.resources.javac";
572 private static JavacMessages messages;
573 }