/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/** This class could be the main entry point for GJC when GJC is used as a
* component in a larger software system. It provides operations to
* construct a new compiler, and to run a new compiler on a set of source
* files.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
/** The context key for the compiler. */
/** Get the JavaCompiler instance for this context. */
return instance;
}
/** The current version number as a string.
*/
}
/** The current full version number as a string.
*/
}
try {
} catch (MissingResourceException e) {
}
}
try {
}
catch (MissingResourceException e) {
}
}
/**
* Control how the compiler's latter phases (attr, flow, desugar, generate)
* are connected. Each individual file is processed by each phase in turn,
* but with different compile policies, you can control the order in which
* each class is processed through its next phase.
*
* <p>Generally speaking, the compiler will "fail fast" in the face of
* errors, although not aggressively so. flow, desugar, etc become no-ops
* once any errors have occurred. No attempt is currently made to determine
* if it might be safe to process a class through its next phase because
* it does not depend on any unrelated errors that might have occurred.
*/
protected static enum CompilePolicy {
/**
* Just attribute the parse trees.
*/
/**
* Just attribute and do flow analysis on the parse trees.
* This should catch most user errors.
*/
/**
* Attribute everything, then do flow analysis for everything,
* then desugar everything, and only then generate output.
* This means no output will be generated if there are any
* errors in any classes.
*/
/**
* Groups the classes for each source file together, then process
* each group in a manner equivalent to the {@code SIMPLE} policy.
* This means no output will be generated if there are any
* errors in any of the classes in a source file.
*/
/**
* Completely process each entry on the todo list in turn.
* -- this is the same for 1.5.
* Means output might be generated for some classes in a compilation unit
* and not others.
*/
return DEFAULT_COMPILE_POLICY;
return ATTR_ONLY;
return CHECK_ONLY;
return SIMPLE;
return BY_FILE;
return BY_TODO;
else
return DEFAULT_COMPILE_POLICY;
}
}
protected static enum ImplicitSourcePolicy {
/** Don't generate or process implicitly read source files. */
NONE,
/** Generate classes for implicitly read source files. */
/** Like CLASS, but generate warnings if annotation processing occurs */
return UNSET;
return NONE;
return CLASS;
else
return UNSET;
}
}
/** The log to be used for error reporting.
*/
/** Factory for creating diagnostic objects
*/
/** The tree factory module.
*/
/** The class reader.
*/
/** The class writer.
*/
/** The module for the symbol table entry phases.
*/
/** The symbol table.
*/
/** The language version.
*/
/** The module for code generation.
*/
/** The name table.
*/
/** The attributor.
*/
/** The attributor.
*/
/** The flow analyzer.
*/
/** The type eraser.
*/
/** The syntactic sugar desweetener.
*/
/** The annotation annotator.
*/
/** Force a completion failure on this name
*/
/** Type utilities.
*/
/** Access to file objects.
*/
/** Factory for parsers.
*/
/** Optional listener for progress events
*/
/**
* Annotation processing may require and provide a new instance
* of the compiler to be used for the analyze and generate phases.
*/
/**
* Command line options.
*/
/**
* Flag set if any annotation processing occurred.
**/
protected boolean annotationProcessingOccurred;
/**
* Flag set if any implicit source files read.
**/
protected boolean implicitSourceFilesRead;
/** Construct a new compiler using a shared context.
*/
// if fileManager not already set, register the JavacFileManager to be used
try {
// catch completion problems with predefineds
} catch (CompletionFailure ex) {
// inlined Check.completionError as it is not initialized yet
throw new Abort();
}
reader.sourceCompleter = this;
if (fileManager instanceof BaseFileManager) {
}
}
}
if (attrParseOnly)
else
: null;
: null;
}
/* Switches:
*/
/** Verbose output.
*/
public boolean verbose;
/** Emit plain Java source files rather than class files.
*/
public boolean sourceOutput;
/** Emit stub source files rather than class files.
*/
public boolean stubOutput;
/** Generate attributed parse tree only.
*/
public boolean attrParseOnly;
/** Switch: relax some constraints for producing the jsr14 prototype.
*/
boolean relax;
/** Debug switch: Emit Java sources after inner class flattening.
*/
public boolean printFlat;
/** The encoding to be used for source input.
*/
/** Generate code with the LineNumberTable attribute for debugging
*/
public boolean lineDebugInfo;
/** Switch: should we store the ending positions?
*/
public boolean genEndPos;
/** Switch: should we debug ignored exceptions
*/
protected boolean devVerbose;
/** Switch: should we (annotation) process packages as well
*/
protected boolean processPcks;
/** Switch: treat warnings as errors
*/
protected boolean werror;
/** Switch: is annotation processing requested explitly via
* CompilationTask.setProcessors?
*/
protected boolean explicitAnnotationProcessingRequested = false;
/**
* The policy for the order in which to perform the compilation
*/
/**
* The policy for what to do with implicitly read source files
*/
/**
* Report activity related to compilePolicy
*/
public boolean verboseCompilePolicy;
/**
* Policy of how far to continue processing. null means until first
* error.
*/
/** A queue of all as yet unattributed classes.
*/
/** Ordered list of compiler phases for each compilation unit. */
public enum CompileState {
}
}
private int value;
};
/** Partial map to record which compiler phases have been executed
* for each compilation unit. Used for ATTR and FLOW phases.
*/
}
}
/** The set of currently compiled inputfiles, needed to ensure
* we don't accidentally overwrite an input file when -s is set.
* initialized by `compile'.
*/
if (shouldStopPolicy == null)
else
}
/** The number of errors reported so far.
*/
public int errorCount() {
return delegateCompiler.errorCount();
else {
}
}
}
}
}
/** The number of warnings reported so far.
*/
public int warningCount() {
return delegateCompiler.warningCount();
else
}
/** Try to open input stream with given name.
* Report an error if this fails.
* @param filename The file name of the input stream to be opened.
*/
try {
return filename.getCharContent(false);
} catch (IOException e) {
return null;
}
}
/** Parse contents of input stream.
* @param filename The name of the file from which input stream comes.
* @param input The input stream to be parsed.
*/
if (verbose) {
}
if (taskListener != null) {
taskListener.started(e);
}
if (verbose) {
}
}
taskListener.finished(e);
}
return tree;
}
// where
public boolean keepComments = false;
protected boolean keepComments() {
}
/** Parse contents of file.
* @param filename The name of the file to be parsed.
*/
}
/** Parse contents of file.
* @param filename The name of the file to be parsed.
*/
try {
if (t.endPositions != null)
return t;
} finally {
}
}
/** Resolve an identifier which may be the binary name of a class or
* the Java name of a class or package.
* @param name The name to resolve
*/
try {
} catch (CompletionFailure ignore) {
return resolveIdent(name);
}
}
/** Resolve an identifier.
* @param name The identifier to resolve
*/
try {
}
} finally {
}
}
/** Emit plain Java source for a class.
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition to be printed.
*/
null);
return null;
} else {
try {
if (verbose)
} finally {
}
return outFile;
}
}
/** Generate code and emit a class file for a given class
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition from which code is generated.
*/
try {
} catch (CompletionFailure ex) {
}
return null;
}
/** Complete compiling a source file that has been accessed
* by the class file reader.
* @param c The class the source file of which needs to be compiled.
* @param filename The name of the source file.
* @param f An input stream that reads the source file.
*/
// System.err.println("completing " + c);//DEBUG
if (completionFailureName == c.fullname) {
throw new CompletionFailure(c, "user-selected completion failure by class name");
}
try {
} catch (IOException e) {
} finally {
}
if (taskListener != null) {
taskListener.started(e);
}
if (taskListener != null) {
taskListener.finished(e);
}
boolean isPkgInfo =
if (isPkgInfo) {
c.location());
}
} else {
c.getQualifiedName());
}
}
implicitSourceFilesRead = true;
}
/** Track when the JavaCompiler has been used to compile something. */
private boolean hasBeenUsed = false;
throws Throwable {
}
/**
* Main method: compile a list of files, return all compiled classes
*
* @param sourceFileObjects file objects to be compiled
* @param classnames class names to process for annotations
* @param processors user provided annotation processors to bypass
* discovery, {@code null} means that no processors were provided
*/
{
// as a JavaCompiler can only be used once, throw an exception if
// it has been used before.
if (hasBeenUsed)
throw new AssertionError("attempt to reuse JavaCompiler");
hasBeenUsed = true;
// forcibly set the equivalent of -Xlint:-options, so that no further
// warnings about command line options are generated from this point on
start_msec = now();
try {
// These method calls must be chained to avoid memory leaks
if (devVerbose)
} finally {
if (procEnvImpl != null)
procEnvImpl.close();
}
}
/**
* The phases following annotation processing: attribution,
* desugar, and finally code generation.
*/
private void compile2() {
try {
switch (compilePolicy) {
case ATTR_ONLY:
break;
case CHECK_ONLY:
break;
case SIMPLE:
break;
case BY_FILE: {
}
}
break;
case BY_TODO:
break;
default:
}
if (devVerbose)
}
if (verbose) {
}
if (!log.hasDiagnosticListener()) {
}
}
/**
* Parses a list of files.
*/
//parse all files
}
}
}
/**
* Enter the symbols found in a list of parse trees.
* As a side-effect, this puts elements on the "todo" list.
* Also stores a list of all top level classes in rootClasses.
*/
//enter symbols for all files
if (taskListener != null) {
taskListener.started(e);
}
}
if (taskListener != null) {
taskListener.finished(e);
}
}
//If generating source, remember the classes declared in
//the original compilation units listed on the command line.
if (sourceOutput || stubOutput) {
}
}
}
// Ensure the input files have been recorded. Although this is normally
// done by readSource, it may not have been done if the trees were read
// in a prior round of annotation processing, and the trees have been
// cleaned and are being reused.
}
return roots;
}
/**
* Set to true to enable skeleton annotation processing code.
* Currently, we assume this variable will be replaced more
* advanced logic to figure out if annotation processing is
* needed.
*/
boolean processAnnotations = false;
/**
* Object to handle annotation processing.
*/
/**
* Check if we should process annotations.
* If so, and if no scanner is yet registered, then set up the DocCommentScanner
* to catch doc comments, and set keepComments so the parser records them in
* the compilation unit.
*
* @param processors user provided annotation processors to bypass
* discovery, {@code null} means that no processors were provided
*/
// Process annotations if processing is not disabled and there
// is at least one Processor available.
processAnnotations = false;
} else if (procEnvImpl == null) {
if (processAnnotations) {
reader.saveParameterNames = true;
keepComments = true;
genEndPos = true;
if (taskListener != null)
log.deferDiagnostics = true;
} else { // free resources
procEnvImpl.close();
}
}
}
// TODO: called by JavacTaskImpl
}
/**
* Process any anotations found in the specifed compilation units.
* @param roots a list of compilation units
* @return an instance of the compiler in which to complete the compilation
*/
// Implementation note: when this method is called, log.deferredDiagnostics
// will have been set true by initProcessAnnotations, meaning that any diagnostics
// that are reported will go into the log.deferredDiagnostics queue.
// By the time this method exits, log.deferDiagnostics must be set back to false,
// and all deferredDiagnostics must have been handled: i.e. either reported
// or determined to be transient, and therefore suppressed.
// Errors were encountered.
// Unless all the errors are resolve errors, the errors were parse errors
// or other errors during enter which cannot be fixed by running
// any annotation processors.
if (unrecoverableError()) {
return this;
}
}
// ASSERT: processAnnotations and procEnvImpl should have been set up by
// by initProcessAnnotations
// NOTE: The !classnames.isEmpty() checks should be refactored to Main.
if (!processAnnotations) {
// If there are no annotation processors present, and
// annotation processing is to occur with compilation,
// emit a warning.
}
// If not processing annotations, classnames must be empty
if (!classnames.isEmpty()) {
}
return this; // continue regular compilation
}
try {
if (!classnames.isEmpty()) {
// Check for explicit request for annotation
// processing
if (!explicitAnnotationProcessingRequested()) {
return this; // TODO: Will this halt compilation?
} else {
boolean errors = false;
errors = true;
continue;
}
try {
else
continue;
}
} catch (CompletionFailure e) {
errors = true;
continue;
}
}
if (errors) {
return this;
}
}
}
try {
if (c != this)
// doProcessing will have handled deferred diagnostics
return c;
} finally {
procEnvImpl.close();
}
} catch (CompletionFailure ex) {
return this;
}
}
private boolean unrecoverableError() {
return true;
}
return false;
}
boolean explicitAnnotationProcessingRequested() {
return
}
return
}
/**
* Attribute a list of parse trees, such as found on the "todo" list.
* Note that attributing classes may cause additional files to be
* parsed and entered via the SourceCompleter.
* Attribution of the entries in the list does not stop if any errors occur.
* @returns a list of environments for attributd classes.
*/
}
/**
* Attribute a parse tree.
* @returns the attributed parse tree
*/
return env;
if (verboseCompilePolicy)
if (verbose)
if (taskListener != null) {
taskListener.started(e);
}
try {
//if in fail-over mode, ensure that AST expression nodes
}
}
finally {
}
return env;
}
/**
* Perform dataflow checks on attributed parse trees.
* These include checks for definite assignment and unreachable statements.
* If any errors occur, an empty list will be returned.
* @returns the list of attributed parse trees
*/
}
}
/**
* Perform dataflow checks on an attributed parse tree.
*/
}
/**
* Perform dataflow checks on an attributed parse tree.
*/
try {
return;
return;
}
if (verboseCompilePolicy)
try {
return;
}
finally {
}
}
finally {
if (taskListener != null) {
taskListener.finished(e);
}
}
}
/**
* Prepare attributed parse trees, in conjunction with their attribution contexts,
* for source or code generation.
* If any errors occur, an empty list will be returned.
* @returns a list containing the classes to be generated
*/
}
/**
* Prepare attributed parse trees, in conjunction with their attribution contexts,
* for source or code generation. If the file was not listed on the command line,
* the current implicitSourcePolicy is taken into account.
* The preparation stops as soon as an error is found.
*/
protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
return;
return;
}
return;
}
/**
* Ensure that superclasses of C are desugared before C itself. This is
* required for two reasons: (i) as erasure (TransTypes) destroys
* information needed in flow analysis and (ii) as some checks carried
* already been added to C and its superclasses.
*/
class ScanNested extends TreeScanner {
}
}
super.visitClassDef(node);
}
}
}
//We need to check for error another time as more classes might
//have been attributed and analyzed at this stage
return;
if (verboseCompilePolicy)
try {
//save tree prior to rewriting
return;
}
}
return;
}
if (stubOutput) {
//emit stub Java source file, only for compilation
//units enumerated explicitly on the command line
if (untranslated instanceof JCClassDecl &&
}
return;
}
return;
return;
if (sourceOutput) {
//emit standard Java source file, only for compilation
//units enumerated explicitly on the command line
if (untranslated instanceof JCClassDecl &&
}
return;
}
//translate out inner classes
return;
//generate code for each class
}
}
finally {
}
}
/** Generates the source or class file for a list of classes.
* The decision to generate a source file or a class file is
* based upon the compiler's options.
* Generation stops if an error occurs while writing files.
*/
}
public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
return;
if (verboseCompilePolicy) {
printNote("[generate "
}
if (taskListener != null) {
taskListener.started(e);
}
try {
if (usePrintSource)
else
} catch (IOException ex) {
return;
} finally {
}
if (taskListener != null) {
taskListener.finished(e);
}
}
}
// where
// use a LinkedHashMap to preserve the order of the original list as much as possible
Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
}
}
return map;
}
class MethodBodyRemover extends TreeTranslator {
super.visitMethodDef(tree);
}
super.visitVarDef(tree);
}
switch (t.getTag()) {
if (isInterface ||
(((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
break;
if (isInterface ||
(((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
break;
(((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
break;
default:
break;
}
}
super.visitClassDef(tree);
}
}
MethodBodyRemover r = new MethodBodyRemover();
}
public void reportDeferredDiagnostics() {
if (errorCount() == 0
else
}
}
/** Close the compiler, flushing the logs
*/
public void close() {
close(true);
}
rootClasses = null;
transTypes = null;
try {
fileManager.flush();
} catch (IOException e) {
throw new Abort(e);
} finally {
}
}
}
/** Print numbers of errors and warnings.
*/
if (count != 0) {
if (count == 1)
else
}
}
private static long now() {
return System.currentTimeMillis();
}
}
hasBeenUsed = true;
}
public static void enableLogging() {
}
}
}