Class Compiler
- java.lang.Object
-
- com.google.javascript.jscomp.AbstractCompiler
-
- com.google.javascript.jscomp.Compiler
-
- All Implemented Interfaces:
CompilerInputProvider
,ErrorHandler
,SourceExcerptProvider
,SourceFileMapping
public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFileMapping
Compiler (and the other classes in this package) does the following:- parses JS code
- checks for undefined variables
- performs optimizations such as constant folding and constants inlining
- renames variables (to short names)
- outputs compact JavaScript code
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Compiler.ChunkGraphAwareLicenseTracker
An implementation of a license tracker to be used when licenses can be de-duped among Chunks (because licenses might be loaded by a chunk's transitive dependencies.static class
Compiler.CodeBuilder
Stores a buffer of text to which more can be appended.protected static class
Compiler.CompilerState
Serializable state of the compiler specific to multistage binary buildsstatic class
Compiler.ExternalSourceLoader
Subclasses are responsible for loading sources that were not provided as explicit inputs to the compiler.static class
Compiler.ScriptNodeLicensesOnlyTracker
A license tracker implementation that emits all licenses attached to script nodes, regardless of if the content of that script is used anywhere in the compilation.static class
Compiler.SingleBinaryLicenseTracker
A license tracker implementation that only retains licenses for which there are useful nodes in a binary.-
Nested classes/interfaces inherited from class com.google.javascript.jscomp.AbstractCompiler
AbstractCompiler.LifeCycleStage
-
Nested classes/interfaces inherited from interface com.google.javascript.jscomp.SourceExcerptProvider
SourceExcerptProvider.ExcerptFormatter, SourceExcerptProvider.SourceExcerpt
-
-
Field Summary
Fields Modifier and Type Field Description static java.util.logging.Logger
logger
Logger for the whole com.google.javascript.jscomp domain - setting configuration for this logger affects all loggers in other classes within the compiler.protected com.google.javascript.jscomp.RecentChange
recentChange
PerformanceTracker
tracker
-
Constructor Summary
Constructors Constructor Description Compiler()
Creates a Compiler that reports errors and warnings to its logger.Compiler(@Nullable java.io.PrintStream outStream)
Creates a Compiler that reports errors and warnings to an output stream.Compiler(ErrorManager errorManager)
Creates a Compiler that uses a custom error manager.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
addExportedNames(java.util.Set<java.lang.String> exportedNames)
Adds exported names to keep track.void
addInputSourceMap(java.lang.String sourceFileName, SourceMapInput inputSourceMap)
Adds aSourceMapInput
for the givensourceFileName
, to be used for error reporting and source map combining.SymbolTable
buildKnownSymbolTable()
void
clearJSTypeRegistry()
Result
compile(SourceFile extern, SourceFile input, CompilerOptions options)
Compiles a single source file and a single externs file.Result
compile(java.util.List<SourceFile> externs, java.util.List<SourceFile> inputs, CompilerOptions options)
Compiles a list of inputs.Result
compileModules(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options)
Compiles a list of modules.protected com.google.javascript.jscomp.CompilerExecutor
createCompilerExecutor()
protected Config
createConfig(Config.LanguageMode mode, Config.StrictMode strictMode)
protected PassConfig
createPassConfigInternal()
Create the passes object.void
disableThreads()
Disable threads.protected Node
ensureLibraryInjected(java.lang.String resourceName, boolean force)
void
forwardDeclareType(java.lang.String typeName)
void
generateReport()
Generates a report of all warnings and errors found during compilation to stderr.java.lang.String
getAstDotGraph()
Gets the DOT graph of the AST generated at the end of compilation.int
getChangeStamp()
CodingConvention
getCodingConvention()
Gets the current coding convention.ColorRegistry
getColorRegistry()
Gets a central registry of colors from deserialized JS types.java.util.List<Comment>
getComments(java.lang.String filename)
protected com.google.javascript.jscomp.CompilerExecutor
getCompilerExecutor()
protected Compiler.CompilerState
getCompilerState()
IdGenerator
getCrossModuleIdGenerator()
Gets the id generator for cross-module motion.DiagnosticGroups
getDiagnosticGroups()
The warning classes that are available from the command-line, and are suppressible by the@suppress
annotation.int
getErrorCount()
Gets the number of errors.CheckLevel
getErrorLevel(JSError error)
ErrorManager
getErrorManager()
Gets the error manager.com.google.common.collect.ImmutableList<JSError>
getErrors()
Returns the list of errors (never null).java.util.Set<java.lang.String>
getExportedNames()
Gets the names that have been exported.com.google.common.collect.ImmutableSet<java.lang.String>
getExternProperties()
Gets the names of the properties defined in externs or null if GatherExternProperties pass was not run yet.protected Node
getExternsRoot()
@Nullable CompilerInput
getInput(InputId id)
Looks up an input (possibly an externs input) by input id.java.util.Map<InputId,CompilerInput>
getInputsById()
Returns an unmodifiable view of the compiler inputs indexed by id.VariableMap
getInstrumentationMapping()
protected Node
getJsRoot()
static @Nullable java.lang.String
getLicenseForFile(AbstractCompiler compiler, @Nullable java.lang.String fileName)
ModuleLoader
getModuleLoader()
ModuleMap
getModuleMap()
ModuleMetadataMap
getModuleMetadataMap()
@Nullable java.lang.Iterable<JSChunk>
getModules()
Gets the JS source modules in dependency order.protected Node
getNodeForCodeInsertion(@Nullable JSChunk module)
CompilerOptions
getOptions()
Result
getResult()
Returns the result of the compilation.ReverseAbstractInterpreter
getReverseAbstractInterpreter()
Get an interpreter for type analysis.Node
getRoot()
Returns the root node of the AST, which includes both externs and source.@Nullable Node
getScriptNode(java.lang.String filename)
@Nullable java.lang.CharSequence
getSourceFileContentByName(java.lang.String sourceName)
@Nullable java.lang.String
getSourceLine(java.lang.String sourceName, int lineNumber)
Get the line indicated by the line number.@Nullable Region
getSourceLines(java.lang.String sourceName, int lineNumber, int length)
Gets the specific lines returned by the beginning and excerpt length.SourceMap
getSourceMap()
@Nullable com.google.debugging.sourcemap.proto.Mapping.OriginalMapping
getSourceMapping(java.lang.String sourceName, int lineNumber, int columnNumber)
Returns the original mapping for the file name, line number and column position found in the source map.@Nullable Region
getSourceRegion(java.lang.String sourceName, int lineNumber)
Get a region around the indicated line number.TypedScope
getTopScope()
Gets the top scope.com.google.javascript.jscomp.ScopeCreator
getTypedScopeCreator()
java.lang.Iterable<TypeMismatch>
getTypeMismatches()
Gets the central registry of type violations.JSTypeRegistry
getTypeRegistry()
Gets a central registry of type information from the compiled JS.int
getWarningCount()
Gets the number of warnings.com.google.common.collect.ImmutableList<JSError>
getWarnings()
Returns the list of warnings (never null).boolean
hasErrors()
Consults theErrorManager
to see if we've encountered errors that should halt compilation.boolean
hasOptimizationColors()
Whether the AST has been annotated with optimization colors.boolean
hasTypeCheckingRun()
Returns whether the typechecking passes have runvoid
incrementChangeStamp()
void
init(java.util.List<SourceFile> externs, java.util.List<SourceFile> sources, CompilerOptions options)
Initializes the instance state needed for a compile job.void
initBasedOnOptions()
Do any initialization that is dependent on the compiler options.void
initModules(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options)
Initializes the instance state needed for a compile job if the sources are in modules.void
initModulesWithTypedAstFilesystem(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options, java.io.InputStream typedAstListStream)
Initializes a compiler that will use pre-compiled TypedAst files instead of reading the source from diskvoid
initOptions(CompilerOptions options)
Initializes the compiler options.void
initRuntimeLibraryTypedAsts(com.google.common.base.Optional<ColorPool.Builder> colorPoolBuilder)
Deserialize runtime libraries from a TypedAST packaged as a JAR resource and reconcile their Colors with the current inputs.void
initWebpackMap(com.google.common.collect.ImmutableMap<java.lang.String,java.lang.String> inputPathByWebpackId)
void
initWithTypedAstFilesystem(java.util.List<SourceFile> externs, java.util.List<SourceFile> sources, CompilerOptions options, java.io.InputStream typedAstListStream)
Initializes a compiler that will use pre-compiled TypedAst files instead of reading the source from diskvoid
instrumentForCoverage()
Instrument code for coverage.boolean
isTypeRegistryCleared()
Returns `true` when type checking has run, but the type registry has been cleared.static java.lang.String
joinPathParts(java.lang.String... pathParts)
Creates an OS specific path string from partsvoid
maybeSetTracker()
protected CompilerOptions
newCompilerOptions()
Allow subclasses to override the default CompileOptions object.void
parse()
Parses input files without doing progress tracking that is part of a full compile.Node
parse(SourceFile file)
void
parseForCompilation()
Parses input files in preparation for compilation.Node
parseSyntheticCode(java.lang.String fileName, java.lang.String js)
Parses code for injecting, and associate it with a given source file.void
performPostCompilationTasks()
Performs all the bookkeeping required at the end of a compilation.void
printConfig()
void
rebuildInputsFromModules()
Rebuilds the internal input map by iterating over all modules.protected void
reconcileOptionsWithGuards()
When the CompilerOptions and its WarningsGuard overlap, reconcile any discrepancies.void
report(CheckLevel ignoredLevel, JSError error)
void
report(JSError error)
Report an error or warning.void
reportChangeToChangeScope(Node changeScopeRoot)
Mark modifications in a scope that is different than the Compiler.currentScope use this (eg, InlineVariables and many others)void
reportChangeToEnclosingScope(Node n)
Passes that make modifications in a scope that is different than the Compiler.currentScope use this (eg, InlineVariables and many others)void
reportFunctionDeleted(Node n)
void
resetAndIntitializeSourceMap()
protected void
restoreFromState(Compiler.CompilerState compilerState)
Restore the portions of the compiler state that don't require access to the serialized AST.void
restoreState(java.io.InputStream inputStream)
void
saveState(java.io.OutputStream outputStream)
void
setAccessorSummary(com.google.javascript.jscomp.AccessorSummary summary)
Sets the summary of properties with getters and setters.void
setAnonymousFunctionNameMap(VariableMap functionMap)
Sets the naming map for anonymous functionsvoid
setColorRegistry(ColorRegistry colorRegistry)
Sets the color registryvoid
setCssNames(java.util.LinkedHashMap<java.lang.String,java.lang.Integer> cssNames)
Sets the css names found during compilation.void
setErrorManager(ErrorManager errorManager)
Sets the error manager.void
setIdGeneratorMap(java.lang.String serializedIdMappings)
Sets the id generator for cross-module motion.void
setInstrumentationMapping(VariableMap instrumentationMapping)
Sets the mapping for instrumentation parameter encoding.static void
setLoggingLevel(java.util.logging.Level level)
Sets the logging level for the com.google.javascript.jscomp package.void
setModuleMap(ModuleMap moduleMap)
void
setModuleMetadataMap(ModuleMetadataMap moduleMetadataMap)
void
setPassConfig(PassConfig passes)
void
setPropertyMap(VariableMap propertyMap)
Sets the property renaming mapvoid
setStringMap(VariableMap stringMap)
Sets the string replacement mapvoid
setTimeout(int timeout)
Sets the timeout when Compiler is run in a threadvoid
setVariableMap(VariableMap variableMap)
Sets the variable renaming mapvoid
stage1Passes()
Perform compiler passes for stage 1 of compilation.void
stage2Passes()
Perform compiler passes for stage 2 of compilation.void
stage3Passes()
Perform compiler passes for stage 3 of compilation.java.lang.String
toSource()
Converts the main parse tree back to JS code.java.lang.String
toSource(CodePrinter.LicenseTracker licenseTracker, JSChunk module)
Converts the parse tree for a module back to JS code, using the given License Tracker to determine which licenses should be emitted before the source code.void
toSource(Compiler.CodeBuilder cb, int inputSeqNum, Node root)
Deprecated.use toSource(CodeBuilder, LicenseTracker, int, Node) instead for better license tracking.void
toSource(Compiler.CodeBuilder cb, CodePrinter.LicenseTracker licenseTracker, int inputSeqNum, Node root)
Writes out JS code from a root node.java.lang.String
toSource(JSChunk module)
Converts the parse tree for a module back to JS code.java.lang.String
toSource(Node n)
Generates JavaScript source code for an AST, doesn't generate source map info.java.lang.String[]
toSourceArray(CodePrinter.LicenseTracker licenseTracker, JSChunk module)
Converts the parse tree for each input in a module back to JS code, using the given License Tracker implementation to decide which licenses should be emitted before each input file.void
transpileAndDontCheck()
void
whitespaceOnlyPasses()
-
Methods inherited from class com.google.javascript.jscomp.AbstractCompiler
createAstFactory, createAstFactoryWithoutTypes, createDefaultExpressionDecomposer, createExpressionDecomposer, createOrReopenIndexedLog, createOrReopenLog, getAstAnalyzer, getDebugLogFilterList, getLifeCycleStage, isDebugLoggingEnabled, isFillFileName
-
-
-
-
Field Detail
-
tracker
public PerformanceTracker tracker
-
logger
public static final java.util.logging.Logger logger
Logger for the whole com.google.javascript.jscomp domain - setting configuration for this logger affects all loggers in other classes within the compiler.
-
recentChange
protected final com.google.javascript.jscomp.RecentChange recentChange
-
-
Constructor Detail
-
Compiler
public Compiler()
Creates a Compiler that reports errors and warnings to its logger.
-
Compiler
public Compiler(@Nullable java.io.PrintStream outStream)
Creates a 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 benull
-
initOptions
public void initOptions(CompilerOptions options)
Initializes the compiler options. It's called as part of a normal compile() job. Public for the callers that are not doing a normal compile() job.
-
printConfig
public void printConfig()
-
reconcileOptionsWithGuards
protected void reconcileOptionsWithGuards()
When the CompilerOptions and its WarningsGuard overlap, reconcile any discrepancies.
-
initWithTypedAstFilesystem
@GwtIncompatible public final void initWithTypedAstFilesystem(java.util.List<SourceFile> externs, java.util.List<SourceFile> sources, CompilerOptions options, java.io.InputStream typedAstListStream)
Initializes a compiler that will use pre-compiled TypedAst files instead of reading the source from disk
-
initModulesWithTypedAstFilesystem
@GwtIncompatible public void initModulesWithTypedAstFilesystem(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options, java.io.InputStream typedAstListStream)
Initializes a compiler that will use pre-compiled TypedAst files instead of reading the source from disk
-
initRuntimeLibraryTypedAsts
@GwtIncompatible public void initRuntimeLibraryTypedAsts(com.google.common.base.Optional<ColorPool.Builder> colorPoolBuilder)
Description copied from class:AbstractCompiler
Deserialize runtime libraries from a TypedAST packaged as a JAR resource and reconcile their Colors with the current inputs.This method must be called anywhere that Colors are reconciled for application to the AST. Otherwise Color information won't be consistent. `colorPoolBuilder` must be the same builder as used for the other inputs, and the caller retains ownership.
- Overrides:
initRuntimeLibraryTypedAsts
in classAbstractCompiler
- Parameters:
colorPoolBuilder
- if present, includes inferred optimization colors on the deserialized ASTs. If absent, does not include colors.
-
init
public final void init(java.util.List<SourceFile> externs, java.util.List<SourceFile> sources, CompilerOptions options)
Initializes the instance state needed for a compile job.
-
initModules
public void initModules(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options)
Initializes the instance state needed for a compile job if the sources are in modules.
-
initBasedOnOptions
public void initBasedOnOptions()
Do any initialization that is dependent on the compiler options.
-
joinPathParts
public static java.lang.String joinPathParts(java.lang.String... pathParts)
Creates an OS specific path string from parts
-
rebuildInputsFromModules
public void rebuildInputsFromModules()
Rebuilds the internal input map by iterating over all modules. This is necessary if inputs have been added to or removed from a module after aninit(java.util.List<com.google.javascript.jscomp.SourceFile>, java.util.List<com.google.javascript.jscomp.SourceFile>, com.google.javascript.jscomp.CompilerOptions)
orinitModules(java.util.List<com.google.javascript.jscomp.SourceFile>, java.util.List<com.google.javascript.jscomp.JSChunk>, com.google.javascript.jscomp.CompilerOptions)
call.
-
compile
public Result compile(SourceFile extern, SourceFile input, CompilerOptions options)
Compiles a single source file and a single externs file.
-
compile
public Result compile(java.util.List<SourceFile> externs, java.util.List<SourceFile> inputs, CompilerOptions options)
Compiles a list of inputs.This is a convenience method to wrap up all the work of compilation, including generating the error and warning report.
NOTE: All methods called here must be public, because client code must be able to replicate and customize this.
-
generateReport
public void generateReport()
Generates a report of all warnings and errors found during compilation to stderr.Client code must call this method explicitly if it doesn't use one of the convenience methods that do so automatically.
Always call this method, even if the compiler throws an exception. The report will include information about the exception.
-
compileModules
public Result compileModules(java.util.List<SourceFile> externs, java.util.List<JSChunk> modules, CompilerOptions options)
Compiles a list of modules.This is a convenience method to wrap up all the work of compilation, including generating the error and warning report.
NOTE: All methods called here must be public, because client code must be able to replicate and customize this.
-
stage1Passes
public void stage1Passes()
Perform compiler passes for stage 1 of compilation.Stage 1 consists primarily of error and type checking passes.
parseForCompilation()
must be called before this method is called.The caller is responsible for also calling
generateReport()
to generate a report of warnings and errors to stderr. See the invocation incompile(com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.CompilerOptions)
for a good example.
-
stage2Passes
public void stage2Passes()
Perform compiler passes for stage 2 of compilation.Stage 2 consists primarily of transpilation and optimization passes.
stage1Passes()
must be called before this method is called.The caller is responsible for also calling
generateReport()
to generate a report of warnings and errors to stderr. See the invocation incompile(com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.CompilerOptions)
for a good example.
-
stage3Passes
public void stage3Passes()
Perform compiler passes for stage 3 of compilation.Stage 3 consists primarily of localization passes.
stage2Passes()
must be called before this method is called.The caller is responsible for also calling
generateReport()
to generate a report of warnings and errors to stderr. See the invocation incompile(com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.CompilerOptions)
for a good example.
-
disableThreads
public void disableThreads()
Disable threads. This is for clients that run on AppEngine and don't have threads.
-
setTimeout
public void setTimeout(int timeout)
Sets the timeout when Compiler is run in a thread- Parameters:
timeout
- seconds to wait before timeout
-
performPostCompilationTasks
public void performPostCompilationTasks()
Performs all the bookkeeping required at the end of a compilation.This method must be called if the compilation makes it as far as doing checks.
DON'T call it if the compiler threw an exception.
DO call it even when
hasErrors()
returns true.
-
instrumentForCoverage
public void instrumentForCoverage()
Instrument code for coverage.parseForCompilation()
must be called before this method is called.The caller is responsible for also calling
generateReport()
to generate a report of warnings and errors to stderr. See the invocation incompile(com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.SourceFile, com.google.javascript.jscomp.CompilerOptions)
for a good example.This method is mutually exclusive with stage1Passes() and stage2Passes(). Either call those two methods or this one, but not both.
-
parseForCompilation
public void parseForCompilation()
Parses input files in preparation for compilation.Either
init()
orinitModules()
must be called first to set up the input files to be read.TODO(bradfordcsmith): Rename this to parse()
-
parse
public void parse()
Parses input files without doing progress tracking that is part of a full compile.Either
init()
orinitModules()
must be called first to set up the input files to be read.TODO(bradfordcsmith): Rename this to parseIndependentOfCompilation() or similar.
-
parse
public Node parse(SourceFile file)
-
createPassConfigInternal
protected PassConfig createPassConfigInternal()
Create the passes object. Clients should use setPassConfig instead of overriding this.
-
setPassConfig
public void setPassConfig(PassConfig passes)
- Parameters:
passes
- The PassConfig to use with this Compiler.- Throws:
java.lang.NullPointerException
- if passes is nulljava.lang.IllegalStateException
- if this.passes has already been assigned
-
whitespaceOnlyPasses
public void whitespaceOnlyPasses()
-
transpileAndDontCheck
public void transpileAndDontCheck()
-
getScriptNode
public final @Nullable Node getScriptNode(java.lang.String filename)
- Specified by:
getScriptNode
in classAbstractCompiler
-
getResult
public Result getResult()
Returns the result of the compilation.
-
getErrors
public com.google.common.collect.ImmutableList<JSError> getErrors()
Returns the list of errors (never null).
-
getWarnings
public com.google.common.collect.ImmutableList<JSError> getWarnings()
Returns the list 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.- Specified by:
getRoot
in classAbstractCompiler
-
getInput
public @Nullable CompilerInput getInput(InputId id)
Description copied from class:AbstractCompiler
Looks up an input (possibly an externs input) by input id. May return null.- Specified by:
getInput
in interfaceCompilerInputProvider
- Specified by:
getInput
in classAbstractCompiler
-
getModules
public @Nullable java.lang.Iterable<JSChunk> getModules()
Gets the JS source modules in dependency order.Returns null if
#init
or#initModules
hasn't been called yet. Otherwise, the result is always non-empty, even in the degenerate case where there's only one module.
-
clearJSTypeRegistry
public void clearJSTypeRegistry()
- Specified by:
clearJSTypeRegistry
in classAbstractCompiler
-
isTypeRegistryCleared
public boolean isTypeRegistryCleared()
Description copied from class:AbstractCompiler
Returns `true` when type checking has run, but the type registry has been cleared.See also `clearJSTypeRegistry()`.
- Specified by:
isTypeRegistryCleared
in classAbstractCompiler
-
getTypeRegistry
public JSTypeRegistry getTypeRegistry()
Description copied from class:AbstractCompiler
Gets a central registry of type information from the compiled JS.- Specified by:
getTypeRegistry
in classAbstractCompiler
-
getColorRegistry
public ColorRegistry getColorRegistry()
Description copied from class:AbstractCompiler
Gets a central registry of colors from deserialized JS types.- Specified by:
getColorRegistry
in classAbstractCompiler
-
setColorRegistry
public void setColorRegistry(ColorRegistry colorRegistry)
Description copied from class:AbstractCompiler
Sets the color registry- Specified by:
setColorRegistry
in classAbstractCompiler
-
forwardDeclareType
public void forwardDeclareType(java.lang.String typeName)
-
hasTypeCheckingRun
public boolean hasTypeCheckingRun()
Description copied from class:AbstractCompiler
Returns whether the typechecking passes have run- Specified by:
hasTypeCheckingRun
in classAbstractCompiler
-
hasOptimizationColors
public boolean hasOptimizationColors()
Description copied from class:AbstractCompiler
Whether the AST has been annotated with optimization colors.- Specified by:
hasOptimizationColors
in classAbstractCompiler
-
getTypedScopeCreator
public com.google.javascript.jscomp.ScopeCreator getTypedScopeCreator()
-
buildKnownSymbolTable
public SymbolTable buildKnownSymbolTable()
-
getTopScope
public TypedScope getTopScope()
Description copied from class:AbstractCompiler
Gets the top scope.- Specified by:
getTopScope
in classAbstractCompiler
-
getReverseAbstractInterpreter
public ReverseAbstractInterpreter getReverseAbstractInterpreter()
Description copied from class:AbstractCompiler
Get an interpreter for type analysis.- Specified by:
getReverseAbstractInterpreter
in classAbstractCompiler
-
getTypeMismatches
public java.lang.Iterable<TypeMismatch> getTypeMismatches()
Description copied from class:AbstractCompiler
Gets the central registry of type violations.- Specified by:
getTypeMismatches
in classAbstractCompiler
-
maybeSetTracker
public void maybeSetTracker()
-
newCompilerOptions
protected CompilerOptions newCompilerOptions()
Allow subclasses to override the default CompileOptions object.
-
parseSyntheticCode
public Node parseSyntheticCode(java.lang.String fileName, java.lang.String js)
Description copied from class:AbstractCompiler
Parses code for injecting, and associate it with a given source file.- Specified by:
parseSyntheticCode
in classAbstractCompiler
-
toSource
public java.lang.String toSource()
Converts the main parse tree back to JS code.- Specified by:
toSource
in classAbstractCompiler
-
toSource
public java.lang.String toSource(JSChunk module)
Converts the parse tree for a module back to JS code.Consider using toSource(JSChunk, LicenseTracker) for better license handling. This call will emit all license text attached to all direct inputs to the module, which can be very inefficient.
-
toSource
public java.lang.String toSource(CodePrinter.LicenseTracker licenseTracker, JSChunk module)
Converts the parse tree for a module back to JS code, using the given License Tracker to determine which licenses should be emitted before the source code.- Parameters:
licenseTracker
- The license tracker implementation to use.Compiler.ChunkGraphAwareLicenseTracker
is a suitable implementation when this method is being called on each module in the chunk graph in dependency order.
-
toSource
@Deprecated public void toSource(Compiler.CodeBuilder cb, int inputSeqNum, Node root)
Deprecated.use toSource(CodeBuilder, LicenseTracker, int, Node) instead for better license tracking.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.
-
toSource
public void toSource(Compiler.CodeBuilder cb, CodePrinter.LicenseTracker licenseTracker, 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.The LicenseTracker provided determines which licenses attached to the nodes visited should be included in the output. When building a single JS bundle, consider using the
Compiler.SingleBinaryLicenseTracker
implementation.
-
toSource
public java.lang.String toSource(Node n)
Generates JavaScript source code for an AST, doesn't generate source map info.- Specified by:
toSource
in classAbstractCompiler
-
getLicenseForFile
public static @Nullable java.lang.String getLicenseForFile(AbstractCompiler compiler, @Nullable java.lang.String fileName)
-
toSourceArray
public java.lang.String[] toSourceArray(CodePrinter.LicenseTracker licenseTracker, JSChunk module)
Converts the parse tree for each input in a module back to JS code, using the given License Tracker implementation to decide which licenses should be emitted before each input file.- Parameters:
licenseTracker
- The license tracker implementation to use.Compiler.ChunkGraphAwareLicenseTracker
is a suitable implementation when this method is being called on each module in the chunk graph in dependency order - see its javadoc on how to use it correctly.module
- the chunk being converted to source.
-
getExternsRoot
protected Node getExternsRoot()
-
getJsRoot
protected Node getJsRoot()
-
getChangeStamp
public int getChangeStamp()
-
incrementChangeStamp
public void incrementChangeStamp()
-
reportChangeToChangeScope
public void reportChangeToChangeScope(Node changeScopeRoot)
Description copied from class:AbstractCompiler
Mark modifications in a scope that is different than the Compiler.currentScope use this (eg, InlineVariables and many others)- Specified by:
reportChangeToChangeScope
in classAbstractCompiler
-
reportFunctionDeleted
public void reportFunctionDeleted(Node n)
-
reportChangeToEnclosingScope
public void reportChangeToEnclosingScope(Node n)
Description copied from class:AbstractCompiler
Passes that make modifications in a scope that is different than the Compiler.currentScope use this (eg, InlineVariables and many others)- Specified by:
reportChangeToEnclosingScope
in classAbstractCompiler
-
getCodingConvention
public CodingConvention getCodingConvention()
Description copied from class:AbstractCompiler
Gets the current coding convention.- Specified by:
getCodingConvention
in classAbstractCompiler
-
createConfig
protected Config createConfig(Config.LanguageMode mode, Config.StrictMode strictMode)
-
getDiagnosticGroups
public DiagnosticGroups getDiagnosticGroups()
The warning classes that are available from the command-line, and are suppressible by the@suppress
annotation.
-
report
public void report(JSError error)
Description copied from class:AbstractCompiler
Report an error or warning.- Specified by:
report
in classAbstractCompiler
-
report
public void report(CheckLevel ignoredLevel, JSError error)
- Specified by:
report
in interfaceErrorHandler
- Parameters:
ignoredLevel
- the reporting levelerror
- the error to report
-
getErrorLevel
public CheckLevel getErrorLevel(JSError error)
-
getErrorCount
public int getErrorCount()
Gets the number of errors.
-
getWarningCount
public int getWarningCount()
Gets the number of warnings.
-
hasErrors
public boolean hasErrors()
Consults theErrorManager
to see if we've encountered errors that should halt compilation.If
CompilerOptions.canContinueAfterErrors()
istrue
, this function always returnsfalse
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.
-
getSourceFileContentByName
public @Nullable java.lang.CharSequence getSourceFileContentByName(java.lang.String sourceName)
-
addInputSourceMap
public void addInputSourceMap(java.lang.String sourceFileName, SourceMapInput inputSourceMap)
Description copied from class:AbstractCompiler
Adds aSourceMapInput
for the givensourceFileName
, to be used for error reporting and source map combining.- Specified by:
addInputSourceMap
in classAbstractCompiler
-
getSourceMapping
public @Nullable com.google.debugging.sourcemap.proto.Mapping.OriginalMapping getSourceMapping(java.lang.String sourceName, int lineNumber, int columnNumber)
Description copied from interface:SourceFileMapping
Returns the original mapping for the file name, line number and column position found in the source map. Returnsnull
if none is found.- Specified by:
getSourceMapping
in interfaceSourceExcerptProvider
- Specified by:
getSourceMapping
in interfaceSourceFileMapping
lineNumber
- The line number, 1-based.columnNumber
- The column index, 1-based.
-
getSourceLine
public @Nullable java.lang.String getSourceLine(java.lang.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.- Specified by:
getSourceLine
in interfaceSourceExcerptProvider
lineNumber
- the line number, 1 being the first line of the file- Returns:
- the line indicated, or
null
if it does not exist
-
getSourceLines
public @Nullable Region getSourceLines(java.lang.String sourceName, int lineNumber, int length)
Description copied from interface:SourceExcerptProvider
Gets the specific lines returned by the beginning and excerpt length. Must not start or end with a carriage return. Implementations may decide to truncate lines but will always include the first line and never be longer than the specified length.- Specified by:
getSourceLines
in interfaceSourceExcerptProvider
lineNumber
- the line number, 1 being the first line of the filelength
- the desired length of the excerpt (in chars). If -1, returns just a single line. Otherwise, returns as many lines as needed. (including the remainder of the last line)- Returns:
- the region around the line number indicated, or
null
if it does not exist
-
getSourceRegion
public @Nullable Region getSourceRegion(java.lang.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.- Specified by:
getSourceRegion
in interfaceSourceExcerptProvider
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()
-
setVariableMap
public void setVariableMap(VariableMap variableMap)
Description copied from class:AbstractCompiler
Sets the variable renaming map- Specified by:
setVariableMap
in classAbstractCompiler
-
setPropertyMap
public void setPropertyMap(VariableMap propertyMap)
Description copied from class:AbstractCompiler
Sets the property renaming map- Specified by:
setPropertyMap
in classAbstractCompiler
-
setStringMap
public void setStringMap(VariableMap stringMap)
Description copied from class:AbstractCompiler
Sets the string replacement map- Specified by:
setStringMap
in classAbstractCompiler
-
setCssNames
public void setCssNames(java.util.LinkedHashMap<java.lang.String,java.lang.Integer> cssNames)
Description copied from class:AbstractCompiler
Sets the css names found during compilation.- Specified by:
setCssNames
in classAbstractCompiler
-
setIdGeneratorMap
public void setIdGeneratorMap(java.lang.String serializedIdMappings)
Description copied from class:AbstractCompiler
Sets the id generator for cross-module motion.- Specified by:
setIdGeneratorMap
in classAbstractCompiler
-
getCrossModuleIdGenerator
public IdGenerator getCrossModuleIdGenerator()
Description copied from class:AbstractCompiler
Gets the id generator for cross-module motion.- Specified by:
getCrossModuleIdGenerator
in classAbstractCompiler
-
setAnonymousFunctionNameMap
public void setAnonymousFunctionNameMap(VariableMap functionMap)
Description copied from class:AbstractCompiler
Sets the naming map for anonymous functions- Specified by:
setAnonymousFunctionNameMap
in classAbstractCompiler
-
setInstrumentationMapping
public void setInstrumentationMapping(VariableMap instrumentationMapping)
Description copied from class:AbstractCompiler
Sets the mapping for instrumentation parameter encoding.- Specified by:
setInstrumentationMapping
in classAbstractCompiler
-
getInstrumentationMapping
public VariableMap getInstrumentationMapping()
-
addExportedNames
public void addExportedNames(java.util.Set<java.lang.String> exportedNames)
Description copied from class:AbstractCompiler
Adds exported names to keep track.- Specified by:
addExportedNames
in classAbstractCompiler
-
getExportedNames
public java.util.Set<java.lang.String> getExportedNames()
Description copied from class:AbstractCompiler
Gets the names that have been exported.- Specified by:
getExportedNames
in classAbstractCompiler
-
getOptions
public CompilerOptions getOptions()
-
setLoggingLevel
public static void setLoggingLevel(java.util.logging.Level level)
Sets the logging level for the com.google.javascript.jscomp package.
-
getAstDotGraph
public java.lang.String getAstDotGraph() throws java.io.IOException
Gets the DOT graph of the AST generated at the end of compilation.- Throws:
java.io.IOException
-
getErrorManager
public ErrorManager getErrorManager()
Description copied from class:AbstractCompiler
Gets the error manager.- Specified by:
getErrorManager
in classAbstractCompiler
-
getInputsById
public java.util.Map<InputId,CompilerInput> getInputsById()
Returns an unmodifiable view of the compiler inputs indexed by id.
-
getExternProperties
public com.google.common.collect.ImmutableSet<java.lang.String> getExternProperties()
Description copied from class:AbstractCompiler
Gets the names of the properties defined in externs or null if GatherExternProperties pass was not run yet.- Specified by:
getExternProperties
in classAbstractCompiler
-
setAccessorSummary
public void setAccessorSummary(com.google.javascript.jscomp.AccessorSummary summary)
Description copied from class:AbstractCompiler
Sets the summary of properties with getters and setters.- Specified by:
setAccessorSummary
in classAbstractCompiler
-
ensureLibraryInjected
protected Node ensureLibraryInjected(java.lang.String resourceName, boolean force)
-
getComments
public java.util.List<Comment> getComments(java.lang.String filename)
-
getModuleLoader
public ModuleLoader getModuleLoader()
-
initWebpackMap
public void initWebpackMap(com.google.common.collect.ImmutableMap<java.lang.String,java.lang.String> inputPathByWebpackId)
-
createCompilerExecutor
protected com.google.javascript.jscomp.CompilerExecutor createCompilerExecutor()
-
getCompilerExecutor
protected com.google.javascript.jscomp.CompilerExecutor getCompilerExecutor()
-
restoreFromState
protected void restoreFromState(Compiler.CompilerState compilerState)
Restore the portions of the compiler state that don't require access to the serialized AST.
-
saveState
@GwtIncompatible("ObjectOutputStream") public void saveState(java.io.OutputStream outputStream) throws java.io.IOException
- Throws:
java.io.IOException
-
getCompilerState
protected Compiler.CompilerState getCompilerState()
-
restoreState
@GwtIncompatible("ClassNotFoundException") public void restoreState(java.io.InputStream inputStream) throws java.io.IOException, java.lang.ClassNotFoundException
- Throws:
java.io.IOException
java.lang.ClassNotFoundException
-
getModuleMetadataMap
public ModuleMetadataMap getModuleMetadataMap()
- Specified by:
getModuleMetadataMap
in classAbstractCompiler
-
setModuleMetadataMap
public void setModuleMetadataMap(ModuleMetadataMap moduleMetadataMap)
- Specified by:
setModuleMetadataMap
in classAbstractCompiler
-
getModuleMap
public ModuleMap getModuleMap()
- Specified by:
getModuleMap
in classAbstractCompiler
-
setModuleMap
public void setModuleMap(ModuleMap moduleMap)
- Specified by:
setModuleMap
in classAbstractCompiler
-
resetAndIntitializeSourceMap
public void resetAndIntitializeSourceMap()
-
-