Path: blob/aarch64-shenandoah-jdk8u272-b10/langtools/src/share/classes/javax/tools/JavaCompiler.java
38900 views
/*1* Copyright (c) 2005, 2013, 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.File;28import java.io.Writer;29import java.nio.charset.Charset;30import java.util.Locale;31import java.util.concurrent.Callable;32import javax.annotation.processing.Processor;3334/**35* Interface to invoke Java™ programming language compilers from36* programs.37*38* <p>The compiler might generate diagnostics during compilation (for39* example, error messages). If a diagnostic listener is provided,40* the diagnostics will be supplied to the listener. If no listener41* is provided, the diagnostics will be formatted in an unspecified42* format and written to the default output, which is {@code43* System.err} unless otherwise specified. Even if a diagnostic44* listener is supplied, some diagnostics might not fit in a {@code45* Diagnostic} and will be written to the default output.46*47* <p>A compiler tool has an associated standard file manager, which48* is the file manager that is native to the tool (or built-in). The49* standard file manager can be obtained by calling {@linkplain50* #getStandardFileManager getStandardFileManager}.51*52* <p>A compiler tool must function with any file manager as long as53* any additional requirements as detailed in the methods below are54* met. If no file manager is provided, the compiler tool will use a55* standard file manager such as the one returned by {@linkplain56* #getStandardFileManager getStandardFileManager}.57*58* <p>An instance implementing this interface must conform to59* <cite>The Java™ Language Specification</cite>60* and generate class files conforming to61* <cite>The Java™ Virtual Machine Specification</cite>.62* The versions of these63* specifications are defined in the {@linkplain Tool} interface.64*65* Additionally, an instance of this interface supporting {@link66* javax.lang.model.SourceVersion#RELEASE_6 SourceVersion.RELEASE_6}67* or higher must also support {@linkplain javax.annotation.processing68* annotation processing}.69*70* <p>The compiler relies on two services: {@linkplain71* DiagnosticListener diagnostic listener} and {@linkplain72* JavaFileManager file manager}. Although most classes and73* interfaces in this package defines an API for compilers (and74* tools in general) the interfaces {@linkplain DiagnosticListener},75* {@linkplain JavaFileManager}, {@linkplain FileObject}, and76* {@linkplain JavaFileObject} are not intended to be used in77* applications. Instead these interfaces are intended to be78* implemented and used to provide customized services for a79* compiler and thus defines an SPI for compilers.80*81* <p>There are a number of classes and interfaces in this package82* which are designed to ease the implementation of the SPI to83* 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 a90* standard file manager for operating on regular {@linkplain91* java.io.File files}. The StandardJavaFileManager interface92* defines additional methods for creating file objects from93* 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 reads99* 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 of104* scanning the file system and reading jar files. Although there105* might be no reduction in overhead, a standard file manager must106* work with multiple sequential compilations making the following107* example a recommended coding pattern:108*109* <pre>110* File[] files1 = ... ; // input for first compilation task111* File[] files2 = ... ; // input for second compilation task112*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 method122* // reuse the same file manager to allow caching of jar files123* 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}, and149* {@link ForwardingJavaFileObject}150* </dt>151* <dd>152*153* Subclassing is not available for overriding the behavior of a154* standard file manager as it is created by calling a method on a155* compiler, not by invoking a constructor. Instead forwarding156* (or delegation) should be used. These classes makes it easy to157* forward most calls to a given file manager or file object while158* allowing customizing behavior. For example, consider how to159* log all calls to {@linkplain JavaFileManager#flush}:160*161* <pre>162* final {@linkplain java.util.logging.Logger 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 which180* can be used as building block for creating file objects. For181* example, here is how to define a file object which represent182* 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 object197* * {@code @}param code the source code for the compilation unit represented by this file object198* {@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 @}Override206* public CharSequence getCharContent(boolean ignoreEncodingErrors) {207* return code;208* }209* }</pre>210* </dd>211* </dl>212*213* @author Peter von der Ahé214* @author Jonathan Gibbons215* @see DiagnosticListener216* @see Diagnostic217* @see JavaFileManager218* @since 1.6219*/220public interface JavaCompiler extends Tool, OptionChecker {221222/**223* Creates a future for a compilation task with the given224* components and arguments. The compilation might not have225* completed as described in the CompilationTask interface.226*227* <p>If a file manager is provided, it must be able to handle all228* locations defined in {@link StandardLocation}.229*230* <p>Note that annotation processing can process both the231* compilation units of source code to be compiled, passed with232* the {@code compilationUnits} parameter, as well as class233* 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 the239* compiler's standard filemanager240* @param diagnosticListener a diagnostic listener; if {@code241* null} use the compiler's default method for reporting242* diagnostics243* @param options compiler options, {@code null} means no options244* @param classes names of classes to be processed by annotation245* processing, {@code null} means no class names246* @param compilationUnits the compilation units to compile, {@code247* null} means no compilation units248* @return an object representing the compilation249* @throws RuntimeException if an unrecoverable error250* occurred in a user supplied component. The251* {@linkplain Throwable#getCause() cause} will be the error in252* 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 than255* {@linkplain JavaFileObject.Kind#SOURCE source}256*/257CompilationTask getTask(Writer out,258JavaFileManager fileManager,259DiagnosticListener<? super JavaFileObject> diagnosticListener,260Iterable<String> options,261Iterable<String> classes,262Iterable<? extends JavaFileObject> compilationUnits);263264/**265* Gets a new instance of the standard file manager implementation266* for this tool. The file manager will use the given diagnostic267* listener for producing any non-fatal diagnostics. Fatal errors268* will be signaled with the appropriate exceptions.269*270* <p>The standard file manager will be automatically reopened if271* 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-fatal275* diagnostics; if {@code null} use the compiler's default method276* for reporting diagnostics277* @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; if280* {@code null} use the platform default281* @return the standard file manager282*/283StandardJavaFileManager getStandardFileManager(284DiagnosticListener<? super JavaFileObject> diagnosticListener,285Locale locale,286Charset charset);287288/**289* Interface representing a future for a compilation task. The290* compilation task has not yet started. To start the task, call291* the {@linkplain #call call} method.292*293* <p>Before calling the call method, additional aspects of the294* task can be configured, for example, by calling the295* {@linkplain #setProcessors setProcessors} method.296*/297interface CompilationTask extends Callable<Boolean> {298299/**300* Sets processors (for annotation processing). This will301* bypass the normal discovery mechanism.302*303* @param processors processors (for annotation processing)304* @throws IllegalStateException if the task has started305*/306void setProcessors(Iterable<? extends Processor> processors);307308/**309* Set the locale to be applied when formatting diagnostics and310* other localized data.311*312* @param locale the locale to apply; {@code null} means apply no313* locale314* @throws IllegalStateException if the task has started315*/316void setLocale(Locale locale);317318/**319* Performs this compilation task. The compilation may only320* be performed once. Subsequent calls to this method throw321* IllegalStateException.322*323* @return true if and only all the files compiled without errors;324* false otherwise325*326* @throws RuntimeException if an unrecoverable error occurred327* in a user-supplied component. The328* {@linkplain Throwable#getCause() cause} will be the error329* in user code.330* @throws IllegalStateException if called more than once331*/332Boolean call();333}334}335336337