Derive the code for a global AST transformation that automatically capitalizes all…
- User
Derive the code for a global AST transformation that automatically capitalizes all String literals in the source code at compile time.
Assistant
Derive the code for a global AST transformation that automatically capitalizes all String literals in the source code at compile time.
The user wants a Groovy AST (Abstract Syntax Tree) transformation that globally modifies String literals in the source code to be capitalized. Specifically, "global" means it applies to the whole project/module where it's configured, not just annotated classes. The modification is: "capitalizes all String literals". This usually means converting the string to uppercase (e.g., "hello" -> "HELLO").
1. Understanding AST Transformations in Groovy:
@Singleton). Global transformations are triggered by a META-INF/services/org.codehaus.groovy.transform.ASTTransformation file in the classpath.SEMANTIC_ANALYSIS or CONVERSION are common, but modifying constants often needs to happen when the constants are resolved. However, simply changing a ConstantExpression can be done. Let's aim for SEMANTIC_ANALYSIS.2. Analyzing the Request:
3. Designing the Transformation Class:
org.codehaus.groovy.transform.ASTTransformation.@GroovyASTTransformation annotation to specify the phase.4. The Visitor Pattern:
ConstantExpression nodes where the value is a String.5. Step-by-Step Implementation Plan:
Step 1: The Class Structure.
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class CapitalizeStringTransformation implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
// Logic here
}
}
Step 2: Traversing the AST.
The nodes array passed to visit usually contains the SourceUnit and the root node (ModuleNode). But for a global transformation, the nodes array typically contains the ASTNode that triggered it? Wait, global transformations receive (ASTNode[], SourceUnit). The ASTNode[] is usually empty or contains the SourceUnit's top-level node depending on how it's registered? Actually, for a standard Global Transformation, the entry point is visit(ASTNode[] nodes, SourceUnit sourceUnit). The first element is the module node.
I need to iterate through all classes/methods/statements to find the string literals. Groovy provides ClassCodeVisitorSupport or CodeVisitorSupport to help with traversal.
Correction: Global transformations run once per source unit. I should get the ModuleNode from the sourceUnit and traverse it.
Step 3: The Visitor.
I need a custom visitor that extends ClassCodeVisitorSupport.
I need to override visitConstantExpression(ConstantExpression expression).
Inside:
Check if expression.value is a String.
If so, update it: expression.value = expression.value.toString().toUpperCase().
Edge case: GStrings (interpolated strings like "Hello ${name}"). The prompt asks for "String literals". Technically GStrings are separate nodes. I should probably stick to ConstantExpression which represents plain Java/Groovy strings. If I touch GStrings, I might break the logic of the variables embedded in them. Let's stick to ConstantExpression.
Step 4: Handling Safety. AST manipulation can be tricky. I need to ensure I don't modify nulls or non-strings. Also, I need to handle the "Global" registration aspect.
Step 5: The META-INF descriptor.
This is crucial for a global transformation. I must explain how to create the file META-INF/services/org.codehaus.groovy.transform.ASTTransformation containing the full class name of the transformation.
6. Refing the Visitor Logic:
class CapitalizingVisitor extends ClassCodeVisitorSupport {
@Override
void visitConstantExpression(ConstantExpression expression) {
if (expression.value instanceof String) {
// Create a new expression or modify in place?
// Modifying in place is safer for retaining line numbers etc, though setting value might work.
// Actually, ConstantExpression has a 'value' field.
// We can't simply set it because it's often final or intended to be immutable in logic,
// but in AST, we are modifying the tree before code gen.
// However, there is a specific constructor or method to update text?
// Let's look at the API.
// expression.setValue(...) exists? No, ConstantExpression.value is field.
// It's safer to replace the node? Or just modify the object.
// Let's modify the object for simplicity, assuming standard Groovy AST capabilities.
def original = expression.value
def newVal = original.toUpperCase()
// We need to be careful. If this string is a key in a map or annotation attribute,
// it might need to be a literal.
expression.value = newVal
}
}
// Must implement this
protected SourceUnit getSourceUnit() { return null }
}
Wait, modifying ConstantExpression.value directly might be restricted or cause issues if the type inference has already run. Since this is SEMANTIC_ANALYSIS, it should be okay.
7. Putting it together in the ASTTransformation:
class CapitalizeStringTransformation implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
// Create the visitor
def visitor = new CapitalizingVisitor()
// Iterate over all classes in the module
sourceUnit.AST.classes.each { classNode ->
visitor.visitClass(classNode)
}
}
}
8. Compilation & Build setup: The user asked for the code, but for this to work, the transformation must be compiled before the code it transforms (separate module or previous build step). I should mention this.
9. Refinement on "Capitalize":
Does "capitalize" mean "First letter upper case" or "ALL CAPS"?
In standard programming terminology, toUpperCase() (ALL CAPS) is usually what's meant when modifying constants for things like logging or identifying keys. However, capitalize() usually means "Hello".
Given the context of AST transformations (often used for standardization or obfuscation), toUpperCase() is the most distinct operation to demonstrate the effect clearly (e.g., seeing "hello" become "HELLO"). I will implement toUpperCase() but add a note.
10. Code Structure:
Let's write the code.
Imports: org.codehaus.groovy.ast.*, org.codehaus.groovy.ast.expr.*, org.codehaus.groovy.control.*, org.codehaus.groovy.transform.*.
Phase: CompilePhase.SEMANTIC_ANALYSIS.
The Visitor Logic:
Groovy AST traversal works by visiting statements and expressions.
ClassCodeVisitorSupport visits classes, methods, fields.
Inside methods, we have BlockStatement, which contains expressions.
We need to intercept ConstantExpression.
Self-Correction: ConstantExpression is also used for numbers, booleans, etc. Must check instanceof String.
11. Drafting the code (Mental or Scratchpad):
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
class CapitalizeStringTransform implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
// Create a visitor to traverse the AST
def visitor = new MyVisitor()
// Apply to all classes
sourceUnit.getAST().getClasses().each { cn ->
visitor.visitClass(cn)
}
}
}
class MyVisitor extends ClassCodeVisitorSupport {
void visitConstantExpression(ConstantExpression ce) {
if (ce.value instanceof String) {
ce.value = ce.value.toString().toUpperCase() // Or capitalize
}
}
protected SourceUnit getSourceUnit() { null }
}
12. Wait, visitMethod and Code.
ClassCodeVisitorSupport handles method structure, but does it dive into the code statements automatically?
Yes, visitClass -> visitMethod -> visitStatement (which handles code blocks).
However, ConstantExpression is an expression.
Does ClassCodeVisitorSupport traverse expressions inside statements?
Yes, visitMethod calls MethodNode.getCode().visit(this).
So BlockStatement calls visit on its children.
Crucial Detail: Global transformations are applied to every file being compiled. This includes the transformation itself if it's in the same source set. Usually, transformations must be pre-compiled. I will treat this as a standalone project/module.
13. Final Polish: I will provide:
META-INF/services file.build.gradle or explanation of how to package it.I will assume toUpperCase() implies "capitalize" in the "make capital letters" sense, as opposed to just the first letter, because that creates a more visually obvious transformation for testing.
Summary of the solution:
CapitalizeStringsTransformation@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)ConstantExpression with String value, set value to value.toUpperCase().Let's write the actual response.
Constraint Checklist & Confidence Score:
Mental Sandbox Simulation:
Input: def s = "hello"
AST: VariableExpression("s") = ConstantExpression("hello")
Transform visits ConstantExpression. Sees "hello". Changes to "HELLO".
Bytecode generated: String s = "HELLO";
Result: Success.
Input: @Author(name="john")
AST: Annotation with member name -> ConstantExpression("john").
Transform visits. Changes to "JOHN".
Result: Annotation value is now "JOHN". This satisfies "all String literals".
Input: println "${x}"
AST: GStringExpression containing ConstantExpression("prefix")?
GString is composed of strings and values.
If I do "Hello ${name}", the AST is GStringExpression. It holds a list of strings (verbatims) and values.
The visitor needs to catch the strings inside GString too.
ClassCodeVisitorSupport calls visitConstantExpression. Does it visit inside GString?
GStringExpression has a method visit(MethodCodeVisitor). It usually delegates to the verifier.
Actually, looking at CodeVisitorSupport, visitGStringExpression iterates over strings.
But visitConstantExpression is the terminal method.
If I override visitConstantExpression, it catches the string chunks of a GString as well.
So just overriding visitConstantExpression is the robust way to get all string literals, including annotations and GString parts.
Let's double check GStringExpression.
It contains strings (list of ConstantExpressions) and values (list of Expressions).
When GStringExpression.visit(visitor) is called, it iterates over strings and calls visitor.visitConstantExpression.
So yes, simply overriding visitConstantExpression covers annotations, variables, and GStrings.
Final check on Global aspect.
The user needs the META-INF file explanation, otherwise it's not "Global", just a class sitting there.
I will structure the answer to provide the Java/Groovy code, the registration file, and a brief explanation of how to use it.
To create a Global AST Transformation in Groovy that modifies String literals, you need to implement the ASTTransformation interface and specifically target the CompilePhase.SEMANTIC_ANALYSIS.
Here is the complete implementation code, followed by the necessary configuration steps to make it work.
Save this file as CapitalizeStringTransformation.groovy.
package com.example.transform
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.ClassCodeVisitorSupport
import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.Expression
import org.codehaus.groovy.ast.expr.GStringExpression
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
import org.objectweb.asm.Opcodes
/**
* A Global AST Transformation that capitalizes all String literals found in the source code.
*/
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class CapitalizeStringTransformation implements ASTTransformation, Opcodes {
@Override
void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
// Create a custom visitor to traverse the Abstract Syntax Tree
def visitor = new CapitalizingVisitor(sourceUnit)
// Iterate over all classes (Script, Class, etc.) in the source file
sourceUnit.getAST().getClasses().each { classNode ->
visitor.visitClass(classNode)
}
}
}
/**
* The Visitor that walks through the code nodes and performs the modification.
*/
class CapitalizingVisitor extends ClassCodeVisitorSupport {
SourceUnit sourceUnit
CapitalizingVisitor(SourceUnit sourceUnit) {
this.sourceUnit = sourceUnit
}
@Override
protected SourceUnit getSourceUnit() {
return sourceUnit
}
/**
* Called whenever a ConstantExpression (like a String, Number, Boolean) is found.
*/
@Override
void visitConstantExpression(ConstantExpression expression) {
// 1. Check if the value is a String
if (expression.value instanceof String) {
String original = expression.value
// 2. Apply Capitalization (UpperCase)
// Note: In a real-world scenario, you might want to check for empty strings
if (original) {
String transformed = original.toUpperCase()
// 3. Modify the AST Node in place
// Using the setter ensures the type information remains consistent
expression.value = transformed
// Optional: Update the text representation used by some tools/debuggers
expression.text = transformed
}
}
super.visitConstantExpression(expression)
}
}
Global transformations are not activated by annotations. They require a specific service file to be present in the classpath at compile time.
src/main/resources/META-INF/services/.org.codehaus.groovy.transform.ASTTransformation.com.example.transform.CapitalizeStringTransformation
For a Global Transformation to work, the transformation code (and the config file) must be on the classpath of the project you are compiling.
Example setup (using Gradle):
META-INF folder is included in the JAR.build.gradle (usually in the implementation or compileOnly configuration).Test Script (in Project B):
// Before compilation logic runs:
// This literal will be modified by the AST transformation
def greeting = "hello world"
println greeting
Output at Runtime:
HELLO WORLD
visitConstantExpression, we intercept every hardcoded value in the source."Hello ${name}", "Hello " becomes "HELLO ").SEMANTIC_ANALYSIS. This is early enough that the source code has been parsed into an AST, but late enough that we can modify it before it is turned into bytecode.value) of the existing ConstantExpression node.