Package spoon.compiler
Interface Environment
- All Known Implementing Classes:
StandardEnvironment
public interface Environment
This interface represents the environment in which Spoon is launched -
accessible through
Factory.getEnvironment()
. Its
primary use is to report messages, warnings, and errors.-
Nested Class Summary
Modifier and TypeInterfaceDescriptionstatic class
Drives how the model is pretty-printed to disk, or whenCtElement.prettyprint()
is called -
Method Summary
Modifier and TypeMethodDescriptionboolean
Tells whether Spoon does no checks at all.Creates the default pretty-printer.Creates a pretty-printer that automatically imports used types and turns fully qualified type names into simply qualified names.void
debugMessage(String message)
Logs a debug messagevoid
Disable all consistency checks on the AST.Get the directory where binary .class files are createdint
Gets the Java version compliance level.Get the type of serialization to be used by defaultFileGenerator<? extends CtElement>
Returns the default file generator for this environment (gives the default output directory for the created files).Get the encoding used inside the projectGet encoding provider, which is used to detect encoding for each file separatelyint
Gets the error count from building, processing, and compiling within this environment.boolean
Returns the value ot the option ignore-syntax-errors.Returns theClassLoader
which is used by JDT and to resolve classes from references.getLevel()
Gets the level of loggers asked by the user.Gets the processing manager.get the model change listener that is used to follow the change of the AST.boolean
Returns the value ot the option noclasspathReturns the output destination that handles where source files are writtenGet the output typeGet the current pretty-printing mode.@Nullable ProcessorProperties
getProcessorProperties(String processorName)
Returns the properties for a given processor.String[]
Returns the source class path of the Spoon model.Returns the directory where source files are writtenGet the spoonProgress logger.int
Gets the size of the tabulations in the generated source code.int
Gets the warning count from building, processing, and compiling within this environment.boolean
Returns true if we let Spoon handle imports and turn fully qualified type names int simply qualified names.boolean
Returns the value of the option enable-comments.boolean
Returns the value of the option copy-resources.boolean
Whether Spoon currently ignores duplicate declarations of types.boolean
Tells if the source generator will try to preserve the original line numbers.boolean
Returns true if preview language features are enabled.boolean
Tells if the processing is stopped, generally because one of the processors calledsetProcessingStopped(boolean)
after reporting an error.boolean
Tells if Spoon uses tabulations in the source code.void
This method should be called to print out a message during the processing.void
Helper method called by a processor to report an error, warning or message as dictated by the severity parameter.void
This method should be called to report the end of the processing.void
reportProgressMessage(String message)
This method should be called to print out a progress message during the processing.void
setAutoImports(boolean autoImports)
Tell to the Java printer to automatically generate imports and use simple names instead of fully-qualified name.void
setBinaryOutputDirectory(String directory)
Set the directory where binary .class files are createdvoid
setCommentEnabled(boolean commentEnabled)
Sets the option enable-comments to parse comments of the target project.void
setComplianceLevel(int level)
Sets the Java version compliance level.void
setCompressionType(CompressionType serializationType)
Set the type of serialization to be used by defaultvoid
setCopyResources(boolean copyResources)
Sets the option copy-resources to copy all resources in a project on the folder destination.void
setDefaultFileGenerator(FileGenerator<? extends CtElement> generator)
Sets the default file generator for this environment.void
setEncoding(Charset encoding)
Set the encoding to use for parsing source codevoid
setEncodingProvider(EncodingProvider encodingProvider)
Set encoding provider, which is used to detect encoding for each file separatelyvoid
setIgnoreDuplicateDeclarations(boolean ignoreDuplicateDeclarations)
Set Spoon to ignore duplicate type declarations in a project.void
setIgnoreSyntaxErrors(boolean ignoreSyntaxErrors)
Sets the option ignore-syntax-errors to remove files with any syntax errors or JLS violations from the compilation batch.void
setInputClassLoader(ClassLoader classLoader)
Sets a specific classloader for JDT and reference resolutionvoid
Sets the level of loggers asked by the user.void
setManager(ProcessingManager manager)
Sets the processing manager of this environment.void
setModelChangeListener(FineModelChangeListener modelChangeListener)
Set the model change listenervoid
setNoClasspath(boolean option)
Sets the option "noclasspath", use with caution (see explanation below).void
setOutputDestinationHandler(OutputDestinationHandler outputDestinationHandler)
Set the output destination that handles where source files are writtenvoid
setOutputType(OutputType outputType)
Set the output type used for processing filesvoid
setPreserveLineNumbers(boolean preserveLineNumbers)
When set, the generated source code will try to generate code that preserves the line numbers of the original source code.void
setPrettyPrinterCreator(Supplier<PrettyPrinter> creator)
Sets a custom pretty-printer that overrides the default pretty-printer.void
setPrettyPrintingMode(Environment.PRETTY_PRINTING_MODE prettyPrintingMode)
void
setPreviewFeaturesEnabled(boolean enabled)
Set to true to enable latest preview language features.void
setProcessingStopped(boolean processingStopped)
This method can be called to stop the processing and all the remaining tasks.void
setProcessorProperties(String processorName, ProcessorProperties prop)
Sets the properties for a given processor.void
setShouldCompile(boolean shouldCompile)
Sets the compile argument.void
setSourceClasspath(String[] sourceClasspath)
Sets the source class path of the Spoon model.void
setSourceOutputDirectory(File directory)
Sets the directory where source files are writtenvoid
setSpoonProgress(SpoonProgress spoonProgress)
void
setTabulationSize(int size)
Sets the size of the tabulations in the generated source code.void
setUseLegacyTypeAdaption(boolean useLegacyTypeAdaption)
Deprecated, for removal: This API element is subject to removal in a future version.boolean
Checks if we want compile the target source code and get their binary.boolean
Deprecated, for removal: This API element is subject to removal in a future version.void
useTabulations(boolean b)
Sets Spoon to use tabulations in the source code.
-
Method Details
-
getComplianceLevel
int getComplianceLevel()Gets the Java version compliance level.- Returns:
- the compliance level
-
setComplianceLevel
void setComplianceLevel(int level)Sets the Java version compliance level.- Parameters:
level
- the compliance level
-
isPreviewFeaturesEnabled
boolean isPreviewFeaturesEnabled()Returns true if preview language features are enabled.- Returns:
- true iff preview features are enabled
-
setPreviewFeaturesEnabled
void setPreviewFeaturesEnabled(boolean enabled)Set to true to enable latest preview language features. Note: compliance level should be set to the latest.- Parameters:
enabled
- whether to enable preview features
-
getPrettyPrintingMode
Environment.PRETTY_PRINTING_MODE getPrettyPrintingMode()Get the current pretty-printing mode. most robust:Environment.PRETTY_PRINTING_MODE.DEBUG
most sophisticated:Environment.PRETTY_PRINTING_MODE.AUTOIMPORT
- Returns:
- the kind of pretty-printing expected.
-
setPrettyPrintingMode
-
debugMessage
Logs a debug message- Parameters:
message
- a message to write to the debug log
-
getDefaultFileGenerator
FileGenerator<? extends CtElement> getDefaultFileGenerator()Returns the default file generator for this environment (gives the default output directory for the created files).- Returns:
- the default file generator
-
getManager
ProcessingManager getManager()Gets the processing manager.- Returns:
- the current processing manager
-
getProcessorProperties
Returns the properties for a given processor.- Parameters:
processorName
- fully qualified name of a processor- Returns:
- properties for the processor, or
null
if there is no processor by that name
-
setProcessorProperties
Sets the properties for a given processor.- Parameters:
processorName
- fully qualified name of the processorprop
- properties to set
-
isAutoImports
boolean isAutoImports()Returns true if we let Spoon handle imports and turn fully qualified type names int simply qualified names.- Returns:
- true iff Spoon is set to automatically import types and simplify type names
-
isProcessingStopped
boolean isProcessingStopped()Tells if the processing is stopped, generally because one of the processors calledsetProcessingStopped(boolean)
after reporting an error.- Returns:
- true iff processing has been forcibly aborted
-
report
Helper method called by a processor to report an error, warning or message as dictated by the severity parameter. Note that this does not stop the processing or any remaining task. To do so, usesetProcessingStopped(boolean)
.- Parameters:
processor
- The processor that report this message. Can be null.level
- The level of the reportelement
- The CtElement to which the report is associatedmessage
- The message to report
-
report
This method should be called to print out a message during the processing.- Parameters:
processor
- The processor that report this message. Can be null.level
- The level of the reportmessage
- The message to report
-
reportEnd
void reportEnd()This method should be called to report the end of the processing. -
reportProgressMessage
This method should be called to print out a progress message during the processing. On contrary to regular messages, progress messages are not meant to remain in the message logs and just indicate to the user some task progression information.- Parameters:
message
- a message to print
-
setDefaultFileGenerator
Sets the default file generator for this environment.- Parameters:
generator
- a file generator to set as the default
-
setManager
Sets the processing manager of this environment.- Parameters:
manager
- a processing manager to set as the default
-
setProcessingStopped
void setProcessingStopped(boolean processingStopped)This method can be called to stop the processing and all the remaining tasks. In general, a processor calls it after reporting a fatal error.- Parameters:
processingStopped
- if true, any ongoing processing is aborted as soon as possible and future processing is prohibited
-
getTabulationSize
int getTabulationSize()Gets the size of the tabulations in the generated source code.- Returns:
- the current tabulation size
-
setTabulationSize
void setTabulationSize(int size)Sets the size of the tabulations in the generated source code.- Parameters:
size
- tabulation size to set
-
isUsingTabulations
boolean isUsingTabulations()Tells if Spoon uses tabulations in the source code.- Returns:
- true iff Spoon uses tabulations when pretty-printing
-
useTabulations
void useTabulations(boolean b)Sets Spoon to use tabulations in the source code.- Parameters:
b
- whether Spoon should use tabulations when pretty-printing
-
setAutoImports
void setAutoImports(boolean autoImports)Tell to the Java printer to automatically generate imports and use simple names instead of fully-qualified name.- Parameters:
autoImports
- whether Spoon should auto-import types and simplify names
-
getErrorCount
int getErrorCount()Gets the error count from building, processing, and compiling within this environment.- Returns:
- the amount of errors that have occurred
-
getWarningCount
int getWarningCount()Gets the warning count from building, processing, and compiling within this environment.- Returns:
- the amount of warnings that have occurred
-
getInputClassLoader
ClassLoader getInputClassLoader()Returns theClassLoader
which is used by JDT and to resolve classes from references. By default, returns a class loader able to load classes from the Spoon-specific class path set withsetSourceClasspath(String[])
- Returns:
- the currently configured classloader
-
setInputClassLoader
Sets a specific classloader for JDT and reference resolution- Parameters:
classLoader
- a classloader to set
-
setPreserveLineNumbers
void setPreserveLineNumbers(boolean preserveLineNumbers)When set, the generated source code will try to generate code that preserves the line numbers of the original source code. This option may lead to difficult-to-read indentation and formatting.- Parameters:
preserveLineNumbers
- whether Spoon should attempt to preserve line numbers when pretty-printing
-
isPreserveLineNumbers
boolean isPreserveLineNumbers()Tells if the source generator will try to preserve the original line numbers.- Returns:
- true iff Spoon attempts to preserve line numbers of elements when pretty-printing
-
getSourceClasspath
String[] getSourceClasspath()Returns the source class path of the Spoon model. This class path is used when the SpoonCompiler is building the model and also to find external classes, referenced from within the model.- Returns:
- all paths in the classpath
-
setSourceClasspath
Sets the source class path of the Spoon model. After the class path is set, it can be retrieved bygetSourceClasspath()
. Only .jar files or directories with *.class files are accepted. The *.jar or *.java files contained in given directories are ignored.- Parameters:
sourceClasspath
- classpath to set- Throws:
InvalidClassPathException
- if a given classpath does not exists or does not have the right format (.jar file or directory)
-
setNoClasspath
void setNoClasspath(boolean option)Sets the option "noclasspath", use with caution (see explanation below). With this option, Spoon does not require the full classpath to build the model. In this case, all references to classes that are not in the classpath are handled with the reference mechanism. The "simplename" of the reference object refers to the unbound identifier. This option facilitates the use of Spoon when it is hard to have the complete and correct classpath, for example for mining software repositories. For writing analyses, this option works well if you don't cross the reference by a call to getDeclaration() (if you really want to do so, then check for nullness of the result before). In normal mode, compilation errors are signaled as exception, with this option enabled they are signaled as message only. The reason is that in most cases, there are necessarily errors related to the missing classpath elements.- Parameters:
option
- whether to set Spoon to noclasspath mode
-
getNoClasspath
boolean getNoClasspath()Returns the value ot the option noclasspath- Returns:
- true iff Spoon is currently in noclasspath mode
-
setIgnoreSyntaxErrors
void setIgnoreSyntaxErrors(boolean ignoreSyntaxErrors)Sets the option ignore-syntax-errors to remove files with any syntax errors or JLS violations from the compilation batch. Also while transformations no checks for JLS correctness are reported as error.- Parameters:
ignoreSyntaxErrors
- whether Spoon should ignore files with any syntax errors or JLS violations
-
getIgnoreSyntaxErrors
boolean getIgnoreSyntaxErrors()Returns the value ot the option ignore-syntax-errors.- Returns:
- true iff Spoon ignores files with any syntax errors, JLS violations or reports JLS correctness problems as exception.
-
isCopyResources
boolean isCopyResources()Returns the value of the option copy-resources.- Returns:
- true iff Spoon should copy resource files from the project when pretty-printing
-
setCopyResources
void setCopyResources(boolean copyResources)Sets the option copy-resources to copy all resources in a project on the folder destination.- Parameters:
copyResources
- whether Spoon should copy resources
-
isCommentsEnabled
boolean isCommentsEnabled()Returns the value of the option enable-comments.- Returns:
- true iff Spoon respects comments in source code
-
setCommentEnabled
void setCommentEnabled(boolean commentEnabled)Sets the option enable-comments to parse comments of the target project.- Parameters:
commentEnabled
- whether Spoon should respect comments in source code
-
getLevel
Level getLevel()Gets the level of loggers asked by the user.- Returns:
- the current logging level
-
setLevel
Sets the level of loggers asked by the user.- Parameters:
level
- the logging level to set, seeLevel
for options
-
shouldCompile
boolean shouldCompile()Checks if we want compile the target source code and get their binary.- Returns:
- true iff Spoon should compile target source code
-
setShouldCompile
void setShouldCompile(boolean shouldCompile)Sets the compile argument.- Parameters:
shouldCompile
- whether Spoon should compile target source code
-
checksAreSkipped
boolean checksAreSkipped()Tells whether Spoon does no checks at all. - parents are consistent (seeAstParentConsistencyChecker
) - hashcode violation (seeCtElementImpl.equals(Object)
) - method violation (seeCtType.addMethod(CtMethod)
) are active or not. By default all checks are enabled andchecksAreSkipped()
return false.- Returns:
- true iff Spoon skips consistency checks
-
disableConsistencyChecks
void disableConsistencyChecks()Disable all consistency checks on the AST. Dangerous! The only valid usage of this is to keep full backward-compatibility. -
setBinaryOutputDirectory
Set the directory where binary .class files are created- Parameters:
directory
- path to set for the binary output directory
-
getBinaryOutputDirectory
String getBinaryOutputDirectory()Get the directory where binary .class files are created- Returns:
- path to the binary output directory
-
setSourceOutputDirectory
Sets the directory where source files are written- Parameters:
directory
- path to set for the source output directory
-
getSourceOutputDirectory
File getSourceOutputDirectory()Returns the directory where source files are written- Returns:
- path to the source output directory
-
setOutputDestinationHandler
Set the output destination that handles where source files are written- Parameters:
outputDestinationHandler
- handler for determining where to write source files
-
getOutputDestinationHandler
OutputDestinationHandler getOutputDestinationHandler()Returns the output destination that handles where source files are written- Returns:
- the current output destination handler
-
getModelChangeListener
FineModelChangeListener getModelChangeListener()get the model change listener that is used to follow the change of the AST.- Returns:
- the current change listener
-
setModelChangeListener
Set the model change listener- Parameters:
modelChangeListener
- change listener to set
-
getEncoding
Charset getEncoding()Get the encoding used inside the project- Returns:
- encoding used in the project
-
getEncodingProvider
EncodingProvider getEncodingProvider()Get encoding provider, which is used to detect encoding for each file separately- Returns:
- the current encoding provider
-
setEncoding
Set the encoding to use for parsing source code- Parameters:
encoding
- the character set to use for source file encoding
-
setEncodingProvider
Set encoding provider, which is used to detect encoding for each file separately- Parameters:
encodingProvider
- the encoding provider to set
-
setOutputType
Set the output type used for processing files- Parameters:
outputType
- output type to use when pretty-printing
-
getOutputType
OutputType getOutputType()Get the output type- Returns:
- the current output type
-
getSpoonProgress
SpoonProgress getSpoonProgress()Get the spoonProgress logger. This method mustn't return null.- Returns:
- the spoonProgress
-
setSpoonProgress
-
getCompressionType
CompressionType getCompressionType()Get the type of serialization to be used by default- Returns:
- the current type of serialization
-
setCompressionType
Set the type of serialization to be used by default- Parameters:
serializationType
- the type of serialization to set
-
createPrettyPrinter
PrettyPrinter createPrettyPrinter()Creates the default pretty-printer.- Returns:
- new instance of
PrettyPrinter
which is configured for this environment
-
createPrettyPrinterAutoImport
PrettyPrinter createPrettyPrinterAutoImport()Creates a pretty-printer that automatically imports used types and turns fully qualified type names into simply qualified names. This is roughly equivalent to settingsetAutoImports(boolean)
totrue
and then invokincreatePrettyPrinter()
, except that the environment is not modified.- Returns:
- new instance of
PrettyPrinter
which prints nice code
-
setPrettyPrinterCreator
Sets a custom pretty-printer that overrides the default pretty-printer. Can for example be used to create aSniperJavaPrettyPrinter
for enabling the sniper mode.env.setPrettyPrinterCreator(() -> new SniperJavaPrettyPrinter(env));
- Parameters:
creator
- aSupplier
, which creates new instance of pretty printer.
-
useLegacyTypeAdaption
Deprecated, for removal: This API element is subject to removal in a future version.Whether to use the new or legacy and (soon to be) deprecated type adaption. You should not use this method.- Returns:
- true if spoon uses the old and (soon to be) deprecated type adaption.
-
setUseLegacyTypeAdaption
@Deprecated(forRemoval=true, since="10.2.0") void setUseLegacyTypeAdaption(boolean useLegacyTypeAdaption)Deprecated, for removal: This API element is subject to removal in a future version.Sets whether to use the new or legacy and (soon to be) deprecated type adaption. You should not use this method.- Parameters:
useLegacyTypeAdaption
- whether to use the old type adaption implementation
-
isIgnoreDuplicateDeclarations
boolean isIgnoreDuplicateDeclarations()Whether Spoon currently ignores duplicate declarations of types.- Returns:
- true if spoon is allowed to create a model of a project that contains multiple copies of the same class
-
setIgnoreDuplicateDeclarations
void setIgnoreDuplicateDeclarations(boolean ignoreDuplicateDeclarations)Set Spoon to ignore duplicate type declarations in a project. Setting this option totrue
causes Spoon to attempt to build a model even when the same qualified name appears for multiple types. This mode of operation makes Spoon less stable as duplicated types do not make sense in Java, and causes strange behavior in the underlying JDT compiler. Type resolution can become unpredictable as the order in which types are parsed becomes a determining factor in which duplicated type actually makes it into the model.- Parameters:
ignoreDuplicateDeclarations
- (default false) set to true to allow spoon to create a model of a project that contains multiple times the same class
-