# Refactoring Engine **Status**: ✅ Complete **Phase**: Phase 2 (Post-MVP) **Last Updated**: December 5, 2025 --- ## Overview The RiceCoder Refactoring Engine provides safe, automated code refactoring with comprehensive impact analysis and rollback capabilities. It enables developers to make systematic code changes with full understanding of dependencies and automatic safety checks. ## Key Features - **Safe Refactoring**: Automatic backups and rollback on failure - **Impact Analysis**: Understand scope and risk of changes - **Preview Mode**: See changes before applying them - **Configuration-Driven**: Language-specific rules via configuration files - **Multi-Language Support**: Rust, TypeScript, Python, and generic fallback - **Validation**: Comprehensive safety checks before and after refactoring - **Reusable Patterns**: Store and apply refactoring patterns across projects ## Supported Refactoring Types - **Rename**: Rename symbols (functions, variables, types, etc.) - **Extract**: Extract code into new functions/methods - **Inline**: Inline functions or variables - **Move**: Move symbols to different locations - **ChangeSignature**: Modify function signatures - **RemoveUnused**: Remove unused code - **Simplify**: Simplify code structures ## How to Use ### Basic Refactoring ```rust use ricecoder_refactoring::{ RefactoringEngine, Refactoring, RefactoringType, RefactoringTarget, RefactoringOptions, ConfigManager, }; use std::path::PathBuf; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { // Create configuration manager let config_manager = Arc::new(ConfigManager::new()); // Create refactoring engine let engine = RefactoringEngine::new(config_manager); // Create a refactoring let refactoring = Refactoring { id: "rename-function".to_string(), refactoring_type: RefactoringType::Rename, target: RefactoringTarget { file: PathBuf::from("src/main.rs"), symbol: "old_name".to_string(), range: None, }, options: RefactoringOptions::default(), }; // Preview the refactoring let preview = engine.preview(&refactoring).await?; println!("Impact: {:?}", preview.impact); // Execute the refactoring let result = engine.execute(&refactoring).await?; println!("Success: {}", result.success); Ok(()) } ``` ### Impact Analysis Before applying a refactoring, analyze its impact: ```rust let impact = engine.analyze_impact(&refactoring).await?; println!("Affected files: {}", impact.affected_files.len()); println!("Risk level: {:?}", impact.risk_level); println!("Estimated effort: {:?}", impact.estimated_effort); ``` ### Preview Changes See what changes will be made: ```rust let preview = engine.preview(&refactoring).await?; for hunk in &preview.diff.hunks { println!("File: {}", hunk.file); println!("Changes:\n{}", hunk.content); } ``` ### Safe Execution with Rollback The engine automatically handles backups and rollback: ```rust let result = engine.execute(&refactoring).await?; if result.success { println!("Refactoring applied successfully"); } else { println!("Refactoring failed and was rolled back"); } ``` ## Configuration See [Refactoring-Configuration.md](./Refactoring-Configuration.md) for detailed configuration guide. ## Architecture See [Refactoring-Architecture.md](./Refactoring-Architecture.md) for architecture documentation. ## Refactoring Patterns See [Refactoring-Patterns.md](./Refactoring-Patterns.md) for pattern guide. ## Safety Features ### Automatic Backups The engine creates automatic backups before applying changes: ```rust let backup = engine.create_backup(&refactoring).await?; println!("Backup created at: {}", backup.path.display()); ``` ### Validation Comprehensive validation ensures code integrity: ```rust let validation = engine.validate(&refactoring).await?; if validation.is_valid { println!("Refactoring is safe to apply"); } else { println!("Validation errors: {:?}", validation.errors); } ``` ### Rollback Automatic rollback on failure: ```rust let result = engine.execute(&refactoring).await?; if !result.success { engine.rollback(&result.backup_info).await?; println!("Refactoring rolled back"); } ``` ## Error Handling All operations return `Result` with explicit error types: ```rust match engine.execute(&refactoring).await { Ok(result) => println!("Success: {}", result.success), Err(e) => eprintln!("Error: {}", e), } ``` ## Performance - Configuration loading: < 100ms - Impact analysis: < 2s for typical projects - Preview generation: < 1s - Provider lookup: < 50ms ## Troubleshooting ### Refactoring Failed 1. Check the error message for details 2. Review the impact analysis to understand scope 3. Verify configuration is correct 4. Check that the target symbol exists ### Rollback Issues 1. Verify backup files exist 2. Check file permissions 3. Ensure sufficient disk space 4. Review rollback logs ### Performance Issues 1. Profile the operation to identify bottlenecks 2. Check configuration for unnecessary rules 3. Consider breaking large refactorings into smaller ones 4. Verify system resources are available ## See Also - [Refactoring-Configuration.md](./Refactoring-Configuration.md) - Configuration guide - [Refactoring-Architecture.md](./Refactoring-Architecture.md) - Architecture documentation - [Refactoring-Patterns.md](./Refactoring-Patterns.md) - Pattern guide - [API-Reference.md](./API-Reference.md) - API documentation --- *Last updated: December 5, 2025*