Main.java revision 2734:b96d74fa60aa
1104862Sru/* 275584Sru * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. 375584Sru * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 475584Sru * 5104862Sru * This code is free software; you can redistribute it and/or modify it 6114402Sru * 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 */ 25 26package com.sun.tools.javac.main; 27 28import java.io.FileNotFoundException; 29import java.io.IOException; 30import java.io.PrintWriter; 31import java.net.URL; 32import java.nio.file.NoSuchFileException; 33import java.security.DigestInputStream; 34import java.security.MessageDigest; 35import java.security.NoSuchAlgorithmException; 36import java.util.Set; 37 38import javax.tools.JavaFileManager; 39 40import com.sun.tools.javac.api.BasicJavacTask; 41import com.sun.tools.javac.file.CacheFSInfo; 42import com.sun.tools.javac.file.JavacFileManager; 43import com.sun.tools.javac.processing.AnnotationProcessingError; 44import com.sun.tools.javac.util.*; 45import com.sun.tools.javac.util.Log.PrefixKind; 46import com.sun.tools.javac.util.Log.WriterKind; 47 48/** This class provides a command line interface to the javac compiler. 49 * 50 * <p><b>This is NOT part of any supported API. 51 * If 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 */ 55public class Main { 56 57 /** The name of the compiler, for use in diagnostics. 58 */ 59 String ownName; 60 61 /** The writer to use for diagnostic output. 62 */ 63 PrintWriter out; 64 65 /** The log to use for diagnostic output. 66 */ 67 public Log log; 68 69 /** 70 * If true, certain errors will cause an exception, such as command line 71 * arg errors, or exceptions in user provided code. 72 */ 73 boolean apiMode; 74 75 76 /** Result codes. 77 */ 78 public enum Result { 79 OK(0), // Compilation completed with no errors. 80 ERROR(1), // Completed but reported errors. 81 CMDERR(2), // Bad command-line arguments 82 SYSERR(3), // System error or resource exhaustion. 83 ABNORMAL(4); // Compiler terminated abnormally 84 85 Result(int exitCode) { 86 this.exitCode = exitCode; 87 } 88 89 public boolean isOK() { 90 return (exitCode == 0); 91 } 92 93 public final int exitCode; 94 } 95 96 /** 97 * Construct a compiler instance. 98 * @param name the name of this tool 99 */ 100 public Main(String name) { 101 this(name, new PrintWriter(System.err, true)); 102 } 103 104 /** 105 * Construct a compiler instance. 106 * @param name the name of this tool 107 * @param out a stream to which to write messages 108 */ 109 public Main(String name, PrintWriter out) { 110 this.ownName = name; 111 this.out = out; 112 } 113 114 /** Report a usage error. 115 */ 116 void error(String key, Object... args) { 117 if (apiMode) { 118 String msg = log.localize(PrefixKind.JAVAC, key, args); 119 throw new PropagatedException(new IllegalStateException(msg)); 120 } 121 warning(key, args); 122 log.printLines(PrefixKind.JAVAC, "msg.usage", ownName); 123 } 124 125 /** Report a warning. 126 */ 127 void warning(String key, Object... args) { 128 log.printRawLines(ownName + ": " + log.localize(PrefixKind.JAVAC, key, args)); 129 } 130 131 132 /** 133 * Programmatic interface for main function. 134 * @param args the command line parameters 135 * @return the result of the compilation 136 */ 137 public Result compile(String[] args) { 138 Context context = new Context(); 139 JavacFileManager.preRegister(context); // can't create it until Log has been set up 140 Result result = compile(args, context); 141 if (fileManager instanceof JavacFileManager) { 142 // A fresh context was created above, so jfm must be a JavacFileManager 143 ((JavacFileManager)fileManager).close(); 144 } 145 return result; 146 } 147 148 /** 149 * Internal version of compile, allowing context to be provided. 150 * Note that the context needs to have a file manager set up. 151 * @param argv the command line parameters 152 * @param context the context 153 * @return the result of the compilation 154 */ 155 public Result compile(String[] argv, Context context) { 156 context.put(Log.outKey, out); 157 log = Log.instance(context); 158 159 if (argv.length == 0) { 160 Option.HELP.process(new OptionHelper.GrumpyHelper(log) { 161 @Override 162 public String getOwnName() { return ownName; } 163 @Override 164 public void put(String name, String value) { } 165 }, "-help"); 166 return Result.CMDERR; 167 } 168 169 try { 170 argv = CommandLine.parse(argv); 171 } catch (FileNotFoundException | NoSuchFileException e) { 172 warning("err.file.not.found", e.getMessage()); 173 return Result.SYSERR; 174 } catch (IOException ex) { 175 log.printLines(PrefixKind.JAVAC, "msg.io"); 176 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 177 return Result.SYSERR; 178 } 179 180 Arguments args = Arguments.instance(context); 181 args.init(ownName, argv); 182 183 if (log.nerrors > 0) 184 return Result.CMDERR; 185 186 Options options = Options.instance(context); 187 188 // init Log 189 boolean forceStdOut = options.isSet("stdout"); 190 if (forceStdOut) { 191 log.flush(); 192 log.setWriters(new PrintWriter(System.out, true)); 193 } 194 195 // init CacheFSInfo 196 // allow System property in following line as a Mustang legacy 197 boolean batchMode = (options.isUnset("nonBatchMode") 198 && System.getProperty("nonBatchMode") == null); 199 if (batchMode) 200 CacheFSInfo.preRegister(context); 201 202 // init file manager 203 fileManager = context.get(JavaFileManager.class); 204 if (fileManager instanceof BaseFileManager) { 205 ((BaseFileManager) fileManager).setContext(context); // reinit with options 206 ((BaseFileManager) fileManager).handleOptions(args.getDeferredFileManagerOptions()); 207 } 208 209 // handle this here so it works even if no other options given 210 String showClass = options.get("showClass"); 211 if (showClass != null) { 212 if (showClass.equals("showClass")) // no value given for option 213 showClass = "com.sun.tools.javac.Main"; 214 showClass(showClass); 215 } 216 217 boolean ok = args.validate(); 218 if (!ok || log.nerrors > 0) 219 return Result.CMDERR; 220 221 if (args.isEmpty()) 222 return Result.OK; 223 224 // init plugins 225 Set<List<String>> pluginOpts = args.getPluginOpts(); 226 if (!pluginOpts.isEmpty()) { 227 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 228 t.initPlugins(pluginOpts); 229 } 230 231 // init doclint 232 List<String> docLintOpts = args.getDocLintOpts(); 233 if (!docLintOpts.isEmpty()) { 234 BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context); 235 t.initDocLint(docLintOpts); 236 } 237 238 // init Depeendencies 239 if (options.isSet("completionDeps")) { 240 Dependencies.GraphDependencies.preRegister(context); 241 } 242 243 // init JavaCompiler 244 JavaCompiler comp = JavaCompiler.instance(context); 245 if (options.get(Option.XSTDOUT) != null) { 246 // Stdout reassigned - ask compiler to close it when it is done 247 comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE)); 248 } 249 250 try { 251 comp.compile(args.getFileObjects(), args.getClassNames(), null); 252 253 if (log.expectDiagKeys != null) { 254 if (log.expectDiagKeys.isEmpty()) { 255 log.printRawLines("all expected diagnostics found"); 256 return Result.OK; 257 } else { 258 log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys); 259 return Result.ERROR; 260 } 261 } 262 263 return (comp.errorCount() == 0) ? Result.OK : Result.ERROR; 264 265 } catch (OutOfMemoryError | StackOverflowError ex) { 266 resourceMessage(ex); 267 return Result.SYSERR; 268 } catch (FatalError ex) { 269 feMessage(ex, options); 270 return Result.SYSERR; 271 } catch (AnnotationProcessingError ex) { 272 apMessage(ex); 273 return Result.SYSERR; 274 } catch (PropagatedException ex) { 275 // TODO: what about errors from plugins? should not simply rethrow the error here 276 throw ex.getCause(); 277 } catch (Throwable ex) { 278 // Nasty. If we've already reported an error, compensate 279 // for buggy compiler error recovery by swallowing thrown 280 // exceptions. 281 if (comp == null || comp.errorCount() == 0 || options.isSet("dev")) 282 bugMessage(ex); 283 return Result.ABNORMAL; 284 } finally { 285 if (comp != null) { 286 try { 287 comp.close(); 288 } catch (ClientCodeException ex) { 289 throw new RuntimeException(ex.getCause()); 290 } 291 } 292 } 293 } 294 295 /** Print a message reporting an internal error. 296 */ 297 void bugMessage(Throwable ex) { 298 log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version()); 299 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 300 } 301 302 /** Print a message reporting a fatal error. 303 */ 304 void feMessage(Throwable ex, Options options) { 305 log.printRawLines(ex.getMessage()); 306 if (ex.getCause() != null && options.isSet("dev")) { 307 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 308 } 309 } 310 311 /** Print a message reporting an input/output error. 312 */ 313 void ioMessage(Throwable ex) { 314 log.printLines(PrefixKind.JAVAC, "msg.io"); 315 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 316 } 317 318 /** Print a message reporting an out-of-resources error. 319 */ 320 void resourceMessage(Throwable ex) { 321 log.printLines(PrefixKind.JAVAC, "msg.resource"); 322 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 323 } 324 325 /** Print a message reporting an uncaught exception from an 326 * annotation processor. 327 */ 328 void apMessage(AnnotationProcessingError ex) { 329 log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception"); 330 ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE)); 331 } 332 333 /** Print a message reporting an uncaught exception from an 334 * annotation processor. 335 */ 336 void pluginMessage(Throwable ex) { 337 log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception"); 338 ex.printStackTrace(log.getWriter(WriterKind.NOTICE)); 339 } 340 341 /** Display the location and checksum of a class. */ 342 void showClass(String className) { 343 PrintWriter pw = log.getWriter(WriterKind.NOTICE); 344 pw.println("javac: show class: " + className); 345 URL url = getClass().getResource('/' + className.replace('.', '/') + ".class"); 346 if (url == null) 347 pw.println(" class not found"); 348 else { 349 pw.println(" " + url); 350 try { 351 final String algorithm = "MD5"; 352 byte[] digest; 353 MessageDigest md = MessageDigest.getInstance(algorithm); 354 try (DigestInputStream in = new DigestInputStream(url.openStream(), md)) { 355 byte[] buf = new byte[8192]; 356 int n; 357 do { n = in.read(buf); } while (n > 0); 358 digest = md.digest(); 359 } 360 StringBuilder sb = new StringBuilder(); 361 for (byte b: digest) 362 sb.append(String.format("%02x", b)); 363 pw.println(" " + algorithm + " checksum: " + sb); 364 } catch (NoSuchAlgorithmException | IOException e) { 365 pw.println(" cannot compute digest: " + e); 366 } 367 } 368 } 369 370 // TODO: update this to JavacFileManager 371 private JavaFileManager fileManager; 372 373 /* ************************************************************************ 374 * Internationalization 375 *************************************************************************/ 376 377 public static final String javacBundleName = 378 "com.sun.tools.javac.resources.javac"; 379} 380