Skip to content

Refactoring Engine

Mo Abualruz edited this page Dec 5, 2025 · 1 revision

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

use ricecoder_refactoring::{
    RefactoringEngine, Refactoring, RefactoringType, RefactoringTarget,
    RefactoringOptions, ConfigManager,
};
use std::path::PathBuf;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 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:

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:

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:

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 for detailed configuration guide.

Architecture

See Refactoring-Architecture.md for architecture documentation.

Refactoring Patterns

See Refactoring-Patterns.md for pattern guide.

Safety Features

Automatic Backups

The engine creates automatic backups before applying changes:

let backup = engine.create_backup(&refactoring).await?;
println!("Backup created at: {}", backup.path.display());

Validation

Comprehensive validation ensures code integrity:

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:

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<T> with explicit error types:

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


Last updated: December 5, 2025

Clone this wiki locally