Skip to main content

hydro_lang/viz/
debug.rs

1//! File saving utilities for Hydro IR graph visualization.
2
3use std::io::Result;
4
5use super::render::{
6    HydroWriteConfig, render_hydro_ir_dot, render_hydro_ir_json, render_hydro_ir_mermaid,
7};
8use crate::compile::ir::HydroRoot;
9
10fn render_with_config<F>(
11    roots: &[HydroRoot],
12    config: Option<HydroWriteConfig>,
13    renderer: F,
14) -> String
15where
16    F: Fn(&[HydroRoot], HydroWriteConfig<'_>) -> String,
17{
18    renderer(roots, config.unwrap_or_default())
19}
20
21/// Saves Hydro IR roots as a Mermaid diagram file.
22pub fn save_mermaid(
23    roots: &[HydroRoot],
24    filename: Option<&str>,
25    config: Option<HydroWriteConfig>,
26) -> Result<std::path::PathBuf> {
27    let content = render_with_config(roots, config, render_hydro_ir_mermaid);
28    save_to_file(content, filename, "hydro_graph.mmd")
29}
30
31/// Saves Hydro IR roots as a DOT/Graphviz file.
32pub fn save_dot(
33    roots: &[HydroRoot],
34    filename: Option<&str>,
35    config: Option<HydroWriteConfig>,
36) -> Result<std::path::PathBuf> {
37    let content = render_with_config(roots, config, render_hydro_ir_dot);
38    save_to_file(content, filename, "hydro_graph.dot")
39}
40
41/// Saves Hydro IR roots as a JSON file.
42pub fn save_json(
43    roots: &[HydroRoot],
44    filename: Option<&str>,
45    config: Option<HydroWriteConfig>,
46) -> Result<std::path::PathBuf> {
47    let content = render_with_config(roots, config, render_hydro_ir_json);
48    save_to_file(content, filename, "hydro_graph.json")
49}
50
51fn save_to_file(
52    content: String,
53    filename: Option<&str>,
54    default_name: &str,
55) -> Result<std::path::PathBuf> {
56    let path = std::path::PathBuf::from(filename.unwrap_or(default_name));
57    std::fs::write(&path, content)?;
58    Ok(path)
59}