com.sun.tools.javac.main
Class JavaCompiler

java.lang.Object
  extended by com.sun.tools.javac.main.JavaCompiler
All Implemented Interfaces:
ClassReader.SourceCompleter
Direct Known Subclasses:
ASTCodeCompiler, JavaCompiler, JavadocTool, StringCodeCompiler

public class JavaCompiler
extends java.lang.Object
implements ClassReader.SourceCompleter

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.

This is NOT part of any API supported by Sun Microsystems. 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.


Nested Class Summary
protected static class JavaCompiler.CompilePolicy
          Control how the compiler's latter phases (attr, flow, desugar, generate) are connected.
protected static class JavaCompiler.CompileState
           
protected  class JavaCompiler.CompileStates
           
protected static class JavaCompiler.ImplicitSourcePolicy
           
 
Field Summary
protected  Annotate annotate
          The annotation annotator.
protected  boolean annotationProcessingOccurred
          Flag set if any annotation processing occurred.
protected  Attr attr
          The attributor.
 boolean attrParseOnly
          Generate attributed parse tree only.
protected  Check chk
          The attributor.
protected  JavaCompiler.CompilePolicy compilePolicy
          The policy for the order in which to perform the compilation
protected static Context.Key<JavaCompiler> compilerKey
          The context key for the compiler.
private  JavaCompiler.CompileStates compileStates
           
protected  Name completionFailureName
          Force a completion failure on this name
protected  Context context
           
private static JavaCompiler.CompilePolicy DEFAULT_COMPILE_POLICY
           
protected  JavaCompiler delegateCompiler
          Annotation processing may require and provide a new instance of the compiler to be used for the analyze and generate phases.
protected  boolean devVerbose
          Switch: should we debug ignored exceptions
(package private)  JCDiagnostic.Factory diagFactory
          Factory for creating diagnostic objects
 long elapsed_msec
           
 java.lang.String encoding
          The encoding to be used for source input.
protected  Enter enter
          The module for the symbol table entry phases.
protected  boolean explicitAnnotationProcessingRequested
          Switch: is annotation processing requested explitly via CompilationTask.setProcessors?
protected  JavaFileManager fileManager
          Access to file objects.
protected  Flow flow
          The flow analyzer.
protected  Gen gen
          The module for code generation.
 boolean genEndPos
          Switch: should we store the ending positions?
private  boolean hasBeenUsed
          Track when the JavaCompiler has been used to compile something.
protected  boolean implicitSourceFilesRead
          Flag set if any implicit source files read.
protected  JavaCompiler.ImplicitSourcePolicy implicitSourcePolicy
          The policy for what to do with implicitly read source files
protected  java.util.Set<JavaFileObject> inputFiles
          The set of currently compiled inputfiles, needed to ensure we don't accidentally overwrite an input file when -s is set.
 boolean keepComments
           
 boolean lineDebugInfo
          Generate code with the LineNumberTable attribute for debugging
 Log log
          The log to be used for error reporting.
protected  Lower lower
          The syntactic sugar desweetener.
protected  TreeMaker make
          The tree factory module.
protected  Names names
          The name table.
private  boolean parseErrors
          Track whether any errors occurred while parsing source text.
protected  ParserFactory parserFactory
          Factory for parsers.
 boolean printFlat
          Debug switch: Emit Java sources after inner class flattening.
(package private)  JavacProcessingEnvironment procEnvImpl
          Object to handle annotation processing.
(package private)  boolean processAnnotations
          Set to true to enable skeleton annotation processing code.
protected  boolean processPcks
          Switch: should we (annotation) process packages as well
protected  ClassReader reader
          The class reader.
(package private)  boolean relax
          Switch: relax some constraints for producing the jsr14 prototype.
private  List<JCTree.JCClassDecl> rootClasses
           
protected  Source source
          The language version.
 boolean sourceOutput
          Emit plain Java source files rather than class files.
private  long start_msec
           
 boolean stubOutput
          Emit stub source files rather than class files.
protected  Symtab syms
          The symbol table.
protected  TaskListener taskListener
          Optional listener for progress events
 Todo todo
          A queue of all as yet unattributed classes.
protected  TransStaging transStaging
          The staging eraser.
protected  TransTypes transTypes
          The type eraser.
protected  Types types
          Type utilities.
 boolean verbose
          Verbose output.
 boolean verboseCompilePolicy
          Report activity related to compilePolicy
private static java.util.ResourceBundle versionRB
           
private static java.lang.String versionRBName
           
protected  ClassWriter writer
          The class writer.
 
Constructor Summary
JavaCompiler(Context context)
          Construct a new compiler using a shared context.
 
Method Summary
 Env<AttrContext> attribute(Env<AttrContext> env)
          Attribute a parse tree.
 java.util.Queue<Env<AttrContext>> attribute(java.util.Queue<Env<AttrContext>> envs)
          Attribute a list of parse trees, such as found on the "todo" list.
 void close()
          Close the compiler, flushing the logs
 void close(boolean disposeNames)
           
 void compile(List<JavaFileObject> sourceFileObject)
           
 void compile(List<JavaFileObject> sourceFileObjects, List<java.lang.String> classnames, java.lang.Iterable<? extends Processor> processors)
          Main method: compile a list of files, return all compiled classes
private  void compile2()
          The phases following annotation processing: attribution, desugar, and finally code generation.
 void complete(Symbol.ClassSymbol c)
          Complete compiling a source file that has been accessed by the class file reader.
protected  void desugar(Env<AttrContext> env, java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> results)
          Prepare attributed parse trees, in conjunction with their attribution contexts, for source or code generation.
 java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> desugar(java.util.Queue<Env<AttrContext>> envs)
          Prepare attributed parse trees, in conjunction with their attribution contexts, for source or code generation.
private static long elapsed(long then)
           
static void enableLogging()
           
 List<JCTree.JCCompilationUnit> enterTrees(List<JCTree.JCCompilationUnit> roots)
          Enter the symbols found in a list of parse trees.
 int errorCount()
          The number of errors reported so far.
(package private)  boolean explicitAnnotationProcessingRequested()
           
 java.util.Queue<Env<AttrContext>> flow(Env<AttrContext> env)
          Perform dataflow checks on an attributed parse tree.
protected  void flow(Env<AttrContext> env, java.util.Queue<Env<AttrContext>> results)
          Perform dataflow checks on an attributed parse tree.
 java.util.Queue<Env<AttrContext>> flow(java.util.Queue<Env<AttrContext>> envs)
          Perform dataflow checks on attributed parse trees.
static java.lang.String fullVersion()
          The current full version number as a string.
(package private)  JavaFileObject genCode(Env<AttrContext> env, JCTree.JCClassDecl cdef)
          Generate code and emit a class file for a given class
 void generate(java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> queue)
          Generates the source or class file for a list of classes.
 void generate(java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> queue, java.util.Queue<JavaFileObject> results)
           
(package private)  java.util.Map<JCTree.JCCompilationUnit,java.util.Queue<Env<AttrContext>>> groupByFile(java.util.Queue<Env<AttrContext>> envs)
           
 void initProcessAnnotations(java.lang.Iterable<? extends Processor> processors)
          Check if we should process annotations.
 void initRound(JavaCompiler prev)
           
static JavaCompiler instance(Context context)
          Get the JavaCompiler instance for this context.
protected  boolean keepComments()
           
private static long now()
           
 JCTree.JCCompilationUnit parse(JavaFileObject filename)
          Parse contents of file.
protected  JCTree.JCCompilationUnit parse(JavaFileObject filename, java.lang.CharSequence content)
          Parse contents of input stream.
 JCTree.JCCompilationUnit parse(java.lang.String filename)
          Deprecated. 
 boolean parseErrors()
          Whether or not any parse errors have occurred.
 List<JCTree.JCCompilationUnit> parseFiles(List<JavaFileObject> fileObjects)
          Parses a list of files.
protected  void printCount(java.lang.String kind, int count)
          Print numbers of errors and warnings.
(package private)  JavaFileObject printSource(Env<AttrContext> env, JCTree.JCClassDecl cdef)
          Emit plain Java source for a class.
protected  void printVerbose(java.lang.String key, java.lang.Object arg)
          Output for "-verbose" option.
 JavaCompiler processAnnotations(List<JCTree.JCCompilationUnit> roots)
           
 JavaCompiler processAnnotations(List<JCTree.JCCompilationUnit> roots, List<java.lang.String> classnames)
          Process any anotations found in the specifed compilation units.
 java.lang.CharSequence readSource(JavaFileObject filename)
          Try to open input stream with given name.
(package private)  JCTree.JCClassDecl removeMethodBodies(JCTree.JCClassDecl cdef)
           
 void reportDeferredDiagnostics()
           
 Symbol resolveIdent(java.lang.String name)
          Resolve an identifier.
protected
<T> List<T>
stopIfError(List<T> list)
           
protected
<T> java.util.Queue<T>
stopIfError(java.util.Queue<T> queue)
           
static java.lang.String version()
          The current version number as a string.
private static java.lang.String version(java.lang.String key)
           
 int warningCount()
          The number of warnings reported so far.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

compilerKey

protected static final Context.Key<JavaCompiler> compilerKey
The context key for the compiler.


versionRBName

private static final java.lang.String versionRBName
See Also:
Constant Field Values

versionRB

private static java.util.ResourceBundle versionRB

DEFAULT_COMPILE_POLICY

private static JavaCompiler.CompilePolicy DEFAULT_COMPILE_POLICY

log

public Log log
The log to be used for error reporting.


diagFactory

JCDiagnostic.Factory diagFactory
Factory for creating diagnostic objects


make

protected TreeMaker make
The tree factory module.


reader

protected ClassReader reader
The class reader.


writer

protected ClassWriter writer
The class writer.


enter

protected Enter enter
The module for the symbol table entry phases.


syms

protected Symtab syms
The symbol table.


source

protected Source source
The language version.


gen

protected Gen gen
The module for code generation.


names

protected Names names
The name table.


attr

protected Attr attr
The attributor.


chk

protected Check chk
The attributor.


flow

protected Flow flow
The flow analyzer.


transTypes

protected TransTypes transTypes
The type eraser.


transStaging

protected TransStaging transStaging
The staging eraser.


lower

protected Lower lower
The syntactic sugar desweetener.


annotate

protected Annotate annotate
The annotation annotator.


completionFailureName

protected final Name completionFailureName
Force a completion failure on this name


types

protected Types types
Type utilities.


fileManager

protected JavaFileManager fileManager
Access to file objects.


parserFactory

protected ParserFactory parserFactory
Factory for parsers.


taskListener

protected TaskListener taskListener
Optional listener for progress events


delegateCompiler

protected JavaCompiler delegateCompiler
Annotation processing may require and provide a new instance of the compiler to be used for the analyze and generate phases.


annotationProcessingOccurred

protected boolean annotationProcessingOccurred
Flag set if any annotation processing occurred.


implicitSourceFilesRead

protected boolean implicitSourceFilesRead
Flag set if any implicit source files read.


context

protected Context context

verbose

public boolean verbose
Verbose output.


sourceOutput

public boolean sourceOutput
Emit plain Java source files rather than class files.


stubOutput

public boolean stubOutput
Emit stub source files rather than class files.


attrParseOnly

public boolean attrParseOnly
Generate attributed parse tree only.


relax

boolean relax
Switch: relax some constraints for producing the jsr14 prototype.


printFlat

public boolean printFlat
Debug switch: Emit Java sources after inner class flattening.


encoding

public java.lang.String encoding
The encoding to be used for source input.


lineDebugInfo

public boolean lineDebugInfo
Generate code with the LineNumberTable attribute for debugging


genEndPos

public boolean genEndPos
Switch: should we store the ending positions?


devVerbose

protected boolean devVerbose
Switch: should we debug ignored exceptions


processPcks

protected boolean processPcks
Switch: should we (annotation) process packages as well


explicitAnnotationProcessingRequested

protected boolean explicitAnnotationProcessingRequested
Switch: is annotation processing requested explitly via CompilationTask.setProcessors?


compilePolicy

protected JavaCompiler.CompilePolicy compilePolicy
The policy for the order in which to perform the compilation


implicitSourcePolicy

protected JavaCompiler.ImplicitSourcePolicy implicitSourcePolicy
The policy for what to do with implicitly read source files


verboseCompilePolicy

public boolean verboseCompilePolicy
Report activity related to compilePolicy


todo

public Todo todo
A queue of all as yet unattributed classes.


compileStates

private JavaCompiler.CompileStates compileStates

inputFiles

protected java.util.Set<JavaFileObject> inputFiles
The set of currently compiled inputfiles, needed to ensure we don't accidentally overwrite an input file when -s is set. initialized by `compile'.


keepComments

public boolean keepComments

hasBeenUsed

private boolean hasBeenUsed
Track when the JavaCompiler has been used to compile something.


start_msec

private long start_msec

elapsed_msec

public long elapsed_msec

parseErrors

private boolean parseErrors
Track whether any errors occurred while parsing source text.


rootClasses

private List<JCTree.JCClassDecl> rootClasses

processAnnotations

boolean processAnnotations
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.


procEnvImpl

JavacProcessingEnvironment procEnvImpl
Object to handle annotation processing.

Constructor Detail

JavaCompiler

public JavaCompiler(Context context)
Construct a new compiler using a shared context.

Method Detail

instance

public static JavaCompiler instance(Context context)
Get the JavaCompiler instance for this context.


version

public static java.lang.String version()
The current version number as a string.


fullVersion

public static java.lang.String fullVersion()
The current full version number as a string.


version

private static java.lang.String version(java.lang.String key)

errorCount

public int errorCount()
The number of errors reported so far.


stopIfError

protected final <T> java.util.Queue<T> stopIfError(java.util.Queue<T> queue)

stopIfError

protected final <T> List<T> stopIfError(List<T> list)

warningCount

public int warningCount()
The number of warnings reported so far.


parseErrors

public boolean parseErrors()
Whether or not any parse errors have occurred.


readSource

public java.lang.CharSequence readSource(JavaFileObject filename)
Try to open input stream with given name. Report an error if this fails.

Parameters:
filename - The file name of the input stream to be opened.

parse

protected JCTree.JCCompilationUnit parse(JavaFileObject filename,
                                         java.lang.CharSequence content)
Parse contents of input stream.

Parameters:
filename - The name of the file from which input stream comes.
input - The input stream to be parsed.

keepComments

protected boolean keepComments()

parse

@Deprecated
public JCTree.JCCompilationUnit parse(java.lang.String filename)
                               throws java.io.IOException
Deprecated. 

Parse contents of file.

Parameters:
filename - The name of the file to be parsed.
Throws:
java.io.IOException

parse

public JCTree.JCCompilationUnit parse(JavaFileObject filename)
Parse contents of file.

Parameters:
filename - The name of the file to be parsed.

resolveIdent

public Symbol resolveIdent(java.lang.String name)
Resolve an identifier.

Parameters:
name - The identifier to resolve

printSource

JavaFileObject printSource(Env<AttrContext> env,
                           JCTree.JCClassDecl cdef)
                     throws java.io.IOException
Emit plain Java source for a class.

Parameters:
env - The attribution environment of the outermost class containing this class.
cdef - The class definition to be printed.
Throws:
java.io.IOException

genCode

JavaFileObject genCode(Env<AttrContext> env,
                       JCTree.JCClassDecl cdef)
                 throws java.io.IOException
Generate code and emit a class file for a given class

Parameters:
env - The attribution environment of the outermost class containing this class.
cdef - The class definition from which code is generated.
Throws:
java.io.IOException

complete

public void complete(Symbol.ClassSymbol c)
              throws Symbol.CompletionFailure
Complete compiling a source file that has been accessed by the class file reader.

Specified by:
complete in interface ClassReader.SourceCompleter
Parameters:
c - The class the source file of which needs to be compiled.
filename - The name of the source file.
f - An input stream that reads the source file.
Throws:
Symbol.CompletionFailure

compile

public void compile(List<JavaFileObject> sourceFileObject)
             throws java.lang.Throwable
Throws:
java.lang.Throwable

compile

public void compile(List<JavaFileObject> sourceFileObjects,
                    List<java.lang.String> classnames,
                    java.lang.Iterable<? extends Processor> processors)
             throws java.io.IOException
Main method: compile a list of files, return all compiled classes

Parameters:
sourceFileObjects - file objects to be compiled
classnames - class names to process for annotations
processors - user provided annotation processors to bypass discovery, null means that no processors were provided
Throws:
java.io.IOException

compile2

private void compile2()
The phases following annotation processing: attribution, desugar, and finally code generation.


parseFiles

public List<JCTree.JCCompilationUnit> parseFiles(List<JavaFileObject> fileObjects)
                                          throws java.io.IOException
Parses a list of files.

Throws:
java.io.IOException

enterTrees

public List<JCTree.JCCompilationUnit> enterTrees(List<JCTree.JCCompilationUnit> roots)
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.


initProcessAnnotations

public void initProcessAnnotations(java.lang.Iterable<? extends Processor> processors)
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.

Parameters:
processors - user provided annotation processors to bypass discovery, null means that no processors were provided

processAnnotations

public JavaCompiler processAnnotations(List<JCTree.JCCompilationUnit> roots)
                                throws java.io.IOException
Throws:
java.io.IOException

processAnnotations

public JavaCompiler processAnnotations(List<JCTree.JCCompilationUnit> roots,
                                       List<java.lang.String> classnames)
                                throws java.io.IOException
Process any anotations found in the specifed compilation units.

Parameters:
roots - a list of compilation units
Returns:
an instance of the compiler in which to complete the compilation
Throws:
java.io.IOException

explicitAnnotationProcessingRequested

boolean explicitAnnotationProcessingRequested()

attribute

public java.util.Queue<Env<AttrContext>> attribute(java.util.Queue<Env<AttrContext>> envs)
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.


attribute

public Env<AttrContext> attribute(Env<AttrContext> env)
Attribute a parse tree.


flow

public java.util.Queue<Env<AttrContext>> flow(java.util.Queue<Env<AttrContext>> envs)
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.


flow

public java.util.Queue<Env<AttrContext>> flow(Env<AttrContext> env)
Perform dataflow checks on an attributed parse tree.


flow

protected void flow(Env<AttrContext> env,
                    java.util.Queue<Env<AttrContext>> results)
Perform dataflow checks on an attributed parse tree.


desugar

public java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> desugar(java.util.Queue<Env<AttrContext>> envs)
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.


desugar

protected void desugar(Env<AttrContext> env,
                       java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> results)
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.


generate

public void generate(java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> queue)
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.


generate

public void generate(java.util.Queue<Pair<Env<AttrContext>,JCTree.JCClassDecl>> queue,
                     java.util.Queue<JavaFileObject> results)

groupByFile

java.util.Map<JCTree.JCCompilationUnit,java.util.Queue<Env<AttrContext>>> groupByFile(java.util.Queue<Env<AttrContext>> envs)

removeMethodBodies

JCTree.JCClassDecl removeMethodBodies(JCTree.JCClassDecl cdef)

reportDeferredDiagnostics

public void reportDeferredDiagnostics()

close

public void close()
Close the compiler, flushing the logs


close

public void close(boolean disposeNames)

printVerbose

protected void printVerbose(java.lang.String key,
                            java.lang.Object arg)
Output for "-verbose" option.

Parameters:
key - The key to look up the correct internationalized string.
arg - An argument for substitution into the output string.

printCount

protected void printCount(java.lang.String kind,
                          int count)
Print numbers of errors and warnings.


now

private static long now()

elapsed

private static long elapsed(long then)

initRound

public void initRound(JavaCompiler prev)

enableLogging

public static void enableLogging()