Skip to main content

clm_rust_core/
parser.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4// Unified Spatiotemporal FND Domain Models (Sprint 190)
5pub use crate::domain::{
6    BailVerdict, BooleanPCard, CordisCoeffects, DynamicPCard, InvariantPhase,
7    MCard as DomainMCard, MCardPayload, PCardDefinition, PrimitivePCard,
8};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct MCard {
12    pub hash: Option<String>,
13    pub content: Value,
14    pub g_time: Option<u64>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct PCard {
19    pub abstract_spec: Value,
20    pub concrete_impl: Value,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub balanced_exp: Option<Value>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct VCard {
27    pub v_pre: Option<Value>,
28    pub p_card: Option<Value>,
29    pub v_post: Option<Value>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct AMCardSignature {
34    pub name: String,
35    pub inputs: Value,
36    pub outputs: Value,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct AMCardInvariants {
41    #[serde(default)]
42    pub preconditions: Vec<String>,
43    #[serde(default)]
44    pub postconditions: Vec<String>,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct AMCard {
49    #[serde(default)]
50    pub context: Option<String>,
51    #[serde(default)]
52    pub goal: Option<String>,
53    pub signature: AMCardSignature,
54    pub invariants: AMCardInvariants,
55}
56
57/// Parses a CLM manifest (YAML or JSON) into a generic JSON Value representing the AST.
58/// Bypasses yq and compiles directly to memory-mapped models.
59pub fn parse_manifest(file_path: &str) -> Result<Value, String> {
60    crate::yaml::parse_to_mcards(file_path)
61        .map_err(|e| e.to_string())
62        .and_then(|json_str| {
63            serde_json::from_str(&json_str)
64                .map_err(|e| format!("Failed to deserialize normalized AST: {}", e))
65        })
66}
67
68/// Attempts to parse a manifest directly into a Token Triad model (MCard, PCard, VCard).
69pub fn parse_mcard(file_path: &str) -> Result<MCard, String> {
70    let ast = parse_manifest(file_path)?;
71    serde_json::from_value(ast)
72        .map_err(|e| format!("Failed to cast AST to MCard: {}", e))
73}
74
75/// Validates that a parsed JSON AST conforms to the formal A-MCard schema requirements.
76pub fn validate_a_mcard_schema(val: &Value) -> Result<(), String> {
77    let root = if let Some(clm) = val.get("clm") { clm } else { val };
78    
79    let abstract_spec = if let Some(spec) = root.get("abstract_spec") {
80        spec
81    } else {
82        if root.get("signature").is_some() {
83            root
84        } else {
85            return Err("Missing 'abstract_spec' block or direct 'signature' block".to_string());
86        }
87    };
88
89    let signature = abstract_spec.get("signature")
90        .ok_or_else(|| "Missing 'signature' block".to_string())?;
91    
92    let _name = signature.get("name")
93        .and_then(|v| v.as_str())
94        .ok_or_else(|| "signature block is missing string 'name'".to_string())?;
95        
96    let _inputs = signature.get("inputs")
97        .ok_or_else(|| "signature block is missing 'inputs'".to_string())?;
98
99    let _outputs = signature.get("outputs")
100        .ok_or_else(|| "signature block is missing 'outputs'".to_string())?;
101
102    let invariants = abstract_spec.get("invariants")
103        .ok_or_else(|| "Missing 'invariants' block".to_string())?;
104
105    if let Some(pre) = invariants.get("preconditions") {
106        if !pre.is_array() {
107            return Err("invariants.preconditions must be an array of strings".to_string());
108        }
109        for item in pre.as_array().unwrap() {
110            if !item.is_string() {
111                return Err("invariants.preconditions items must be strings".to_string());
112            }
113        }
114    }
115
116    if let Some(post) = invariants.get("postconditions") {
117        if !post.is_array() {
118            return Err("invariants.postconditions must be an array of strings".to_string());
119        }
120        for item in post.as_array().unwrap() {
121            if !item.is_string() {
122                return Err("invariants.postconditions items must be strings".to_string());
123            }
124        }
125    }
126
127    Ok(())
128}
129
130/// Parses a manifest and validates it against the A-MCard schema, returning the casted AMCard.
131pub fn parse_a_mcard(file_path: &str) -> Result<AMCard, String> {
132    let ast = parse_manifest(file_path)?;
133    validate_a_mcard_schema(&ast)?;
134    
135    let root = if let Some(clm) = ast.get("clm") { clm } else { &ast };
136    let abstract_spec = root.get("abstract_spec").unwrap_or(root);
137    
138    serde_json::from_value(abstract_spec.clone())
139        .map_err(|e| format!("Failed to cast AST to AMCard: {}", e))
140}