Main.java revision 2599:50b448c5be54
1/*
2 * Copyright (c) 1999, 2014, 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 */
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.security.DigestInputStream;
33import java.security.MessageDigest;
34import java.security.NoSuchAlgorithmException;
35
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            }, "-help");
164            return Result.CMDERR;
165        }
166
167        try {
168            argv = CommandLine.parse(argv);
169        } catch (FileNotFoundException e) {
170            warning("err.file.not.found", e.getMessage());
171            return Result.SYSERR;
172        } catch (IOException ex) {
173            log.printLines(PrefixKind.JAVAC, "msg.io");
174            ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
175            return Result.SYSERR;
176        }
177
178        Arguments args = Arguments.instance(context);
179        args.init(ownName, argv);
180
181        if (log.nerrors > 0)
182            return Result.CMDERR;
183
184        Options options = Options.instance(context);
185
186        // init Log
187        boolean forceStdOut = options.isSet("stdout");
188        if (forceStdOut) {
189            log.flush();
190            log.setWriters(new PrintWriter(System.out, true));
191        }
192
193        // init CacheFSInfo
194        // allow System property in following line as a Mustang legacy
195        boolean batchMode = (options.isUnset("nonBatchMode")
196                    && System.getProperty("nonBatchMode") == null);
197        if (batchMode)
198            CacheFSInfo.preRegister(context);
199
200        // init file manager
201        fileManager = context.get(JavaFileManager.class);
202        if (fileManager instanceof BaseFileManager) {
203            ((BaseFileManager) fileManager).setContext(context); // reinit with options
204            ((BaseFileManager) fileManager).handleOptions(args.getDeferredFileManagerOptions());
205        }
206
207        // handle this here so it works even if no other options given
208        String showClass = options.get("showClass");
209        if (showClass != null) {
210            if (showClass.equals("showClass")) // no value given for option
211                showClass = "com.sun.tools.javac.Main";
212            showClass(showClass);
213        }
214
215        boolean ok = args.validate();
216        if (!ok || log.nerrors > 0)
217            return Result.CMDERR;
218
219        if (args.isEmpty())
220            return Result.OK;
221
222        // init plugins
223        Set<List<String>> pluginOpts = args.getPluginOpts();
224        if (!pluginOpts.isEmpty()) {
225            BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context);
226            t.initPlugins(pluginOpts);
227        }
228
229        // init doclint
230        List<String> docLintOpts = args.getDocLintOpts();
231        if (!docLintOpts.isEmpty()) {
232            BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context);
233            t.initDocLint(docLintOpts);
234        }
235
236        // init Depeendencies
237        if (options.isSet("completionDeps")) {
238            Dependencies.GraphDependencies.preRegister(context);
239        }
240
241        // init JavaCompiler
242        JavaCompiler comp = JavaCompiler.instance(context);
243        if (options.get(Option.XSTDOUT) != null) {
244            // Stdout reassigned - ask compiler to close it when it is done
245            comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE));
246        }
247
248        try {
249            comp.compile(args.getFileObjects(), args.getClassNames(), null);
250
251            if (log.expectDiagKeys != null) {
252                if (log.expectDiagKeys.isEmpty()) {
253                    log.printRawLines("all expected diagnostics found");
254                    return Result.OK;
255                } else {
256                    log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys);
257                    return Result.ERROR;
258                }
259            }
260
261            return (comp.errorCount() == 0) ? Result.OK : Result.ERROR;
262
263        } catch (OutOfMemoryError | StackOverflowError ex) {
264            resourceMessage(ex);
265            return Result.SYSERR;
266        } catch (FatalError ex) {
267            feMessage(ex, options);
268            return Result.SYSERR;
269        } catch (AnnotationProcessingError ex) {
270            apMessage(ex);
271            return Result.SYSERR;
272        } catch (PropagatedException ex) {
273            // TODO: what about errors from plugins?   should not simply rethrow the error here
274            throw ex.getCause();
275        } catch (Throwable ex) {
276            // Nasty.  If we've already reported an error, compensate
277            // for buggy compiler error recovery by swallowing thrown
278            // exceptions.
279            if (comp == null || comp.errorCount() == 0 || options.isSet("dev"))
280                bugMessage(ex);
281            return Result.ABNORMAL;
282        } finally {
283            if (comp != null) {
284                try {
285                    comp.close();
286                } catch (ClientCodeException ex) {
287                    throw new RuntimeException(ex.getCause());
288                }
289            }
290        }
291    }
292
293    /** Print a message reporting an internal error.
294     */
295    void bugMessage(Throwable ex) {
296        log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version());
297        ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
298    }
299
300    /** Print a message reporting a fatal error.
301     */
302    void feMessage(Throwable ex, Options options) {
303        log.printRawLines(ex.getMessage());
304        if (ex.getCause() != null && options.isSet("dev")) {
305            ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
306        }
307    }
308
309    /** Print a message reporting an input/output error.
310     */
311    void ioMessage(Throwable ex) {
312        log.printLines(PrefixKind.JAVAC, "msg.io");
313        ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
314    }
315
316    /** Print a message reporting an out-of-resources error.
317     */
318    void resourceMessage(Throwable ex) {
319        log.printLines(PrefixKind.JAVAC, "msg.resource");
320        ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
321    }
322
323    /** Print a message reporting an uncaught exception from an
324     * annotation processor.
325     */
326    void apMessage(AnnotationProcessingError ex) {
327        log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception");
328        ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
329    }
330
331    /** Print a message reporting an uncaught exception from an
332     * annotation processor.
333     */
334    void pluginMessage(Throwable ex) {
335        log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception");
336        ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
337    }
338
339    /** Display the location and checksum of a class. */
340    void showClass(String className) {
341        PrintWriter pw = log.getWriter(WriterKind.NOTICE);
342        pw.println("javac: show class: " + className);
343        URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
344        if (url == null)
345            pw.println("  class not found");
346        else {
347            pw.println("  " + url);
348            try {
349                final String algorithm = "MD5";
350                byte[] digest;
351                MessageDigest md = MessageDigest.getInstance(algorithm);
352                try (DigestInputStream in = new DigestInputStream(url.openStream(), md)) {
353                    byte[] buf = new byte[8192];
354                    int n;
355                    do { n = in.read(buf); } while (n > 0);
356                    digest = md.digest();
357                }
358                StringBuilder sb = new StringBuilder();
359                for (byte b: digest)
360                    sb.append(String.format("%02x", b));
361                pw.println("  " + algorithm + " checksum: " + sb);
362            } catch (NoSuchAlgorithmException | IOException e) {
363                pw.println("  cannot compute digest: " + e);
364            }
365        }
366    }
367
368    // TODO: update this to JavacFileManager
369    private JavaFileManager fileManager;
370
371    /* ************************************************************************
372     * Internationalization
373     *************************************************************************/
374
375    public static final String javacBundleName =
376        "com.sun.tools.javac.resources.javac";
377}
378