rs-hack
AST-aware Rust code editing tool designed for AI agents and automated refactoring.
Why?
String-based search and replace (sed, Python regex) is fragile for code:
- Breaks on formatting changes
- Can't distinguish between similar patterns
- No semantic understanding
- Risk of partial matches
This tool uses Rust's syn parser to make precise, AST-aware edits based on actual code structure.
Use Cases
Perfect for AI agents making systematic changes across codebases:
✅ Migration tasks: "Add #[derive(Clone)] to all structs"
✅ API updates: "Add new field with default to 50 struct definitions"
✅ Enum expansion: "Add Unknown variant to all enums, update matches"
✅ Code generation: "Add builder methods to all structs with >3 fields"
Installation
From crates.io (after publishing)
From source
The binary will be installed to ~/.cargo/bin/rs-hack.
Quick Start
# Add derive macros with glob pattern
# Auto-detect and add missing match arms
# Add a method to an impl block
# Add a use statement
Supported Operations (20 commands)
Struct Operations (4)
- ✅ add-struct-field: Add fields to definitions (with optional
--literal-default) - ✅ add-struct-literal-field: Add fields to literal expressions only
- ✅ update-struct-field: Update field types/visibility
- ✅ remove-struct-field: Remove fields
Enum Operations (3)
- ✅ add-enum-variant, update-enum-variant, remove-enum-variant
Match Operations (3)
- ✅ add-match-arm (with
--auto-detectfor missing variants) - ✅ update-match-arm, remove-match-arm
Code Organization (3)
- ✅ add-derive: Derive macros (with
--wherefilter support) - ✅ add-impl-method: Methods to impl blocks
- ✅ add-use: Use statements
Inspection & Search (2)
- ✅ find: Locate AST node definitions (structs, enums, functions)
- ✅ inspect: List and view AST nodes (struct literals, etc.) with glob support
State & Utilities (5)
- ✅ history: View past operations
- ✅ revert: Undo specific changes
- ✅ clean: Remove old state
- ✅ batch: Run multiple operations from JSON
- ✅
--format diff: Generate git-compatible patches
Pattern-Based Filtering (NEW!)
- ✅
--where: Filter targets by traits or attributes- Supported on:
add-struct-field,update-struct-field,remove-struct-field,add-enum-variant,update-enum-variant,remove-enum-variant,add-derive - Example:
--where "derives_trait:Clone"or--where "derives_trait:Clone,Debug"
- Supported on:
Usage
Glob Pattern Support
All commands now support glob patterns for targeting multiple files:
# Add derives to all structs in src directory
# Add match arms across multiple handler files
# Common glob patterns:
# src/**/*.rs - All .rs files in src and subdirectories
# src/models/*.rs - All .rs files in src/models
# src/**/handler.rs - All handler.rs files anywhere under src
Benefits:
- Perform bulk operations across your codebase
- Target specific directories or file patterns
- Ideal for migrations and refactoring tasks
Pattern-Based Filtering with --where
Filter which structs/enums to modify based on their traits or attributes:
# Add field only to structs that derive Clone
# Add Serialize to all types that already derive Clone OR Debug
# Update field only in Debug-enabled structs
# Remove variant only from enums with Clone
Filter Syntax:
derives_trait:Clone- Matches if type derives Clonederives_trait:Clone,Debug- Matches if type derives Clone OR Debug (OR logic)
Supported Operations:
- All struct operations:
add-struct-field,update-struct-field,remove-struct-field - All enum operations:
add-enum-variant,update-enum-variant,remove-enum-variant - Derive operations:
add-derive
Benefits:
- Selective refactoring: Only modify types that meet specific criteria
- Safe migrations: Add fields only to serializable types, etc.
- Powerful combinations: Combine with glob patterns for precise bulk operations
Struct Operations
Add Field to Struct Definition
# Add field to struct definition only (idempotent - skips if exists)
# With position control
# NEW: Add field to BOTH struct definition AND all struct literals in one command!
# This updates BOTH:
# 1. The struct definition:
# pub struct IRCtx {
# ...
# current_function_frame: Option<Frame>,
# return_type: Option<Type>, ← Added
# }
#
# 2. All struct initialization expressions:
# IRCtx {
# ...
# current_function_frame: None,
# return_type: None, ← Added
# }
Note: The --literal-default flag is optional. When omitted, only the struct definition is updated (original behavior). When provided, it also updates all struct literals with the given default value.
Add Field to Struct Literal Expressions Only
# Add field to ALL struct initialization expressions (idempotent)
# Use this when the field already exists in the struct definition
# This modifies initialization expressions like:
# IRCtx { stack: vec![], current_function_frame: None, ... }
#
# NOT the struct definition:
# pub struct IRCtx { ... }
Update Field
# Change field visibility
# Change field type
Remove Field
Enum Operations
Add Variant
# Add simple variant (idempotent)
# Add variant with data
Update Variant
Remove Variant
Match Arm Operations
Add Match Arm
# Add match arm (idempotent)
# Auto-detect missing variants and add them all
Auto-Detect Feature: The --auto-detect flag analyzes your enum definition and match expressions to automatically add match arms for ALL missing variants. This is perfect for:
- Ensuring exhaustive match coverage after adding new enum variants
- Quickly scaffolding match expressions with placeholder implementations
- Maintaining consistency across multiple match sites
Update Match Arm
Remove Match Arm
Note: Match operations automatically format the modified function using prettyplease to ensure consistent, readable code.
Derive Macros
# Add derive macros (idempotent)
# Works with enums too
Impl Methods
# Add method to impl block
# With position control
Use Statements
# Add use statement (idempotent)
# Position control
Find AST Nodes
Locate definitions (structs, enums, functions) in a single file:
# Find struct definition location
# Find enum definition
# Output (JSON):
# [{
# "line": 10,
# "column": 0,
# "end_line": 15,
# "end_column": 1
# }]
Inspect AST Nodes
List and view AST nodes (struct literals, etc.) across multiple files with glob support:
# List all Shadow struct initializations
# Output:
# // tests/shadow_bold.rs:42:18 - Shadow
# Shadow { offset: Vec2::new(2.0, 2.0), blur: 4.0, color: Color32::BLACK, }
#
# // tests/shadow_test.rs:15:20 - Shadow
# Shadow { offset: Vec2::ZERO, blur: 0.0, color: Color32::WHITE, }
# Get locations only (like grep -n but AST-aware)
# Output:
# src/app.rs:25:18
# src/config.rs:45:12
# src/main.rs:10:21
# Get structured JSON output
# List ALL struct literals (no name filter)
# Find match arms for specific enum variant (better than grep!)
# Output:
# // src/format/print.rs:766:12 - Operator::AssertSome
# Operator::AssertSome => write!(f, "!_"),
#
# // src/eval.rs:45:12 - Operator::AssertSome
# Operator::AssertSome => self.unwrap_or_panic(value),
# Find ALL match arms in a file
# Find enum variant usages (better than grep!)
# Output:
# // src/format/print.rs:763:12 - Operator::PropagateError
# Operator::PropagateError
#
# // src/eval.rs:120:25 - Operator::PropagateError
# Operator::PropagateError
# Find ALL usages of any Operator variant
|
# Find all calls to a specific function
# Output:
# // src/error.rs:42:4 - handle_error
# handle_error()
#
# // src/parser.rs:156:8 - handle_error
# handle_error(err)
# Find all .unwrap() calls (great for auditing!)
# Find all references to a variable/identifier
# Find all usages of a type
# Output:
# // src/lib.rs:15:18 - Vec<String>
# Vec<String>
#
# // src/lib.rs:42:11 - Vec<i32>
# Vec<i32>
Supported Node Types:
struct-literal- Struct initialization expressionsmatch-arm- Match expression armsenum-usage- Enum variant references/usages anywhere in codefunction-call- Function invocationsmethod-call- Method callsidentifier- Any identifier referencetype-ref- Type usages
Output Formats:
snippets(default): Shows file location + formatted code on single linelocations: File:line:column format (great for piping to other tools)json: Structured data with full location info and code snippets
Use Cases:
- Better than grep: Find code without false positives from comments/strings
- Multi-file search: Use glob patterns to search across many files
- Extract code chunks: Get full struct literal/match arm/path content, not just the first line
- Prepare for refactoring: Inspect before bulk modifications
- Find enum usage: Locate all places where a specific enum variant is used (matches, returns, comparisons, etc.)
- Track variant usage: See everywhere
Status::ActiveorOperator::Errorappears in your codebase - Audit function calls: Find all calls to specific functions (e.g.,
handle_error,format_operator) - Audit method calls: Find all
.unwrap(),.clone(), or.to_string()calls - Track identifiers: Find all references to variables, constants, or parameters
- Type usage analysis: See where types like
Vec,Option, orResultare used
Batch Operations
Create a JSON file with multiple operations:
Run batch:
Diff Output
Generate git-compatible patches for review before applying:
# Generate diff for review
# Output:
# --- src/user.rs
# +++ src/user.rs
# @@ -1,5 +1,6 @@
# pub struct User {
# id: u64,
# + age: u32,
# name: String,
# }
# Save to patch file
# Apply with git
# Or apply AND show diff
Perfect for AI-generated changes that need human review!
State Storage and Revert System
rs-hack includes a powerful state tracking and revert system that allows you to safely experiment with changes and undo them if needed. This is especially useful for AI agents that want to try different approaches.
How It Works
Every time you run a command with --apply, rs-hack:
- Generates a unique run ID (7 characters, like git)
- Backs up only the AST nodes being modified (not entire files)
- Computes checksums for integrity verification
- Stores operation metadata for auditing
Commands
View History
# Show last 10 runs
# Show last 50 runs
# Example output:
# Recent runs (showing up to 10):
#
# a05a626 2025-11-01 18:45 AddStructField 1 file [can revert]
# def456a 2025-11-01 09:15 add-derive 1 file [can revert]
# ghi789b 2025-10-31 16:45 add-match-arm 2 files [reverted]
Revert Changes
# Revert a specific run
# Force revert even if files have changed since
Clean Old State
# Clean runs older than 30 days (default)
# Keep only last 7 days
State Directory
rs-hack stores state in different locations based on your needs:
Priority order:
- Custom directory (via
RS_HACK_STATE_DIRenvironment variable) - highest priority - Local state (via
--local-stateflag) - uses./.rs-hackin current directory - Global default - uses system data directory (
~/.rs-hackon Unix-like systems)
Using Environment Variable (Recommended for Testing)
# Set custom state directory
# View history from custom state
RS_HACK_STATE_DIR=/tmp/my-test-state
# Revert using custom state
RS_HACK_STATE_DIR=/tmp/my-test-state
# Perfect for CI/CD or isolated testing
RS_HACK_STATE_DIR=/path/to/ci/state
Note: The environment variable takes precedence over --local-state, allowing you to override state location for testing without changing commands.
Using Local State Flag
# Use ./.rs-hack directory for state storage
# View history from local state
# Revert using local state
Using Global State (Default)
# No flag needed - uses ~/.rs-hack by default
Safety Features
- Hash Verification: Ensures files haven't changed before reverting (unless
--force) - Atomic Operations: Uses temp files and atomic renames
- AST Node Backups: Stores only modified nodes (85-95% space savings)
- Auto-Cleanup: Removes old backups with
cleancommand - Idempotent: Safe to run operations multiple times
AI Agent Workflow Example
# AI tries adding a field
# Output: Run ID: a05a626
# AI runs tests - they fail!
# AI reverts the change
# Output: ✓ Run a05a626 reverted successfully
# AI tries a different approach
# Output: Run ID: b12c789
# Tests pass!
Use Cases
- Experimentation: Try changes and easily revert if they don't work
- Multi-step Migrations: Revert to any checkpoint if something breaks
- Debugging: Understand what changed when tests start failing
- Safety Net: Confidence to let AI agents make changes automatically
Storage Format
~/.rs-hack/
runs.json # Index of all runs
a05a626.json # Metadata for run a05a626
a05a626/ # Backup directory
node_0.json # Modified struct (AST node only)
node_1.json # Modified enum (AST node only)
Note: Only modified AST nodes are backed up (not entire files), resulting in 85-95% space savings.
AI Agent Integration
Example: Claude Code using rs-hack
# Claude reads the task
# Claude executes
Architecture
Core Components
- Parser (
syncrate): Parses Rust → AST - Editor: Manipulates AST and tracks byte positions
- Operations: Type-safe operation definitions
- CLI: User-friendly interface
Key Design Decisions
- Preserves formatting: Uses
prettypleasefor clean output - Idempotent: Running twice doesn't duplicate changes
- Fail-fast: Returns errors clearly, doesn't corrupt code
- Dry-run default: Must explicitly
--applyto modify files
Real-World Example: rs-hack vs perl/sed
The Problem: Perl Commands Are Dangerously Ambiguous
Consider this perl command that was used to add a field to struct initialization:
This command is DANGEROUSLY AMBIGUOUS because it matches text patterns without understanding Rust syntax:
What It Could Match (All Have the Same Text Pattern!)
// ❌ Struct DEFINITION - probably NOT what you want
// ✅ Struct LITERAL - what you actually want
let ctx = IRCtx ;
// ❌ COMMENT - corrupts your code!
// Example: current_function_frame: None, // ← Matches! Corrupts comment
// ❌ STRING - corrupts your string literal!
let s = "current_function_frame: None,"; // ← Matches! Corrupts string
The perl command can't distinguish between these! It will modify ALL of them, likely corrupting your code.
✅ The Explicit, Safe Way (rs-hack)
rs-hack provides separate, explicit operations for each use case. You can update both in one command or separately:
Option 1: Update BOTH Definition and Literals (One Command!)
# NEW: Do BOTH in one command with --literal-default
This modifies BOTH the struct definition AND all struct literals:
// ✅ Struct definition updated
// ✅ All struct literals updated
let ctx = IRCtx ;
Option 2: Separate Operations (When You Need More Control)
Step 1: Modify Struct Definitions Only
Step 2: Modify Struct Literal Expressions Only
Benefits of Explicit Operations:
- ✅ Explicit Intent: Command name tells you exactly what will be modified
- ✅ AST-Aware: Only modifies actual Rust syntax nodes
- ✅ Never Corrupts: Won't touch comments, strings, or unrelated code
- ✅ Idempotent: Safe to run multiple times
- ✅ Position Control: Precise placement of new fields
- ✅ Glob Patterns: No manual file listing
- ✅ Format-Independent: Works regardless of whitespace/formatting
- ✅ Dry-Run Default: Preview changes before applying
vs Perl/Sed Problems:
- ❌ Ambiguous: Can't distinguish struct definitions from literals from comments
- ❌ Text-Based: Breaks on formatting changes
- ❌ Not Idempotent: Running twice duplicates fields
- ❌ No Validation: Can corrupt code on partial matches
- ❌ Manual Files: Need to list every file explicitly
- ❌ No Preview: Modifies files immediately
What rs-hack Does Behind the Scenes
- Parse each file into an AST using
syn - Traverse the AST to find struct definitions OR struct literal expressions (depending on operation)
- Validate the target exists and check if the field already exists (idempotent)
- Modify the AST by inserting the new field in the correct position
- Format the result with
prettyplease - Write back atomically
Safe, semantic, and correct every time. 🦀
Comparison with Alternatives
| Tool | AST-Aware | Rust-Specific | AI-Friendly | Batch Ops | Idempotent |
|---|---|---|---|---|---|
sed |
❌ | ❌ | ⚠️ | ✅ | ❌ |
rust-analyzer |
✅ | ✅ | ❌ | ❌ | ⚠️ |
syn + custom |
✅ | ✅ | ⚠️ | ⚠️ | ⚠️ |
| rs-hack | ✅ | ✅ | ✅ | ✅ | ✅ |
Development
# Build
# Run tests
# Install locally
Testing
# Unit tests
# Integration tests
# Test individual operations
Publishing
See PUBLISHING_GUIDE.md for instructions on publishing to crates.io.
Features by Version
v0.4.0 - Pattern-Based Filtering & Inspection (Current)
--wherefilter: Pattern-based filtering for selective refactoring--where "derives_trait:Clone"- Filter by derived traits- OR logic support:
--where "derives_trait:Clone,Debug" - Works on all struct/enum operations +
add-derive
inspectcommand: AST-aware search and inspection- List struct literals, match arms, and enum variant usages across files
- Find all match arms handling a specific enum variant
- Find all places where an enum variant is referenced (complete grep replacement!)
- Three output formats:
snippets,locations,json - Glob pattern support for multi-file inspection
- Better than grep: no false positives, extracts full code chunks
- Enhanced
find: Improved documentation for locating definitions
v0.3.0 - State Storage, Revert & Diff Output
- State tracking: Every operation recorded with unique run ID
- Revert system: Undo changes with
rs-hack revert <run-id> - Diff output: Generate git-compatible patches with
--format diff - AST node backups: Stores only modified nodes (85-95% space savings)
- Configurable state: Use
RS_HACK_STATE_DIRenvironment variable - Commands:
history,revert,clean
v0.2.0 - Glob Patterns & Auto-Detect
- Glob patterns: Target multiple files with
"src/**/*.rs" - Auto-detect match arms: Find and add all missing enum variants
- Literal-default: Update struct definitions AND literals together
Contributing
PRs welcome! Future ideas:
- Support for generics in impl blocks
- Attribute macro operations
- Function signature modification
- Type alias operations
License
MIT OR Apache-2.0
Credits
Built for AI agents to stop using sed on Rust code. 🦀
Created by Leif Shackelford (@1e1f)