Path: blob/master/src/java.compiler/share/classes/javax/tools/JavaCompiler.java
41152 views
/*1* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.tools;2627import java.io.Writer;28import java.nio.charset.Charset;29import java.util.Locale;30import java.util.concurrent.Callable;31import javax.annotation.processing.Processor;3233/**34* Interface to invoke Java programming language compilers from35* programs.36*37* <p>The compiler might generate diagnostics during compilation (for38* example, error messages). If a diagnostic listener is provided,39* the diagnostics will be supplied to the listener. If no listener40* is provided, the diagnostics will be formatted in an unspecified41* format and written to the default output, which is {@code42* System.err} unless otherwise specified. Even if a diagnostic43* listener is supplied, some diagnostics might not fit in a {@code44* Diagnostic} and will be written to the default output.45*46* <p>A compiler tool has an associated standard file manager, which47* is the file manager that is native to the tool (or built-in). The48* standard file manager can be obtained by calling {@linkplain49* #getStandardFileManager getStandardFileManager}.50*51* <p>A compiler tool must function with any file manager as long as52* any additional requirements as detailed in the methods below are53* met. If no file manager is provided, the compiler tool will use a54* standard file manager such as the one returned by {@linkplain55* #getStandardFileManager getStandardFileManager}.56*57* <p>An instance implementing this interface must conform to58* <cite>The Java Language Specification</cite>59* and generate class files conforming to60* <cite>The Java Virtual Machine Specification</cite>.61* The versions of these62* specifications are defined in the {@linkplain Tool} interface.63*64* Additionally, an instance of this interface supporting {@link65* javax.lang.model.SourceVersion#RELEASE_6 SourceVersion.RELEASE_6}66* or higher must also support {@linkplain javax.annotation.processing67* annotation processing}.68*69* <p>The compiler relies on two services: {@linkplain70* DiagnosticListener diagnostic listener} and {@linkplain71* JavaFileManager file manager}. Although most classes and72* interfaces in this package defines an API for compilers (and73* tools in general) the interfaces {@linkplain DiagnosticListener},74* {@linkplain JavaFileManager}, {@linkplain FileObject}, and75* {@linkplain JavaFileObject} are not intended to be used in76* applications. Instead these interfaces are intended to be77* implemented and used to provide customized services for a78* compiler and thus defines an SPI for compilers.79*80* <p>There are a number of classes and interfaces in this package81* which are designed to ease the implementation of the SPI to82* customize the behavior of a compiler:83*84* <dl>85* <dt>{@link StandardJavaFileManager}</dt>86* <dd>87*88* Every compiler which implements this interface provides a89* standard file manager for operating on regular {@linkplain90* java.io.File files}. The StandardJavaFileManager interface91* defines additional methods for creating file objects from92* regular files.93*94* <p>The standard file manager serves two purposes:95*96* <ul>97* <li>basic building block for customizing how a compiler reads98* and writes files</li>99* <li>sharing between multiple compilation tasks</li>100* </ul>101*102* <p>Reusing a file manager can potentially reduce overhead of103* scanning the file system and reading jar files. Although there104* might be no reduction in overhead, a standard file manager must105* work with multiple sequential compilations making the following106* example a recommended coding pattern:107*108* <pre>109* File[] files1 = ... ; // input for first compilation task110* File[] files2 = ... ; // input for second compilation task111*112* JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();113* StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);114*115* {@code Iterable<? extends JavaFileObject>} compilationUnits1 =116* fileManager.getJavaFileObjectsFromFiles({@linkplain java.util.Arrays#asList Arrays.asList}(files1));117* compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();118*119* {@code Iterable<? extends JavaFileObject>} compilationUnits2 =120* fileManager.getJavaFileObjects(files2); // use alternative method121* // reuse the same file manager to allow caching of jar files122* compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();123*124* fileManager.close();</pre>125*126* </dd>127*128* <dt>{@link DiagnosticCollector}</dt>129* <dd>130* Used to collect diagnostics in a list, for example:131* <pre>132* {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;133* JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();134* {@code DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();}135* StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);136* compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();137*138* for ({@code Diagnostic<? extends JavaFileObject>} diagnostic : diagnostics.getDiagnostics())139* System.out.format("Error on line %d in %s%n",140* diagnostic.getLineNumber(),141* diagnostic.getSource().toUri());142*143* fileManager.close();</pre>144* </dd>145*146* <dt>147* {@link ForwardingJavaFileManager}, {@link ForwardingFileObject}, and148* {@link ForwardingJavaFileObject}149* </dt>150* <dd>151*152* Subclassing is not available for overriding the behavior of a153* standard file manager as it is created by calling a method on a154* compiler, not by invoking a constructor. Instead forwarding155* (or delegation) should be used. These classes makes it easy to156* forward most calls to a given file manager or file object while157* allowing customizing behavior. For example, consider how to158* log all calls to {@linkplain JavaFileManager#flush}:159*160* <pre>161* final Logger logger = ...;162* {@code Iterable<? extends JavaFileObject>} compilationUnits = ...;163* JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();164* StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);165* JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {166* public void flush() throws IOException {167* logger.entering(StandardJavaFileManager.class.getName(), "flush");168* super.flush();169* logger.exiting(StandardJavaFileManager.class.getName(), "flush");170* }171* };172* compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();</pre>173* </dd>174*175* <dt>{@link SimpleJavaFileObject}</dt>176* <dd>177*178* This class provides a basic file object implementation which179* can be used as building block for creating file objects. For180* example, here is how to define a file object which represent181* source code stored in a string:182*183* <pre>184* /**185* * A file object used to represent source coming from a string.186* {@code *}/187* public class JavaSourceFromString extends SimpleJavaFileObject {188* /**189* * The source code of this "file".190* {@code *}/191* final String code;192*193* /**194* * Constructs a new JavaSourceFromString.195* * {@code @}param name the name of the compilation unit represented by this file object196* * {@code @}param code the source code for the compilation unit represented by this file object197* {@code *}/198* JavaSourceFromString(String name, String code) {199* super({@linkplain java.net.URI#create URI.create}("string:///" + name.replace('.','/') + Kind.SOURCE.extension),200* Kind.SOURCE);201* this.code = code;202* }203*204* {@code @}Override205* public CharSequence getCharContent(boolean ignoreEncodingErrors) {206* return code;207* }208* }</pre>209* </dd>210* </dl>211*212* @author Peter von der Ahé213* @author Jonathan Gibbons214* @see DiagnosticListener215* @see Diagnostic216* @see JavaFileManager217* @since 1.6218*/219public interface JavaCompiler extends Tool, OptionChecker {220221/**222* Creates a future for a compilation task with the given223* components and arguments. The compilation might not have224* completed as described in the CompilationTask interface.225*226* <p>If a file manager is provided, it must be able to handle all227* locations defined in {@link StandardLocation}.228*229* <p>Note that annotation processing can process both the230* compilation units of source code to be compiled, passed with231* the {@code compilationUnits} parameter, as well as class232* files, whose names are passed with the {@code classes}233* parameter.234*235* @param out a Writer for additional output from the compiler;236* use {@code System.err} if {@code null}237* @param fileManager a file manager; if {@code null} use the238* compiler's standard file manager239* @param diagnosticListener a diagnostic listener; if {@code240* null} use the compiler's default method for reporting241* diagnostics242* @param options compiler options, {@code null} means no options243* @param classes names of classes to be processed by annotation244* processing, {@code null} means no class names245* @param compilationUnits the compilation units to compile, {@code246* null} means no compilation units247* @return an object representing the compilation248* @throws RuntimeException if an unrecoverable error249* occurred in a user supplied component. The250* {@linkplain Throwable#getCause() cause} will be the error in251* user code.252* @throws IllegalArgumentException if any of the options are invalid,253* or if any of the given compilation units are of other kind than254* {@linkplain JavaFileObject.Kind#SOURCE source}255*/256CompilationTask getTask(Writer out,257JavaFileManager fileManager,258DiagnosticListener<? super JavaFileObject> diagnosticListener,259Iterable<String> options,260Iterable<String> classes,261Iterable<? extends JavaFileObject> compilationUnits);262263/**264* Returns a new instance of the standard file manager implementation265* for this tool. The file manager will use the given diagnostic266* listener for producing any non-fatal diagnostics. Fatal errors267* will be signaled with the appropriate exceptions.268*269* <p>The standard file manager will be automatically reopened if270* it is accessed after calls to {@code flush} or {@code close}.271* The standard file manager must be usable with other tools.272*273* @param diagnosticListener a diagnostic listener for non-fatal274* diagnostics; if {@code null} use the compiler's default method275* for reporting diagnostics276* @param locale the locale to apply when formatting diagnostics;277* {@code null} means the {@linkplain Locale#getDefault() default locale}.278* @param charset the character set used for decoding bytes; if279* {@code null} use the platform default280* @return the standard file manager281*/282StandardJavaFileManager getStandardFileManager(283DiagnosticListener<? super JavaFileObject> diagnosticListener,284Locale locale,285Charset charset);286287/**288* Interface representing a future for a compilation task. The289* compilation task has not yet started. To start the task, call290* the {@linkplain #call call} method.291*292* <p>Before calling the {@code call} method, additional aspects of the293* task can be configured, for example, by calling the294* {@linkplain #setProcessors setProcessors} method.295*/296interface CompilationTask extends Callable<Boolean> {297/**298* Adds root modules to be taken into account during module299* resolution.300* Invalid module names may cause either301* {@code IllegalArgumentException} to be thrown,302* or diagnostics to be reported when the task is started.303* @param moduleNames the names of the root modules304* @throws IllegalArgumentException may be thrown for some305* invalid module names306* @throws IllegalStateException if the task has started307* @since 9308*/309void addModules(Iterable<String> moduleNames);310311/**312* Sets processors (for annotation processing). This will313* bypass the normal discovery mechanism.314*315* @param processors processors (for annotation processing)316* @throws IllegalStateException if the task has started317*/318void setProcessors(Iterable<? extends Processor> processors);319320/**321* Sets the locale to be applied when formatting diagnostics and322* other localized data.323*324* @param locale the locale to apply; {@code null} means apply no325* locale326* @throws IllegalStateException if the task has started327*/328void setLocale(Locale locale);329330/**331* Performs this compilation task. The compilation may only332* be performed once. Subsequent calls to this method throw333* {@code IllegalStateException}.334*335* @return true if and only all the files compiled without errors;336* false otherwise337*338* @throws RuntimeException if an unrecoverable error occurred339* in a user-supplied component. The340* {@linkplain Throwable#getCause() cause} will be the error341* in user code.342* @throws IllegalStateException if called more than once343*/344@Override345Boolean call();346}347}348349350