com.google.javascript.jscomp
Class Compiler

java.lang.Object
  extended by com.google.javascript.jscomp.AbstractCompiler
      extended by com.google.javascript.jscomp.Compiler
All Implemented Interfaces:
SourceExcerptProvider

public class Compiler
extends AbstractCompiler

Compiler (and the other classes in this package) does the following:

External variables are declared in 'externs' files. For instance, the file may include definitions for global javascript/browser objects such as window, document.


Nested Class Summary
static class Compiler.CodeBuilder
          Stores a buffer of text to which more can be appended.
static class Compiler.IntermediateState
          Stores the internal compiler state just before optimization is performed.
 
Nested classes/interfaces inherited from interface com.google.javascript.jscomp.SourceExcerptProvider
SourceExcerptProvider.ExcerptFormatter, SourceExcerptProvider.SourceExcerpt
 
Field Summary
static DiagnosticType MOTION_ITERATIONS_ERROR
           
static DiagnosticType OPTIMIZE_LOOP_ERROR
          Error strings used for reporting JSErrors
protected  CodeChangeHandler.RecentChange recentChange
           
 PerformanceTracker tracker
           
 
Constructor Summary
Compiler()
          Creates a Compiler that reports errors and warnings to its logger.
Compiler(ErrorManager errorManager)
          Creates a Compiler that uses a custom error manager.
Compiler(PrintStream stream)
          Creates n Compiler that reports errors and warnings to an output stream.
 
Method Summary
 boolean acceptConstKeyword()
           
 boolean acceptEcmaScript5()
           
 void addNewScript(JsAst ast)
          Adds a new Script AST to the compile state.
 SymbolTable buildKnownSymbolTable()
           
 void check()
           
 Result compile(JSSourceFile[] externs, JSModule[] modules, CompilerOptions options)
          Compiles a list of modules.
 Result compile(JSSourceFile[] externs, JSSourceFile[] inputs, CompilerOptions options)
          Compiles a list of inputs.
 Result compile(JSSourceFile extern, JSModule[] modules, CompilerOptions options)
           
<T1 extends SourceFile,T2 extends SourceFile>
Result
compile(List<T1> externs, List<T2> inputs, CompilerOptions options)
          Compiles a list of inputs.
 Result compile(SourceFile extern, JSSourceFile[] input, CompilerOptions options)
           
 Result compile(SourceFile extern, SourceFile input, CompilerOptions options)
           
<T extends SourceFile>
Result
compileModules(List<T> externs, List<JSModule> modules, CompilerOptions options)
          Compiles a list of modules.
 void disableThreads()
          Disable threads.
 String getAstDotGraph()
          Gets the DOT graph of the AST generated at the end of compilation.
 CodingConvention getCodingConvention()
          Gets the current coding convention.
protected  DiagnosticGroups getDiagnosticGroups()
          The warning classes that are available from the command-line, and are suppressable by the @suppress annotation.
 int getErrorCount()
          Gets the number of errors.
 CheckLevel getErrorLevel(JSError error)
           
 ErrorManager getErrorManager()
          Gets the error manager.
 JSError[] getErrors()
          Returns the array of errors (never null).
 CompilerInput getInput(InputId id)
          Looks up an input (possibly an externs input) by name.
 Map<InputId,CompilerInput> getInputsById()
          Returns an unmodifiable view of the compiler inputs indexed by id.
 JSError[] getMessages()
          Returns an array constructed from errors + temporary warnings.
 double getProgress()
           
 Result getResult()
          Returns the result of the compilation.
 com.google.javascript.jscomp.ReverseAbstractInterpreter getReverseAbstractInterpreter()
          Get an interpreter for type analysis.
 Node getRoot()
          Returns the root node of the AST, which includes both externs and source.
 String getSourceLine(String sourceName, int lineNumber)
          Get the line indicated by the line number.
 SourceMap getSourceMap()
           
 Region getSourceRegion(String sourceName, int lineNumber)
          Get a region around the indicated line number.
 Compiler.IntermediateState getState()
          Returns the current internal state, excluding the input files and modules.
 Scope getTopScope()
          Gets the top scope.
 com.google.javascript.jscomp.MemoizedScopeCreator getTypedScopeCreator()
          Gets a memoized scope creator with type information.
 JSTypeRegistry getTypeRegistry()
          Gets a central registry of type information from the compiled JS.
 int getWarningCount()
          Gets the number of warnings.
 JSError[] getWarnings()
          Returns the array of warnings (never null).
 boolean hasErrors()
          Consults the ErrorManager to see if we've encountered errors that should halt compilation.
 void init(JSSourceFile[] externs, JSModule[] modules, CompilerOptions options)
          Initializes the instance state needed for a compile job if the sources are in modules.
 void init(JSSourceFile[] externs, JSSourceFile[] inputs, CompilerOptions options)
          Initializes the instance state needed for a compile job.
<T1 extends SourceFile,T2 extends SourceFile>
void
init(List<T1> externs, List<T2> inputs, CompilerOptions options)
          Initializes the instance state needed for a compile job.
<T extends SourceFile>
void
initModules(List<T> externs, List<JSModule> modules, CompilerOptions options)
          Initializes the instance state needed for a compile job if the sources are in modules.
 void initOptions(CompilerOptions options)
          Initialize the compiler options.
 boolean isIdeMode()
          Returns true if compiling in IDE mode.
 boolean isTypeCheckingEnabled()
          Returns true if type checking is enabled.
 CompilerOptions.LanguageMode languageMode()
           
protected  CompilerOptions newCompilerOptions()
          Allow subclasses to override the default CompileOptions object.
 CompilerInput newExternInput(String name)
          Creates a new externs file.
 void normalize()
           
 void optimize()
           
 void parse()
           
 Node parse(SourceFile file)
           
 void processDefines()
          Reprocesses the current defines over the AST.
 void rebuildInputsFromModules()
          Rebuilds the internal list of inputs by iterating over all modules.
protected  void removeExternInput(InputId id)
          Removes an input file from AST.
 void replaceScript(JsAst ast)
          Replaces one file in a hot-swap mode.
 void report(JSError error)
          Report an error or warning.
 void reportCodeChange()
          All passes should call reportCodeChange() when they alter the JS tree structure.
 void setErrorManager(ErrorManager errorManager)
          Sets the error manager.
static void setLoggingLevel(Level level)
          Sets the logging level for the com.google.javascript.jscomp package.
 void setPassConfig(PassConfig passes)
           
 void setState(Compiler.IntermediateState state)
          Sets the internal state to the capture given.
 String toSource()
          Converts the main parse tree back to js code.
 void toSource(Compiler.CodeBuilder cb, int inputSeqNum, Node root)
          Writes out js code from a root node.
 String toSource(JSModule module)
          Converts the parse tree for a module back to js code.
 String[] toSourceArray()
          Converts the parse tree for each input back to js code.
 String[] toSourceArray(JSModule module)
          Converts the parse tree for each input in a module back to js code.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

tracker

public PerformanceTracker tracker

OPTIMIZE_LOOP_ERROR

public static final DiagnosticType OPTIMIZE_LOOP_ERROR
Error strings used for reporting JSErrors


MOTION_ITERATIONS_ERROR

public static final DiagnosticType MOTION_ITERATIONS_ERROR

recentChange

protected final CodeChangeHandler.RecentChange recentChange
Constructor Detail

Compiler

public Compiler()
Creates a Compiler that reports errors and warnings to its logger.


Compiler

public Compiler(PrintStream stream)
Creates n Compiler that reports errors and warnings to an output stream.


Compiler

public Compiler(ErrorManager errorManager)
Creates a Compiler that uses a custom error manager.

Method Detail

setErrorManager

public void setErrorManager(ErrorManager errorManager)
Sets the error manager.

Parameters:
errorManager - the error manager, it cannot be null

initOptions

public void initOptions(CompilerOptions options)
Initialize the compiler options. Only necessary if you're not doing a normal compile() job.


init

public void init(JSSourceFile[] externs,
                 JSSourceFile[] inputs,
                 CompilerOptions options)
Initializes the instance state needed for a compile job.


init

public <T1 extends SourceFile,T2 extends SourceFile> void init(List<T1> externs,
                                                               List<T2> inputs,
                                                               CompilerOptions options)
Initializes the instance state needed for a compile job.


init

public void init(JSSourceFile[] externs,
                 JSModule[] modules,
                 CompilerOptions options)
Initializes the instance state needed for a compile job if the sources are in modules.


initModules

public <T extends SourceFile> void initModules(List<T> externs,
                                               List<JSModule> modules,
                                               CompilerOptions options)
Initializes the instance state needed for a compile job if the sources are in modules.


rebuildInputsFromModules

public void rebuildInputsFromModules()
Rebuilds the internal list of inputs by iterating over all modules. This is necessary if inputs have been added to or removed from a module after the init(JSSourceFile[], JSModule[], CompilerOptions) call.


compile

public Result compile(SourceFile extern,
                      SourceFile input,
                      CompilerOptions options)

compile

public Result compile(SourceFile extern,
                      JSSourceFile[] input,
                      CompilerOptions options)

compile

public Result compile(JSSourceFile extern,
                      JSModule[] modules,
                      CompilerOptions options)

compile

public Result compile(JSSourceFile[] externs,
                      JSSourceFile[] inputs,
                      CompilerOptions options)
Compiles a list of inputs.


compile

public <T1 extends SourceFile,T2 extends SourceFile> Result compile(List<T1> externs,
                                                                    List<T2> inputs,
                                                                    CompilerOptions options)
Compiles a list of inputs.


compile

public Result compile(JSSourceFile[] externs,
                      JSModule[] modules,
                      CompilerOptions options)
Compiles a list of modules.


compileModules

public <T extends SourceFile> Result compileModules(List<T> externs,
                                                    List<JSModule> modules,
                                                    CompilerOptions options)
Compiles a list of modules.


disableThreads

public void disableThreads()
Disable threads. This is for clients that run on AppEngine and don't have threads.


parse

public void parse()

setPassConfig

public void setPassConfig(PassConfig passes)
Parameters:
passes - The PassConfig to use with this Compiler.
Throws:
NullPointerException - if passes is null
IllegalStateException - if this.passes has already been assigned

check

public void check()

getResult

public Result getResult()
Returns the result of the compilation.


getMessages

public JSError[] getMessages()
Returns an array constructed from errors + temporary warnings.


getErrors

public JSError[] getErrors()
Returns the array of errors (never null).


getWarnings

public JSError[] getWarnings()
Returns the array of warnings (never null).


getRoot

public Node getRoot()
Description copied from class: AbstractCompiler
Returns the root node of the AST, which includes both externs and source.


getInput

public CompilerInput getInput(InputId id)
Description copied from class: AbstractCompiler
Looks up an input (possibly an externs input) by name. May return null.

Specified by:
getInput in class AbstractCompiler

removeExternInput

protected void removeExternInput(InputId id)
Removes an input file from AST.

Parameters:
id - The id of the input to be removed.

newExternInput

public CompilerInput newExternInput(String name)
Description copied from class: AbstractCompiler
Creates a new externs file.

Parameters:
name - A name for the new externs file.

getTypeRegistry

public JSTypeRegistry getTypeRegistry()
Description copied from class: AbstractCompiler
Gets a central registry of type information from the compiled JS.

Specified by:
getTypeRegistry in class AbstractCompiler

getTypedScopeCreator

public com.google.javascript.jscomp.MemoizedScopeCreator getTypedScopeCreator()
Description copied from class: AbstractCompiler
Gets a memoized scope creator with type information.


buildKnownSymbolTable

public SymbolTable buildKnownSymbolTable()

getTopScope

public Scope getTopScope()
Description copied from class: AbstractCompiler
Gets the top scope.

Specified by:
getTopScope in class AbstractCompiler

getReverseAbstractInterpreter

public com.google.javascript.jscomp.ReverseAbstractInterpreter getReverseAbstractInterpreter()
Description copied from class: AbstractCompiler
Get an interpreter for type analysis.

Specified by:
getReverseAbstractInterpreter in class AbstractCompiler

parse

public Node parse(SourceFile file)

newCompilerOptions

protected CompilerOptions newCompilerOptions()
Allow subclasses to override the default CompileOptions object.


toSource

public String toSource()
Converts the main parse tree back to js code.


toSourceArray

public String[] toSourceArray()
Converts the parse tree for each input back to js code.


toSource

public String toSource(JSModule module)
Converts the parse tree for a module back to js code.


toSourceArray

public String[] toSourceArray(JSModule module)
Converts the parse tree for each input in a module back to js code.


toSource

public void toSource(Compiler.CodeBuilder cb,
                     int inputSeqNum,
                     Node root)
Writes out js code from a root node. If printing input delimiters, this method will attach a comment to the start of the text indicating which input the output derived from. If there were any preserve annotations within the root's source, they will also be printed in a block comment at the beginning of the output.


optimize

public void optimize()

processDefines

public void processDefines()
Reprocesses the current defines over the AST. This is used by GwtCompiler to generate N outputs for different targets from the same (checked) AST. For each target, we apply the target-specific defines by calling processDefines and then optimize to optimize the AST specifically for that target.


normalize

public void normalize()

reportCodeChange

public void reportCodeChange()
All passes should call reportCodeChange() when they alter the JS tree structure. This is verified by CompilerTestCase. This allows us to optimize to a fixed point.

Specified by:
reportCodeChange in class AbstractCompiler

getCodingConvention

public CodingConvention getCodingConvention()
Description copied from class: AbstractCompiler
Gets the current coding convention.

Specified by:
getCodingConvention in class AbstractCompiler

isIdeMode

public boolean isIdeMode()
Description copied from class: AbstractCompiler
Returns true if compiling in IDE mode.


acceptEcmaScript5

public boolean acceptEcmaScript5()
Returns:
Whether the compiler is in ES5Mode.

languageMode

public CompilerOptions.LanguageMode languageMode()

acceptConstKeyword

public boolean acceptConstKeyword()
Returns:
Whether the compiler accepts `const' keyword.

isTypeCheckingEnabled

public boolean isTypeCheckingEnabled()
Description copied from class: AbstractCompiler
Returns true if type checking is enabled.


getDiagnosticGroups

protected DiagnosticGroups getDiagnosticGroups()
The warning classes that are available from the command-line, and are suppressable by the @suppress annotation.


report

public void report(JSError error)
Description copied from class: AbstractCompiler
Report an error or warning.

Specified by:
report in class AbstractCompiler

getErrorLevel

public CheckLevel getErrorLevel(JSError error)
Returns:
The error level the given error object will be reported at.

getErrorCount

public int getErrorCount()
Gets the number of errors.


getWarningCount

public int getWarningCount()
Gets the number of warnings.


hasErrors

public boolean hasErrors()
Consults the ErrorManager to see if we've encountered errors that should halt compilation.

If CompilerOptions.ideMode is true, this function always returns false without consulting the error manager. The error manager will continue to be told about new errors and warnings, but the compiler will complete compilation of all inputs.


getSourceLine

public String getSourceLine(String sourceName,
                            int lineNumber)
Description copied from interface: SourceExcerptProvider
Get the line indicated by the line number. This call will return only the specific line.

lineNumber - the line number, 1 being the first line of the file
Returns:
the line indicated, or null if it does not exist

getSourceRegion

public Region getSourceRegion(String sourceName,
                              int lineNumber)
Description copied from interface: SourceExcerptProvider
Get a region around the indicated line number. The exact definition of a region is implementation specific, but it must contain the line indicated by the line number. A region must not start or end by a carriage return.

lineNumber - the line number, 1 being the first line of the file
Returns:
the region around the line number indicated, or null if it does not exist

getSourceMap

public SourceMap getSourceMap()

setLoggingLevel

public static void setLoggingLevel(Level level)
Sets the logging level for the com.google.javascript.jscomp package.


getAstDotGraph

public String getAstDotGraph()
                      throws IOException
Gets the DOT graph of the AST generated at the end of compilation.

Throws:
IOException

getErrorManager

public ErrorManager getErrorManager()
Description copied from class: AbstractCompiler
Gets the error manager.

Specified by:
getErrorManager in class AbstractCompiler

getInputsById

public Map<InputId,CompilerInput> getInputsById()
Returns an unmodifiable view of the compiler inputs indexed by id.


getState

public Compiler.IntermediateState getState()
Returns the current internal state, excluding the input files and modules.


setState

public void setState(Compiler.IntermediateState state)
Sets the internal state to the capture given. Note that this assumes that the input files are already set up.


getProgress

public double getProgress()
Specified by:
getProgress in class AbstractCompiler
Returns:
a number in [0,1] range indicating an approximate progress of the last compile. Note this should only be used as a hint and no assumptions should be made on accuracy, even a completed compile may choose not to set this to 1.0 at the end.

replaceScript

public void replaceScript(JsAst ast)
Replaces one file in a hot-swap mode. The given JsAst should be made from a new version of a file that already was present in the last compile call. If the file is new, this will silently ignored.

Parameters:
ast - the ast of the file that is being replaced

addNewScript

public void addNewScript(JsAst ast)
Adds a new Script AST to the compile state. If a script for the same file already exists the script will not be added, instead a call to #replaceScript should be used.

Parameters:
ast - the ast of the new file