Skip to main content

decy_debugger/
visualize_hir.rs

1//! HIR visualization for debugging
2//!
3//! Display High-level IR conversion from C AST
4
5use anyhow::{Context, Result};
6use colored::Colorize;
7use decy_hir::HirFunction;
8use decy_parser::CParser;
9use std::fs;
10use std::path::Path;
11
12/// Visualize HIR conversion from C source
13///
14/// # Errors
15///
16/// Returns an error if the file cannot be read, parsed, or converted to HIR
17pub fn visualize_hir(file_path: &Path, use_colors: bool) -> Result<String> {
18    // Read and parse source
19    let source = fs::read_to_string(file_path)
20        .with_context(|| format!("Failed to read file: {}", file_path.display()))?;
21
22    let parser = CParser::new()?;
23    let ast = parser.parse(&source).context("Failed to parse C source")?;
24
25    // Convert to HIR
26    let hir_functions: Vec<HirFunction> =
27        ast.functions().iter().map(HirFunction::from_ast_function).collect();
28
29    // Format output
30    let mut output = String::new();
31
32    // Header
33    if use_colors {
34        output.push_str(&format!("{}\n", "╔═══ HIR Visualization ═══╗".green().bold()));
35    } else {
36        output.push_str("╔═══ HIR Visualization ═══╗\n");
37    }
38    output.push('\n');
39
40    // File info
41    output.push_str(&format!("File: {}\n", file_path.display()));
42    output.push_str(&format!("HIR Functions: {}\n\n", hir_functions.len()));
43
44    // Display each HIR function
45    for hir_func in &hir_functions {
46        if use_colors {
47            output.push_str(&format!("{}:\n", hir_func.name().bright_cyan().bold()));
48        } else {
49            output.push_str(&format!("{}:\n", hir_func.name()));
50        }
51
52        output.push_str(&format!("  Return type: {:?}\n", hir_func.return_type()));
53        output.push_str(&format!("  Parameters: {}\n", hir_func.parameters().len()));
54
55        // Show parameter details
56        for param in hir_func.parameters() {
57            output.push_str(&format!("    - {} : {:?}\n", param.name(), param.param_type()));
58        }
59
60        output.push_str(&format!("  Body statements: {}\n", hir_func.body().len()));
61        output.push('\n');
62    }
63
64    Ok(output)
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use std::io::Write;
71    use tempfile::NamedTempFile;
72
73    #[test]
74    fn test_visualize_hir_simple() {
75        let mut temp_file = NamedTempFile::new().unwrap();
76        writeln!(temp_file, "int add(int a, int b) {{ return a + b; }}").unwrap();
77
78        let result = visualize_hir(temp_file.path(), false);
79        assert!(result.is_ok());
80
81        let output = result.unwrap();
82        assert!(output.contains("add"));
83        assert!(output.contains("HIR Functions"));
84    }
85}