Overview
TheLuaSyntaxRewriter class enables you to transform Lua syntax trees by visiting nodes and returning modified versions. It automatically reconstructs the tree with your changes while preserving the overall structure. This is the primary tool for code transformations in Loretta.
Namespace
Syntax
When to Use
UseLuaSyntaxRewriter when you need to:
- Transform or modify syntax trees
- Replace specific nodes with different nodes
- Rename identifiers
- Refactor code programmatically
- Add or remove nodes from the tree
- Preserve trivia (whitespace, comments) during transformations
Key Concepts
Immutability
Syntax trees in Loretta are immutable. When you modify a node:- A new node is created with the changes
- All parent nodes up to the root are recreated
- The original tree remains unchanged
Automatic Tree Reconstruction
The rewriter automatically:- Visits all nodes in the tree
- Reconstructs parent nodes when children change
- Preserves trivia (comments, whitespace) by default
- Maintains tree consistency
Constructor
visitIntoStructuredTrivia: Whether to visit into structured trivia nodes (rarely needed)
Key Properties
VisitIntoStructuredTrivia
Key Methods
Visit
VisitToken
VisitTrivia
VisitList
Examples
Example 1: Rename All Identifiers
Example 2: Convert Global Functions to Locals
This example is from the Creating a Localizer tutorial:Example 3: Add Return Statement to Functions
Example 4: Remove All Comments
Example 5: Transform Binary Operators
Tips for Preserving Trivia
Use WithTriviaFrom
Always preserve trivia when replacing nodes:Use NormalizeWhitespace
Normalize whitespace for generated nodes:Add Line Breaks Explicitly
Add line breaks after generated statements:Preserve Original Formatting
When updating nodes, use theUpdate method to preserve formatting:
Common Patterns
Pattern 1: Conditional Transformation
Pattern 2: Transform and Visit Children
Pattern 3: Remove Nodes
Pattern 4: Add Nodes to Lists
Important Notes
Performance Considerations
- The rewriter creates many intermediate objects
- For large trees, consider caching frequently used nodes
- Use
VisitListmethods efficiently
Error Handling
- Always check for null when calling Visit
- Handle cases where child nodes might be removed
- Validate tree structure after transformation
Testing Transformations
Always test your rewriter:See Also
- LuaSyntaxVisitor - For extracting information
- LuaSyntaxWalker - For automatic traversal
- SyntaxFactory - For creating syntax nodes
- Creating a Localizer Tutorial - Complete rewriter example