JavaCompiler.java revision 4049:2340259b3155
1/*
2 * Copyright (c) 2005, 2017, 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 javax.tools;
27
28import java.io.Writer;
29import java.nio.charset.Charset;
30import java.util.Locale;
31import java.util.concurrent.Callable;
32import javax.annotation.processing.Processor;
33
34/**
35 * Interface to invoke Java™ programming language compilers from
36 * programs.
37 *
38 * <p>The compiler might generate diagnostics during compilation (for
39 * example, error messages).  If a diagnostic listener is provided,
40 * the diagnostics will be supplied to the listener.  If no listener
41 * is provided, the diagnostics will be formatted in an unspecified
42 * format and written to the default output, which is {@code
43 * System.err} unless otherwise specified.  Even if a diagnostic
44 * listener is supplied, some diagnostics might not fit in a {@code
45 * Diagnostic} and will be written to the default output.
46 *
47 * <p>A compiler tool has an associated standard file manager, which
48 * is the file manager that is native to the tool (or built-in).  The
49 * standard file manager can be obtained by calling {@linkplain
50 * #getStandardFileManager getStandardFileManager}.
51 *
52 * <p>A compiler tool must function with any file manager as long as
53 * any additional requirements as detailed in the methods below are
54 * met.  If no file manager is provided, the compiler tool will use a
55 * standard file manager such as the one returned by {@linkplain
56 * #getStandardFileManager getStandardFileManager}.
57 *
58 * <p>An instance implementing this interface must conform to
59 * <cite>The Java&trade; Language Specification</cite>
60 * and generate class files conforming to
61 * <cite>The Java&trade; Virtual Machine Specification</cite>.
62 * The versions of these
63 * specifications are defined in the {@linkplain Tool} interface.
64 *
65 * Additionally, an instance of this interface supporting {@link
66 * javax.lang.model.SourceVersion#RELEASE_6 SourceVersion.RELEASE_6}
67 * or higher must also support {@linkplain javax.annotation.processing
68 * annotation processing}.
69 *
70 * <p>The compiler relies on two services: {@linkplain
71 * DiagnosticListener diagnostic listener} and {@linkplain
72 * JavaFileManager file manager}.  Although most classes and
73 * interfaces in this package defines an API for compilers (and
74 * tools in general) the interfaces {@linkplain DiagnosticListener},
75 * {@linkplain JavaFileManager}, {@linkplain FileObject}, and
76 * {@linkplain JavaFileObject} are not intended to be used in
77 * applications.  Instead these interfaces are intended to be
78 * implemented and used to provide customized services for a
79 * compiler and thus defines an SPI for compilers.
80 *
81 * <p>There are a number of classes and interfaces in this package
82 * which are designed to ease the implementation of the SPI to
83 * customize the behavior of a compiler:
84 *
85 * <dl>
86 *   <dt>{@link StandardJavaFileManager}</dt>
87 *   <dd>
88 *
89 *     Every compiler which implements this interface provides a
90 *     standard file manager for operating on regular {@linkplain
91 *     java.io.File files}.  The StandardJavaFileManager interface
92 *     defines additional methods for creating file objects from
93 *     regular files.
94 *
95 *     <p>The standard file manager serves two purposes:
96 *
97 *     <ul>
98 *       <li>basic building block for customizing how a compiler reads
99 *       and writes files</li>
100 *       <li>sharing between multiple compilation tasks</li>
101 *     </ul>
102 *
103 *     <p>Reusing a file manager can potentially reduce overhead of
104 *     scanning the file system and reading jar files.  Although there
105 *     might be no reduction in overhead, a standard file manager must
106 *     work with multiple sequential compilations making the following
107 *     example a recommended coding pattern:
108 *
109 *     <pre>
110 *       File[] files1 = ... ; // input for first compilation task
111 *       File[] files2 = ... ; // input for second compilation task
112 *
113 *       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
114 *       StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
115 *
116 *       {@code Iterable<? extends JavaFileObject>} compilationUnits1 =
117 *           fileManager.getJavaFileObjectsFromFiles({@linkplain java.util.Arrays#asList Arrays.asList}(files1));
118 *       compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
119 *
120 *       {@code Iterable<? extends JavaFileObject>} compilationUnits2 =
121 *           fileManager.getJavaFileObjects(files2); // use alternative method
122 *       // reuse the same file manager to allow caching of jar files
123 *       compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();
124 *
125 *       fileManager.close();</pre>
126 *
127 *   </dd>
128 *
129 *   <dt>{@link DiagnosticCollector}</dt>
130 *   <dd>
131 *     Used to collect diagnostics in a list, for example:
132 *     <pre>
133 *       {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;
134 *       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
135 *       {@code DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();}
136 *       StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
137 *       compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
138 *
139 *       for ({@code Diagnostic<? extends JavaFileObject>} diagnostic : diagnostics.getDiagnostics())
140 *           System.out.format("Error on line %d in %s%n",
141 *                             diagnostic.getLineNumber(),
142 *                             diagnostic.getSource().toUri());
143 *
144 *       fileManager.close();</pre>
145 *   </dd>
146 *
147 *   <dt>
148 *     {@link ForwardingJavaFileManager}, {@link ForwardingFileObject}, and
149 *     {@link ForwardingJavaFileObject}
150 *   </dt>
151 *   <dd>
152 *
153 *     Subclassing is not available for overriding the behavior of a
154 *     standard file manager as it is created by calling a method on a
155 *     compiler, not by invoking a constructor.  Instead forwarding
156 *     (or delegation) should be used.  These classes makes it easy to
157 *     forward most calls to a given file manager or file object while
158 *     allowing customizing behavior.  For example, consider how to
159 *     log all calls to {@linkplain JavaFileManager#flush}:
160 *
161 *     <pre>
162 *       final  Logger logger = ...;
163 *       {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;
164 *       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
165 *       StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
166 *       JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {
167 *           public void flush() throws IOException {
168 *               logger.entering(StandardJavaFileManager.class.getName(), "flush");
169 *               super.flush();
170 *               logger.exiting(StandardJavaFileManager.class.getName(), "flush");
171 *           }
172 *       };
173 *       compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();</pre>
174 *   </dd>
175 *
176 *   <dt>{@link SimpleJavaFileObject}</dt>
177 *   <dd>
178 *
179 *     This class provides a basic file object implementation which
180 *     can be used as building block for creating file objects.  For
181 *     example, here is how to define a file object which represent
182 *     source code stored in a string:
183 *
184 *     <pre>
185 *       /**
186 *        * A file object used to represent source coming from a string.
187 *        {@code *}/
188 *       public class JavaSourceFromString extends SimpleJavaFileObject {
189 *           /**
190 *            * The source code of this "file".
191 *            {@code *}/
192 *           final String code;
193 *
194 *           /**
195 *            * Constructs a new JavaSourceFromString.
196 *            * {@code @}param name the name of the compilation unit represented by this file object
197 *            * {@code @}param code the source code for the compilation unit represented by this file object
198 *            {@code *}/
199 *           JavaSourceFromString(String name, String code) {
200 *               super({@linkplain java.net.URI#create URI.create}("string:///" + name.replace('.','/') + Kind.SOURCE.extension),
201 *                     Kind.SOURCE);
202 *               this.code = code;
203 *           }
204 *
205 *           {@code @}Override
206 *           public CharSequence getCharContent(boolean ignoreEncodingErrors) {
207 *               return code;
208 *           }
209 *       }</pre>
210 *   </dd>
211 * </dl>
212 *
213 * @author Peter von der Ah&eacute;
214 * @author Jonathan Gibbons
215 * @see DiagnosticListener
216 * @see Diagnostic
217 * @see JavaFileManager
218 * @since 1.6
219 */
220public interface JavaCompiler extends Tool, OptionChecker {
221
222    /**
223     * Creates a future for a compilation task with the given
224     * components and arguments.  The compilation might not have
225     * completed as described in the CompilationTask interface.
226     *
227     * <p>If a file manager is provided, it must be able to handle all
228     * locations defined in {@link StandardLocation}.
229     *
230     * <p>Note that annotation processing can process both the
231     * compilation units of source code to be compiled, passed with
232     * the {@code compilationUnits} parameter, as well as class
233     * files, whose names are passed with the {@code classes}
234     * parameter.
235     *
236     * @param out a Writer for additional output from the compiler;
237     * use {@code System.err} if {@code null}
238     * @param fileManager a file manager; if {@code null} use the
239     * compiler's standard filemanager
240     * @param diagnosticListener a diagnostic listener; if {@code
241     * null} use the compiler's default method for reporting
242     * diagnostics
243     * @param options compiler options, {@code null} means no options
244     * @param classes names of classes to be processed by annotation
245     * processing, {@code null} means no class names
246     * @param compilationUnits the compilation units to compile, {@code
247     * null} means no compilation units
248     * @return an object representing the compilation
249     * @throws RuntimeException if an unrecoverable error
250     * occurred in a user supplied component.  The
251     * {@linkplain Throwable#getCause() cause} will be the error in
252     * user code.
253     * @throws IllegalArgumentException if any of the options are invalid,
254     * or if any of the given compilation units are of other kind than
255     * {@linkplain JavaFileObject.Kind#SOURCE source}
256     */
257    CompilationTask getTask(Writer out,
258                            JavaFileManager fileManager,
259                            DiagnosticListener<? super JavaFileObject> diagnosticListener,
260                            Iterable<String> options,
261                            Iterable<String> classes,
262                            Iterable<? extends JavaFileObject> compilationUnits);
263
264    /**
265     * Returns a new instance of the standard file manager implementation
266     * for this tool.  The file manager will use the given diagnostic
267     * listener for producing any non-fatal diagnostics.  Fatal errors
268     * will be signaled with the appropriate exceptions.
269     *
270     * <p>The standard file manager will be automatically reopened if
271     * it is accessed after calls to {@code flush} or {@code close}.
272     * The standard file manager must be usable with other tools.
273     *
274     * @param diagnosticListener a diagnostic listener for non-fatal
275     * diagnostics; if {@code null} use the compiler's default method
276     * for reporting diagnostics
277     * @param locale the locale to apply when formatting diagnostics;
278     * {@code null} means the {@linkplain Locale#getDefault() default locale}.
279     * @param charset the character set used for decoding bytes; if
280     * {@code null} use the platform default
281     * @return the standard file manager
282     */
283    StandardJavaFileManager getStandardFileManager(
284        DiagnosticListener<? super JavaFileObject> diagnosticListener,
285        Locale locale,
286        Charset charset);
287
288    /**
289     * Interface representing a future for a compilation task.  The
290     * compilation task has not yet started.  To start the task, call
291     * the {@linkplain #call call} method.
292     *
293     * <p>Before calling the call method, additional aspects of the
294     * task can be configured, for example, by calling the
295     * {@linkplain #setProcessors setProcessors} method.
296     */
297    interface CompilationTask extends Callable<Boolean> {
298        /**
299         * Adds root modules to be taken into account during module
300         * resolution.
301         * Invalid module names may cause either
302         * {@code IllegalArgumentException} to be thrown,
303         * or diagnostics to be reported when the task is started.
304         * @param moduleNames the names of the root modules
305         * @throws IllegalArgumentException may be thrown for some
306         *      invalid module names
307         * @throws IllegalStateException if the task has started
308         * @since 9
309         */
310        void addModules(Iterable<String> moduleNames);
311
312        /**
313         * Sets processors (for annotation processing).  This will
314         * bypass the normal discovery mechanism.
315         *
316         * @param processors processors (for annotation processing)
317         * @throws IllegalStateException if the task has started
318         */
319        void setProcessors(Iterable<? extends Processor> processors);
320
321        /**
322         * Sets the locale to be applied when formatting diagnostics and
323         * other localized data.
324         *
325         * @param locale the locale to apply; {@code null} means apply no
326         * locale
327         * @throws IllegalStateException if the task has started
328         */
329        void setLocale(Locale locale);
330
331        /**
332         * Performs this compilation task.  The compilation may only
333         * be performed once.  Subsequent calls to this method throw
334         * IllegalStateException.
335         *
336         * @return true if and only all the files compiled without errors;
337         * false otherwise
338         *
339         * @throws RuntimeException if an unrecoverable error occurred
340         * in a user-supplied component.  The
341         * {@linkplain Throwable#getCause() cause} will be the error
342         * in user code.
343         * @throws IllegalStateException if called more than once
344         */
345        @Override
346        Boolean call();
347    }
348}
349