gcrecomp_core/recompiler/validator.rs
1//! Code Validation
2//!
3//! This module provides validation for generated Rust code to ensure correctness
4//! before writing to output files.
5//!
6//! # Validation Checks
7//! - **Syntax validation**: Basic syntax checks (balanced braces, function definitions)
8//! - **Type validation**: Type correctness (would use rustc or syn crate in full implementation)
9//! - **Semantic validation**: Semantic correctness (would use rustc in full implementation)
10
11use crate::recompiler::error::RecompilerError;
12use anyhow::Result;
13
14/// Code validator for generated Rust code.
15pub struct CodeValidator;
16
17impl CodeValidator {
18 /// Validate generated Rust code.
19 ///
20 /// # Algorithm
21 /// Performs comprehensive syntax validation:
22 /// - Checks for at least one function definition
23 /// - Validates balanced braces, parentheses, and brackets
24 /// - Checks for common syntax errors (unclosed strings, etc.)
25 /// - Validates function signatures
26 /// - (In full implementation) Would use rustc or syn crate for full validation
27 ///
28 /// # Arguments
29 /// * `code` - Generated Rust code string
30 ///
31 /// # Returns
32 /// * `Result<()>` - Success if code is valid, error otherwise
33 ///
34 /// # Errors
35 /// Returns error if code fails validation checks with detailed error messages
36 ///
37 /// # Examples
38 /// ```rust
39 /// CodeValidator::validate_rust_code(&generated_code)?;
40 /// ```
41 #[inline] // May be called frequently
42 #[must_use] // Result should be checked
43 pub fn validate_rust_code(code: &str) -> Result<()> {
44 // Basic syntax validation
45 // In a full implementation, would use rustc or syn crate
46
47 // Check for basic syntax issues
48 if !code.contains("fn ") {
49 return Err(RecompilerError::ValidationError(
50 "Generated code must contain at least one function definition".to_string()
51 ).into());
52 }
53
54 // Check balanced braces
55 let open_braces: usize = code.matches('{').count();
56 let close_braces: usize = code.matches('}').count();
57 if open_braces != close_braces {
58 return Err(RecompilerError::ValidationError(
59 format!(
60 "Unbalanced braces in generated code: {} open, {} close. This indicates a syntax error in code generation.",
61 open_braces, close_braces
62 )
63 ).into());
64 }
65
66 // Check balanced parentheses
67 let open_parens: usize = code.matches('(').count();
68 let close_parens: usize = code.matches(')').count();
69 if open_parens != close_parens {
70 return Err(RecompilerError::ValidationError(
71 format!(
72 "Unbalanced parentheses in generated code: {} open, {} close. This indicates a syntax error in code generation.",
73 open_parens, close_parens
74 )
75 ).into());
76 }
77
78 // Check balanced brackets
79 let open_brackets: usize = code.matches('[').count();
80 let close_brackets: usize = code.matches(']').count();
81 if open_brackets != close_brackets {
82 return Err(RecompilerError::ValidationError(
83 format!(
84 "Unbalanced brackets in generated code: {} open, {} close. This indicates a syntax error in code generation.",
85 open_brackets, close_brackets
86 )
87 ).into());
88 }
89
90 // Check for common syntax errors
91 // Unclosed strings (basic check - doesn't handle escaped quotes)
92 let string_literal_count: usize = code.matches('"').count();
93 if string_literal_count % 2 != 0 {
94 log::warn!("Possible unclosed string literal in generated code (odd number of quotes)");
95 }
96
97 // Check that all functions have return types or statements
98 let fn_count: usize = code.matches("pub fn ").count() + code.matches("fn ").count();
99 let return_count: usize = code.matches("return").count() + code.matches("Ok(").count();
100 if fn_count > 0 && return_count == 0 {
101 log::warn!("Generated code has functions but no return statements - this may indicate incomplete code generation");
102 }
103
104 // Check for required imports
105 if !code.contains("use ") && !code.contains("CpuContext") {
106 log::warn!("Generated code may be missing required imports (CpuContext, MemoryManager, etc.)");
107 }
108
109 log::debug!("Code validation passed: {} functions, {} braces, {} parentheses", fn_count, open_braces, open_parens);
110
111 Ok(())
112 }
113
114 /// Validate a single function's code.
115 ///
116 /// # Arguments
117 /// * `function_code` - Generated function code string
118 ///
119 /// # Returns
120 /// `Result<()>` - Success if function code is valid, error otherwise
121 ///
122 /// # Examples
123 /// ```rust
124 /// CodeValidator::validate_function(&function_code)?;
125 /// ```
126 #[inline] // Simple wrapper
127 #[must_use] // Result should be checked
128 pub fn validate_function(function_code: &str) -> Result<()> {
129 Self::validate_rust_code(function_code)
130 }
131}