use crate::recompiler::error::RecompilerError;
use anyhow::Result;
pub struct CodeValidator;
impl CodeValidator {
#[inline] #[must_use] pub fn validate_rust_code(code: &str) -> Result<()> {
if !code.contains("fn ") {
return Err(RecompilerError::ValidationError(
"Generated code must contain at least one function definition".to_string()
).into());
}
let open_braces: usize = code.matches('{').count();
let close_braces: usize = code.matches('}').count();
if open_braces != close_braces {
return Err(RecompilerError::ValidationError(
format!(
"Unbalanced braces in generated code: {} open, {} close. This indicates a syntax error in code generation.",
open_braces, close_braces
)
).into());
}
let open_parens: usize = code.matches('(').count();
let close_parens: usize = code.matches(')').count();
if open_parens != close_parens {
return Err(RecompilerError::ValidationError(
format!(
"Unbalanced parentheses in generated code: {} open, {} close. This indicates a syntax error in code generation.",
open_parens, close_parens
)
).into());
}
let open_brackets: usize = code.matches('[').count();
let close_brackets: usize = code.matches(']').count();
if open_brackets != close_brackets {
return Err(RecompilerError::ValidationError(
format!(
"Unbalanced brackets in generated code: {} open, {} close. This indicates a syntax error in code generation.",
open_brackets, close_brackets
)
).into());
}
let string_literal_count: usize = code.matches('"').count();
if string_literal_count % 2 != 0 {
log::warn!("Possible unclosed string literal in generated code (odd number of quotes)");
}
let fn_count: usize = code.matches("pub fn ").count() + code.matches("fn ").count();
let return_count: usize = code.matches("return").count() + code.matches("Ok(").count();
if fn_count > 0 && return_count == 0 {
log::warn!("Generated code has functions but no return statements - this may indicate incomplete code generation");
}
if !code.contains("use ") && !code.contains("CpuContext") {
log::warn!("Generated code may be missing required imports (CpuContext, MemoryManager, etc.)");
}
log::debug!("Code validation passed: {} functions, {} braces, {} parentheses", fn_count, open_braces, open_parens);
Ok(())
}
#[inline] #[must_use] pub fn validate_function(function_code: &str) -> Result<()> {
Self::validate_rust_code(function_code)
}
}