Explain how to use SourceAwareCustomizer in a CompilerConfiguration to apply AST…
- User
Explain how to use
SourceAwareCustomizerin aCompilerConfigurationto apply AST transformations only to files ending in.dsl. Assistant
Explain how to use SourceAwareCustomizer in a CompilerConfiguration to apply AST transformations only to files ending in .dsl.
1. Understand the Goal: The user wants to know how to use SourceAwareCustomizer within a CompilerConfiguration to restrict AST (Abstract Syntax Tree) transformations to specific files, namely those ending in .dsl.
Identify the Key Components:
CompilerConfiguration and AST transformations are Groovy concepts).CompilerConfiguration: The class used to configure the Groovy compiler.ASTTransformation: The actual transformation logic (e.g., a custom annotation or a global transformation).SourceAwareCustomizer: A specific class used to filter when an AST transformation applies based on source unit properties (like the file name).*.dsl.Analyze SourceAwareCustomizer:
ASTTransformation and decides whether to apply that wrapped transformation based on a predicate (closure) or specific criteria (name, extension, etc.).setExtensionValidator, setSourceUnitValidator, or setValidator (a Closure).Determine the Context (Script vs. Annotation):
CompilerConfiguration (global).CompilerConfiguration. This implies a Global AST transformation or a customized compilation process (e.g., using GroovyShell or Groovyc programmatically).Step-by-Step Implementation Plan:
Step 1: Create/Identify the Transformation. I need a dummy or real AST transformation to wrap. Let's call it MyDslTransformation. It must implement ASTTransformation.
Step 2: Instantiate SourceAwareCustomizer.
MyDslTransformation to the constructor.Step 3: Configure the Filter (The .dsl part).
SourceAwareCustomizer:
sourceAwareCustomizer.setExtensionValidator({ ext -> ext == 'dsl' }). (Wait, looking at the API, usually setExtension expects a list or string, but SourceAwareCustomizer in newer Groovy versions allows closures).sourceAwareCustomizer.setSourceUnitValidator { sourceUnit -> sourceUnit.name.endsWith('.dsl') }. This is the most robust way to check the filename if the extension logic isn't strictly just the extension (though "files ending in .dsl" implies extension). Let's look for the cleanest API.SourceAwareCustomizer has setSourceUnitValidator(Closure<Boolean> validator). This is the safest bet. The SourceUnit has a getName() method which usually returns the filename.Step 4: Register with CompilerConfiguration.
CompilerConfiguration.SourceAwareCustomizer to the configuration.CompilerConfiguration programmatically, we inject the transformation instance directly.compilerConfiguration.addCompilationCustomizers(sourceAwareCustomizer).Refining the Example Code:
GroovyShell to run scripts.org.codehaus.groovy.control.CompilerConfiguration, org.codehaus.groovy.control.customizers.SourceAwareCustomizer, org.codehaus.groovy.ast.ASTTransformation, etc.Drafting the Code Structure:
// 1. The Delegate Transformation
def myTransform = new MyCustomAstTransformation()
// 2. The SourceAwareCustomizer
def sac = new SourceAwareCustomizer(myTransform)
// 3. The Filter Logic
sac.sourceUnitValidator = { sourceUnit ->
// check if name ends with .dsl
sourceUnit.name.endsWith('.dsl')
}
// 4. CompilerConfiguration
def config = new CompilerConfiguration()
config.addCompilationCustomizers(sac)
// 5. Usage
def shell = new GroovyShell(config)
Addressing Potential Pitfalls:
SourceUnit.getName() return the full path or just the filename? Usually just the filename provided to the source loader.setExtensionValidator? Groovy's SourceAwareCustomizer allows setExtension('dsl') in some contexts? No, checking the API: setExtensionValidator(Closure) exists, but setSourceUnitValidator is the most general. Let's stick to sourceUnitValidator for precision regarding "ending in .dsl" (as opposed to just the extension property which might be confused with class extensions).Wait, SourceAwareCustomizer actually has a constructor or setter specifically for extensions? Let's verify standard Groovy usage.
Actually, SourceAwareCustomizer is a CompilationCustomizer.
The API shows:
setSourceUnitValidator(Closure<Boolean> validator)
setExtensionValidator(Closure<Boolean> validator) (deprecated/removed in newer? Let's stick to SourceUnit).
Alternative approach:
sac.setExtensionValidator { it == 'dsl' } ?
Let's stick to the most reliable method: checking sourceUnit.name.
Structuring the Explanation:
SourceAwareCustomizer acts as a filter (decorator pattern) for AST transformations.GroovyShell.Refining the Code Snippet for the User:
Let's make the transformation logic generic (e.g., adding a method or printing "Transformed!").
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.SourceAwareCustomizer
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer // Wait, is SourceAwareCustomizer extending this?
import org.codehaus.groovy.ast.ASTTransformation
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.control.CompilationUnit
// ... imports ...
Actually, SourceAwareCustomizer is strictly a CompilationCustomizer. It is often used to wrap an ASTTransformation.
Wait, let's check the constructor.
public SourceAwareCustomizer(ASTTransformation transformation)
Yes.
The logic:
def customizer = new SourceAwareCustomizer(myTransformation)
customizer.setSourceUnitValidator { SourceUnit unit ->
unit.name.endsWith('.dsl')
}
Final Polish: Ensure the tone is helpful and the formatting is clear. Explain why we check sourceUnit.name. Mention that if running from a stream, the name might be different (e.g., "script1.groovy"), so ensuring the script is identified correctly is important.
Self-Correction during drafting: Is there a built-in way to check extension?
The API has setExtension(String)? No.
The API has setExtensionValidator(Closure).
sac.extensionValidator = { ext -> ext == 'dsl' }
This is cleaner if available. Checking Groovy 3+ docs... Yes, setExtensionValidator exists. It's often cleaner to say "I only want extension 'dsl'".
However, the user said "files ending in .dsl". SourceUnit.name is safer if the file is myfile.dsl.groovy (unlikely, but possible). If strictly extension, extensionValidator is fine. I will provide the sourceUnitValidator approach as the primary one because it offers the most control over the full filename, fitting the prompt "files ending in..." perfectly.
Output Generation: (Proceed to generate response based on these steps).
To use SourceAwareCustomizer to apply AST transformations only to files ending in .dsl, you need to wrap your existing AST transformation within the customizer and provide a closure (predicate) that checks the file extension.
Here is the step-by-step implementation.
SourceAwareCustomizer: This class intercepts the compilation process.sourceUnitValidator: This is a Closure that returns true or false. It receives the SourceUnit (the file being compiled), allowing you to check its name.CompilerConfiguration: Register the customizer with the compiler config.Here is a complete, runnable example using a GroovyShell. This setup ensures that the transformation is applied to script.dsl but ignored by script.groovy.
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.SourceAwareCustomizer
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.ModuleNode
import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
import org.codehaus.groovy.GroovyObject
import groovy.transform.CompileStatic
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
import org.codehaus.groovy.ast.builder.AstBuilder
// ---------------------------------------------------------
// 1. Define a Dummy AST Transformation (For demonstration)
// ---------------------------------------------------------
// This transformation simply adds a field named 'injectedByDsl' to the class.
@GroovyASTTransformation
class MyDslTransformation implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
println " -> [Transform Running] Acting on: ${sourceUnit.name}"
// Iterate over all classes in the file
sourceUnit.AST.classes.each { ClassNode classNode ->
// Add a simple field to prove the transform ran
classNode.addField("injectedByDsl", 1, ClassHelper.OBJECT_TYPE, null)
}
}
}
// ---------------------------------------------------------
// 2. Configure SourceAwareCustomizer
// ---------------------------------------------------------
// Initialize the base transformation
def myTransform = new MyDslTransformation()
// Initialize the SourceAwareCustomizer with the base transformation
def sourceAwareCustomizer = new SourceAwareCustomizer(myTransform)
// Set the validator closure
// 'sourceUnit' contains metadata about the file, specifically 'getName()' or 'getFile()'
sourceAwareCustomizer.sourceUnitValidator = { SourceUnit sourceUnit ->
// Logic: Return true ONLY if the filename ends with .dsl
def isValidDsl = sourceUnit.name?.endsWith('.dsl')
if (isValidDsl) {
println " [Validator] MATCH found: ${sourceUnit.name}. Applying Transform."
} else {
println " [Validator] Ignoring: ${sourceUnit.name}."
}
return isValidDsl
}
// ---------------------------------------------------------
// 3. Setup Compiler Configuration
// ---------------------------------------------------------
def config = new CompilerConfiguration()
// Add the customizer to the configuration
config.addCompilationCustomizers(sourceAwareCustomizer)
// ---------------------------------------------------------
// 4. Run the Test
// ---------------------------------------------------------
def shell = new GroovyShell(config)
println "--- Attempt 1: Compiling 'script.dsl' ---"
// This SHOULD trigger the transformation
shell.parse("""
class MyDslClass {}
""", "script.dsl") // The second argument sets the SourceUnit name
println "\n--- Attempt 2: Compiling 'normal.groovy' ---"
// This should NOT trigger the transformation
shell.parse("""
class MyNormalClass {}
""", "normal.groovy")
// Check the result of the first class
def dslClass = shell.getClassLoader().loadClass("MyDslClass")
println "\nResult: 'MyDslClass' has field 'injectedByDsl'? ${dslClass.declaredFields.any { it.name == 'injectedByDsl' }}"
The most important part is setting the sourceUnitValidator. This Closure determines if the transformation runs.
sourceAwareCustomizer.sourceUnitValidator = { SourceUnit sourceUnit ->
return sourceUnit.name?.endsWith('.dsl')
}
sourceUnit.name: Usually returns the filename (e.g., MyScript.dsl).sourceUnit.file: Returns the java.io.File object if it exists on disk. You can use sourceUnit.file?.path if you need full path checking.If your check is strictly against the file extension (and not the path or specific name), SourceAwareCustomizer also provides a convenience setter called extensionValidator.
// This is shorthand for checking file extensions
sourceAwareCustomizer.extensionValidator = { String extension ->
return extension == 'dsl'
}
This approach is ideal when you have a global transformation (like a script engine) where you want specific files to behave like a Domain Specific Language without requiring the user to annotate every class with @MyDslTransform.