Skip to main content

intent_render/
format.rs

1//! Format a parsed intent specification back to canonical `.intent` source.
2//!
3//! Parses then pretty-prints with consistent indentation and spacing.
4
5use intent_parser::ast;
6
7use crate::format_type;
8
9/// Format an AST [`File`] back to canonical `.intent` source.
10pub fn format(file: &ast::File) -> String {
11    let mut out = String::new();
12    out.push_str(&format!("module {}\n", file.module.name));
13
14    if let Some(doc) = &file.doc {
15        out.push('\n');
16        for line in &doc.lines {
17            out.push_str(&format!("--- {}\n", line.trim()));
18        }
19    }
20
21    for use_decl in &file.imports {
22        out.push('\n');
23        if let Some(item) = &use_decl.item {
24            out.push_str(&format!("use {}.{}\n", use_decl.module_name, item));
25        } else {
26            out.push_str(&format!("use {}\n", use_decl.module_name));
27        }
28    }
29
30    for item in &file.items {
31        out.push('\n');
32        match item {
33            ast::TopLevelItem::Entity(e) => fmt_entity(&mut out, e),
34            ast::TopLevelItem::Action(a) => fmt_action(&mut out, a),
35            ast::TopLevelItem::Invariant(i) => fmt_invariant(&mut out, i),
36            ast::TopLevelItem::EdgeCases(ec) => fmt_edge_cases(&mut out, ec),
37        }
38    }
39
40    out
41}
42
43fn fmt_doc(out: &mut String, doc: &Option<ast::DocBlock>) {
44    if let Some(doc) = doc {
45        for line in &doc.lines {
46            out.push_str(&format!("  --- {}\n", line.trim()));
47        }
48        out.push('\n');
49    }
50}
51
52fn fmt_entity(out: &mut String, entity: &ast::EntityDecl) {
53    out.push_str(&format!("entity {} {{\n", entity.name));
54    fmt_doc(out, &entity.doc);
55    for field in &entity.fields {
56        out.push_str(&format!("  {}: {}\n", field.name, format_type(&field.ty)));
57    }
58    out.push_str("}\n");
59}
60
61fn fmt_action(out: &mut String, action: &ast::ActionDecl) {
62    out.push_str(&format!("action {} {{\n", action.name));
63    fmt_doc(out, &action.doc);
64
65    for param in &action.params {
66        out.push_str(&format!("  {}: {}\n", param.name, format_type(&param.ty)));
67    }
68
69    if let Some(req) = &action.requires {
70        out.push_str("\n  requires {\n");
71        for cond in &req.conditions {
72            out.push_str(&format!("    {}\n", fmt_expr(cond)));
73        }
74        out.push_str("  }\n");
75    }
76
77    if let Some(ens) = &action.ensures {
78        out.push_str("\n  ensures {\n");
79        for item in &ens.items {
80            match item {
81                ast::EnsuresItem::Expr(expr) => {
82                    out.push_str(&format!("    {}\n", fmt_expr(expr)));
83                }
84                ast::EnsuresItem::When(w) => {
85                    out.push_str(&format!(
86                        "    when {} => {}\n",
87                        fmt_expr(&w.condition),
88                        fmt_expr(&w.consequence)
89                    ));
90                }
91            }
92        }
93        out.push_str("  }\n");
94    }
95
96    if let Some(props) = &action.properties {
97        out.push_str("\n  properties {\n");
98        for entry in &props.entries {
99            out.push_str(&format!(
100                "    {}: {}\n",
101                entry.key,
102                fmt_prop_value(&entry.value)
103            ));
104        }
105        out.push_str("  }\n");
106    }
107
108    out.push_str("}\n");
109}
110
111fn fmt_invariant(out: &mut String, inv: &ast::InvariantDecl) {
112    out.push_str(&format!("invariant {} {{\n", inv.name));
113    fmt_doc(out, &inv.doc);
114    out.push_str(&format!("  {}\n", fmt_expr(&inv.body)));
115    out.push_str("}\n");
116}
117
118fn fmt_edge_cases(out: &mut String, ec: &ast::EdgeCasesDecl) {
119    out.push_str("edge_cases {\n");
120    for rule in &ec.rules {
121        out.push_str(&format!(
122            "  when {} => {}({})\n",
123            fmt_expr(&rule.condition),
124            rule.action.name,
125            fmt_call_args(&rule.action.args),
126        ));
127    }
128    out.push_str("}\n");
129}
130
131fn fmt_expr(expr: &ast::Expr) -> String {
132    match &expr.kind {
133        ast::ExprKind::Implies(l, r) => format!("{} => {}", fmt_expr(l), fmt_expr(r)),
134        ast::ExprKind::Or(l, r) => format!("{} || {}", fmt_expr(l), fmt_expr(r)),
135        ast::ExprKind::And(l, r) => format!("{} && {}", fmt_expr(l), fmt_expr(r)),
136        ast::ExprKind::Not(e) => format!("!{}", fmt_expr(e)),
137        ast::ExprKind::Compare { left, op, right } => {
138            let op_str = match op {
139                ast::CmpOp::Eq => "==",
140                ast::CmpOp::Ne => "!=",
141                ast::CmpOp::Lt => "<",
142                ast::CmpOp::Gt => ">",
143                ast::CmpOp::Le => "<=",
144                ast::CmpOp::Ge => ">=",
145            };
146            format!("{} {} {}", fmt_expr(left), op_str, fmt_expr(right))
147        }
148        ast::ExprKind::Arithmetic { left, op, right } => {
149            let op_str = match op {
150                ast::ArithOp::Add => "+",
151                ast::ArithOp::Sub => "-",
152            };
153            format!("{} {} {}", fmt_expr(left), op_str, fmt_expr(right))
154        }
155        ast::ExprKind::Old(e) => format!("old({})", fmt_expr(e)),
156        ast::ExprKind::Quantifier {
157            kind,
158            binding,
159            ty,
160            body,
161        } => {
162            let kw = match kind {
163                ast::QuantifierKind::Forall => "forall",
164                ast::QuantifierKind::Exists => "exists",
165            };
166            format!("{} {}: {} => {}", kw, binding, ty, fmt_expr(body))
167        }
168        ast::ExprKind::Call { name, args } => {
169            format!("{}({})", name, fmt_call_args(args))
170        }
171        ast::ExprKind::FieldAccess { root, fields } => {
172            format!("{}.{}", fmt_expr(root), fields.join("."))
173        }
174        ast::ExprKind::List(items) => {
175            let inner: Vec<_> = items.iter().map(fmt_expr).collect();
176            format!("[{}]", inner.join(", "))
177        }
178        ast::ExprKind::Ident(name) => name.clone(),
179        ast::ExprKind::Literal(lit) => fmt_literal(lit),
180    }
181}
182
183fn fmt_literal(lit: &ast::Literal) -> String {
184    match lit {
185        ast::Literal::Null => "null".to_string(),
186        ast::Literal::Bool(b) => b.to_string(),
187        ast::Literal::Int(n) => n.to_string(),
188        ast::Literal::Decimal(s) => s.clone(),
189        ast::Literal::String(s) => format!("\"{}\"", s),
190    }
191}
192
193fn fmt_call_args(args: &[ast::CallArg]) -> String {
194    args.iter()
195        .map(|a| match a {
196            ast::CallArg::Named { key, value, .. } => {
197                format!("{}: {}", key, fmt_expr(value))
198            }
199            ast::CallArg::Positional(e) => fmt_expr(e),
200        })
201        .collect::<Vec<_>>()
202        .join(", ")
203}
204
205fn fmt_prop_value(val: &ast::PropValue) -> String {
206    match val {
207        ast::PropValue::Literal(lit) => fmt_literal(lit),
208        ast::PropValue::Ident(s) => s.clone(),
209        ast::PropValue::List(items) => {
210            let inner: Vec<_> = items.iter().map(fmt_prop_value).collect();
211            format!("[{}]", inner.join(", "))
212        }
213        ast::PropValue::Object(fields) => {
214            let inner: Vec<_> = fields
215                .iter()
216                .map(|(k, v)| format!("{}: {}", k, fmt_prop_value(v)))
217                .collect();
218            format!("{{ {} }}", inner.join(", "))
219        }
220    }
221}