1use crate::module::Module;
2use thiserror::Error;
3
4#[derive(Debug, Error)]
6pub enum IRGraphError {
7 #[error("JSON serialization error: {0}")]
9 SerializeError(#[from] serde_json::Error),
10 #[error("Invalid IR: {0}")]
12 InvalidIR(String),
13}
14
15#[derive(Clone, Debug)]
19pub struct IRGraph {
20 pub module: Module,
22}
23
24impl IRGraph {
25 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 pub fn to_json(&self) -> Result<String, IRGraphError> {
33 let json = serde_json::to_string_pretty(&self.module)?;
34 Ok(json)
35 }
36
37 pub fn to_json_compact(&self) -> Result<String, IRGraphError> {
39 let json = serde_json::to_string(&self.module)?;
40 Ok(json)
41 }
42
43 pub fn module(&self) -> &Module {
45 &self.module
46 }
47
48 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 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}