Skip to main content

airl_ir/
graph.rs

1use crate::module::Module;
2use thiserror::Error;
3
4/// Errors that can occur when working with the IR graph.
5#[derive(Debug, Error)]
6pub enum IRGraphError {
7    /// JSON (de)serialization failed.
8    #[error("JSON serialization error: {0}")]
9    SerializeError(#[from] serde_json::Error),
10    /// The IR structure is invalid (e.g. missing required fields).
11    #[error("Invalid IR: {0}")]
12    InvalidIR(String),
13}
14
15/// A container for the AIRL IR module graph.
16///
17/// Provides convenience methods for loading and saving IR modules.
18#[derive(Clone, Debug)]
19pub struct IRGraph {
20    /// The contained module.
21    pub module: Module,
22}
23
24impl IRGraph {
25    /// Parse an IR graph from a JSON string.
26    pub fn from_json(json: &str) -> Result<Self, IRGraphError> {
27        let module: Module = serde_json::from_str(json)?;
28        Ok(IRGraph { module })
29    }
30
31    /// Serialize the IR graph to a pretty-printed JSON string.
32    pub fn to_json(&self) -> Result<String, IRGraphError> {
33        let json = serde_json::to_string_pretty(&self.module)?;
34        Ok(json)
35    }
36
37    /// Serialize the IR graph to a compact JSON string.
38    pub fn to_json_compact(&self) -> Result<String, IRGraphError> {
39        let json = serde_json::to_string(&self.module)?;
40        Ok(json)
41    }
42
43    /// Get a reference to the underlying module.
44    pub fn module(&self) -> &Module {
45        &self.module
46    }
47
48    /// Get a mutable reference to the underlying module.
49    pub fn module_mut(&mut self) -> &mut Module {
50        &mut self.module
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_graph_from_json() {
60        let json = r#"{
61            "format_version": "0.1.0",
62            "module": {
63                "id": "mod_test",
64                "name": "test",
65                "metadata": {
66                    "version": "1.0.0",
67                    "description": "Test",
68                    "author": "test",
69                    "created_at": "2026-01-01T00:00:00Z"
70                },
71                "imports": [],
72                "exports": [],
73                "types": [],
74                "traits": [],
75                "impls": [],
76                "constants": [],
77                "functions": []
78            }
79        }"#;
80
81        let graph = IRGraph::from_json(json).unwrap();
82        assert_eq!(graph.module().name(), "test");
83
84        // Roundtrip
85        let json_out = graph.to_json().unwrap();
86        let graph2 = IRGraph::from_json(&json_out).unwrap();
87        assert_eq!(graph.module, graph2.module);
88    }
89}