Skip to content

Rust-Based Preprocessor Design

Performance Expectations

Based on the code sample using ruff-python-parser, a Rust implementation would likely achieve:

Expected Performance Gains

  1. Parsing Speed: 10-50x faster than Python's ast.parse
  2. Ruff's parser is highly optimized
  3. Zero-copy parsing where possible
  4. No Python object overhead

  5. AST Traversal: 5-20x faster

  6. Direct memory access
  7. No Python function call overhead
  8. Efficient visitor pattern

  9. Code Generation: 10-30x faster

  10. Direct string building
  11. No AST unparsing needed
  12. Efficient memory allocation

Overall Expected Performance

Given our current optimized Python implementation processes ~700 lines/ms, a Rust implementation could potentially achieve:

  • 10,000-20,000 lines/ms for simple patterns
  • 5,000-10,000 lines/ms for complex patterns
  • Sub-millisecond processing for most real-world modules

Proposed Rust Implementation

use std::fmt::Write;
use ruff_python_ast::{
    statement_visitor::{walk_stmt, StatementVisitor},
    Expr, Mod, Stmt, StmtAssign, StmtAnnAssign,
};
use ruff_python_parser::{parse, Mode};

pub struct PreprocessorTransformer {
    output: String,
    source_lines: Vec<String>,
    modifications_made: bool,
    import_added: bool,
}

impl PreprocessorTransformer {
    pub fn new(source: &str) -> Self {
        Self {
            output: String::with_capacity(source.len() * 2),
            source_lines: source.lines().map(String::from).collect(),
            modifications_made: false,
            import_added: false,
        }
    }

    pub fn transform(mut self, source: &str) -> Result<String, Box<dyn std::error::Error>> {
        // Parse the source
        let parsed = parse(source, Mode::Module)?;
        let ast = parsed.syntax();

        // Visit and transform
        match ast {
            Mod::Module(module) => {
                self.visit_body(&module.body);
            }
            Mod::Expression(_) => return Ok(source.to_string()),
        }

        // Add import if needed
        if self.modifications_made && !self.import_added {
            self.add_import();
        }

        Ok(self.output)
    }

    fn add_import(&mut self) {
        // Find the right position and insert import
        let import_line = "from nf.codec.autoid.preprocessor import _nf_wrap_with_varname";
        // Implementation details...
    }

    fn is_construct_call(expr: &Expr) -> bool {
        match expr {
            Expr::Call(call) => {
                match &call.func.as_ref() {
                    Expr::Name(name) => name.id.chars().next().map_or(false, |c| c.is_uppercase()),
                    Expr::Attribute(attr) => attr.attr.chars().next().map_or(false, |c| c.is_uppercase()),
                    _ => false,
                }
            }
            _ => false,
        }
    }

    fn wrap_with_varname(&mut self, var_name: &str, call_expr: &Expr) -> String {
        // Generate wrapped call
        format!("_nf_wrap_with_varname({}, '{}'", 
                self.expr_to_string(call_expr), var_name)
    }

    fn expr_to_string(&self, expr: &Expr) -> String {
        // Convert expression back to string
        // This would be custom implementation, not unparsing
        todo!()
    }
}

impl StatementVisitor<'_> for PreprocessorTransformer {
    fn visit_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            // Simple assignment: x = Class()
            Stmt::Assign(StmtAssign { targets, value, .. }) => {
                if targets.len() == 1 && Self::is_construct_call(value) {
                    if let Expr::Name(name) = &targets[0] {
                        let wrapped = self.wrap_with_varname(&name.id, value);
                        writeln!(&mut self.output, "{} = {}", name.id, wrapped).unwrap();
                        self.modifications_made = true;
                        return;
                    }
                }
            }

            // Annotated assignment: x: Type = Class()
            Stmt::AnnAssign(StmtAnnAssign { target, value: Some(value), .. }) => {
                if Self::is_construct_call(value) {
                    if let Expr::Name(name) = target.as_ref() {
                        let wrapped = self.wrap_with_varname(&name.id, value);
                        // Preserve annotation
                        writeln!(&mut self.output, "{}: {} = {}", 
                                name.id, self.expr_to_string(annotation), wrapped).unwrap();
                        self.modifications_made = true;
                        return;
                    }
                }
            }

            _ => {}
        }

        // Default: copy the original line
        // In real implementation, would track line numbers
        walk_stmt(self, stmt);
    }
}

Integration Strategy

1. Python Extension Module

Create a Python extension using PyO3:

use pyo3::prelude::*;

#[pyfunction]
fn preprocess_rust(source: &str) -> PyResult<String> {
    let transformer = PreprocessorTransformer::new(source);
    transformer.transform(source)
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))
}

#[pymodule]
fn rust_preprocessor(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(preprocess_rust, m)?)?;
    Ok(())
}

2. Python Integration

def preprocess(source: str) -> str:
    """Preprocess with Rust if available, fall back to Python."""
    try:
        # Try Rust implementation first
        import rust_preprocessor

        return rust_preprocessor.preprocess_rust(source)
    except ImportError:
        # Fall back to Python optimized version
        from nf.codec.autoid.preprocessor import preprocess_optimized

        return preprocess_optimized(source)

Performance Comparison Estimate

Implementation Speed (lines/ms) 1000-line module 10,000-line module
Original AST ~35 ~30ms ~300ms
Optimized Regex ~700 ~1.4ms ~14ms
Rust (est.) ~15,000 ~0.07ms ~0.7ms

Advantages of Rust Implementation

  1. Blazing Fast: 20-50x faster than optimized Python
  2. Memory Efficient: Zero-copy parsing, minimal allocations
  3. Reliable: Type-safe, no runtime errors
  4. Maintainable: Ruff's AST is well-documented and stable

Challenges

  1. Build Complexity: Requires Rust toolchain
  2. Distribution: Need to build wheels for different platforms
  3. Development Time: More complex than Python implementation
  4. Debugging: Harder to debug than Python code

Recommendation

For netherframe's use case:

  1. Current optimized Python (700 lines/ms) is probably sufficient for most users
  2. Rust implementation would be valuable for:
  3. Very large codebases (>10,000 lines per module)
  4. CI/CD environments with many modules
  5. Users who want minimal import overhead

The 18x improvement from optimization already makes the preprocessor very fast. The additional 20x from Rust would make it essentially "free" in terms of performance impact.