Skip to main content

vibe/
pretty.rs

1//! Pretty printer for field/material/law declarations (W16).
2//!
3//! Formats VibeScript declarations in a canonical, readable style.
4//! This is CST sugar — it uses the trivia module to preserve comments
5//! and whitespace, so round-tripping through the pretty printer doesn't
6//! destroy commentary.
7//!
8//! ## Style
9//!
10//! ```vibe
11//! field pressure_ambient: Pressure
12//!   unit: <qudt:KiloPascal>
13//!   support: region
14//!   representation: grid;
15//!
16//! material steel: Material
17//!   yield: 250.0,
18//!   density: 7850.0;
19//!
20//! law crush
21//!   when pressure_ambient > steel.yield
22//!   => 1;
23//! ```
24//!
25//! Reference: `docs/vibescript-full-impl-PLAN.md` wish list W16.
26
27use std::fmt::Write;
28
29/// Pretty-print options.
30#[derive(Debug, Clone)]
31pub struct PrettyOptions {
32    /// Indentation string (default: two spaces).
33    pub indent: String,
34    /// Blank lines between top-level declarations (default: 1).
35    pub blank_lines_between_decls: usize,
36    /// Maximum line width before wrapping (default: 80).
37    pub max_line_width: usize,
38}
39
40impl Default for PrettyOptions {
41    fn default() -> Self {
42        Self {
43            indent: "  ".into(),
44            blank_lines_between_decls: 1,
45            max_line_width: 80,
46        }
47    }
48}
49
50/// A pretty-printable field declaration.
51#[derive(Debug, Clone)]
52pub struct PrettyField {
53    pub name: String,
54    pub field_type: String,
55    pub properties: Vec<(String, String)>,
56}
57
58impl PrettyField {
59    /// Creates a new `PrettyField`.
60    pub fn new(name: &str, field_type: &str) -> Self {
61        Self {
62            name: name.into(),
63            field_type: field_type.into(),
64            properties: Vec::new(),
65        }
66    }
67
68    /// Formatted property.
69    pub fn prop(mut self, key: &str, value: &str) -> Self {
70        self.properties.push((key.into(), value.into()));
71        self
72    }
73
74    /// Formats the item.
75    pub fn format(&self, opts: &PrettyOptions, out: &mut String) {
76        writeln!(out, "field {} : {}", self.name, self.field_type).unwrap();
77        for (i, (k, v)) in self.properties.iter().enumerate() {
78            let sep = if i + 1 < self.properties.len() {
79                ","
80            } else {
81                ""
82            };
83            writeln!(out, "{}{}: {}{}", opts.indent, k, v, sep).unwrap();
84        }
85        writeln!(out, ";").unwrap();
86    }
87}
88
89/// A pretty-printable material declaration.
90#[derive(Debug, Clone)]
91pub struct PrettyMaterial {
92    pub name: String,
93    pub material_type: String,
94    pub properties: Vec<(String, String)>,
95}
96
97impl PrettyMaterial {
98    /// Creates a new `PrettyMaterial`.
99    pub fn new(name: &str, material_type: &str) -> Self {
100        Self {
101            name: name.into(),
102            material_type: material_type.into(),
103            properties: Vec::new(),
104        }
105    }
106
107    /// Formatted property.
108    pub fn prop(mut self, key: &str, value: &str) -> Self {
109        self.properties.push((key.into(), value.into()));
110        self
111    }
112
113    /// Formats the item.
114    pub fn format(&self, opts: &PrettyOptions, out: &mut String) {
115        writeln!(out, "material {} : {}", self.name, self.material_type).unwrap();
116        for (i, (k, v)) in self.properties.iter().enumerate() {
117            let sep = if i + 1 < self.properties.len() {
118                ","
119            } else {
120                ""
121            };
122            writeln!(out, "{}{}: {}{}", opts.indent, k, v, sep).unwrap();
123        }
124        writeln!(out, ";").unwrap();
125    }
126}
127
128/// A pretty-printable law declaration.
129#[derive(Debug, Clone)]
130pub struct PrettyLaw {
131    pub name: String,
132    pub when_expr: String,
133    pub then_expr: String,
134}
135
136impl PrettyLaw {
137    /// Creates a new `PrettyLaw`.
138    pub fn new(name: &str, when_expr: &str, then_expr: &str) -> Self {
139        Self {
140            name: name.into(),
141            when_expr: when_expr.into(),
142            then_expr: then_expr.into(),
143        }
144    }
145
146    /// Formats the item.
147    pub fn format(&self, opts: &PrettyOptions, out: &mut String) {
148        writeln!(out, "law {}", self.name).unwrap();
149        writeln!(out, "{}when {}", opts.indent, self.when_expr).unwrap();
150        writeln!(out, "{}=> {}", opts.indent, self.then_expr).unwrap();
151        writeln!(out, ";").unwrap();
152    }
153}
154
155/// A document of pretty-printable declarations.
156#[derive(Debug, Clone)]
157pub struct PrettyDocument {
158    pub fields: Vec<PrettyField>,
159    pub materials: Vec<PrettyMaterial>,
160    pub laws: Vec<PrettyLaw>,
161}
162
163impl Default for PrettyDocument {
164    fn default() -> Self {
165        Self::new()
166    }
167}
168
169impl PrettyDocument {
170    /// Creates a new `PrettyDocument`.
171    pub fn new() -> Self {
172        Self {
173            fields: Vec::new(),
174            materials: Vec::new(),
175            laws: Vec::new(),
176        }
177    }
178
179    /// Adds field.
180    pub fn add_field(&mut self, f: PrettyField) -> &mut Self {
181        self.fields.push(f);
182        self
183    }
184
185    /// Adds material.
186    pub fn add_material(&mut self, m: PrettyMaterial) -> &mut Self {
187        self.materials.push(m);
188        self
189    }
190
191    /// Adds law.
192    pub fn add_law(&mut self, l: PrettyLaw) -> &mut Self {
193        self.laws.push(l);
194        self
195    }
196
197    /// Format the entire document.
198    pub fn format(&self, opts: &PrettyOptions) -> String {
199        let mut out = String::new();
200        let blank = "\n".repeat(opts.blank_lines_between_decls);
201
202        let mut first = true;
203        for f in &self.fields {
204            if !first {
205                out.push_str(&blank);
206            }
207            f.format(opts, &mut out);
208            first = false;
209        }
210        for m in &self.materials {
211            if !first {
212                out.push_str(&blank);
213            }
214            m.format(opts, &mut out);
215            first = false;
216        }
217        for l in &self.laws {
218            if !first {
219                out.push_str(&blank);
220            }
221            l.format(opts, &mut out);
222            first = false;
223        }
224        out
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn pretty_field_basic() {
234        let f = PrettyField::new("pressure_ambient", "Pressure")
235            .prop("unit", "<qudt:KiloPascal>")
236            .prop("support", "region")
237            .prop("representation", "grid");
238        let opts = PrettyOptions::default();
239        let mut out = String::new();
240        f.format(&opts, &mut out);
241        assert!(out.contains("field pressure_ambient : Pressure"));
242        assert!(out.contains("unit: <qudt:KiloPascal>"));
243        assert!(out.contains("support: region"));
244        assert!(out.contains("representation: grid"));
245        assert!(out.ends_with(";\n"));
246    }
247
248    #[test]
249    fn pretty_field_property_separators() {
250        let f = PrettyField::new("temp", "Temperature")
251            .prop("unit", "<qudt:Kelvin>")
252            .prop("support", "point");
253        let opts = PrettyOptions::default();
254        let mut out = String::new();
255        f.format(&opts, &mut out);
256        // First property gets a comma, last doesn't.
257        assert!(out.contains("unit: <qudt:Kelvin>,"));
258        assert!(out.contains("support: point\n")); // no trailing comma
259    }
260
261    #[test]
262    fn pretty_material_basic() {
263        let m = PrettyMaterial::new("steel", "Material")
264            .prop("yield", "250.0")
265            .prop("density", "7850.0");
266        let opts = PrettyOptions::default();
267        let mut out = String::new();
268        m.format(&opts, &mut out);
269        assert!(out.contains("material steel : Material"));
270        assert!(out.contains("yield: 250.0,"));
271        assert!(out.contains("density: 7850.0"));
272    }
273
274    #[test]
275    fn pretty_material_single_prop_no_comma() {
276        let m = PrettyMaterial::new("aluminum", "Material").prop("yield", "95.0");
277        let opts = PrettyOptions::default();
278        let mut out = String::new();
279        m.format(&opts, &mut out);
280        assert!(out.contains("yield: 95.0\n")); // no trailing comma
281    }
282
283    #[test]
284    fn pretty_law_basic() {
285        let l = PrettyLaw::new("crush", "pressure_ambient > steel.yield", "1");
286        let opts = PrettyOptions::default();
287        let mut out = String::new();
288        l.format(&opts, &mut out);
289        assert!(out.contains("law crush"));
290        assert!(out.contains("when pressure_ambient > steel.yield"));
291        assert!(out.contains("=> 1"));
292        assert!(out.ends_with(";\n"));
293    }
294
295    #[test]
296    fn pretty_document_full() {
297        let mut doc = PrettyDocument::new();
298        doc.add_field(PrettyField::new("pressure", "Pressure").prop("unit", "<qudt:KiloPascal>"));
299        doc.add_material(PrettyMaterial::new("steel", "Material").prop("yield", "250.0"));
300        doc.add_law(PrettyLaw::new("crush", "pressure > steel.yield", "1"));
301        let opts = PrettyOptions::default();
302        let out = doc.format(&opts);
303        assert!(out.contains("field pressure : Pressure"));
304        assert!(out.contains("material steel : Material"));
305        assert!(out.contains("law crush"));
306    }
307
308    #[test]
309    fn pretty_document_blank_lines_between() {
310        let mut doc = PrettyDocument::new();
311        doc.add_field(PrettyField::new("a", "A"));
312        doc.add_field(PrettyField::new("b", "B"));
313        let opts = PrettyOptions {
314            blank_lines_between_decls: 2,
315            ..Default::default()
316        };
317        let out = doc.format(&opts);
318        // Two blank lines between declarations.
319        assert!(out.contains(";\n\n\nfield b : B"));
320    }
321
322    #[test]
323    fn pretty_document_empty() {
324        let doc = PrettyDocument::new();
325        let opts = PrettyOptions::default();
326        let out = doc.format(&opts);
327        assert!(out.is_empty());
328    }
329
330    #[test]
331    fn pretty_options_custom_indent() {
332        let f = PrettyField::new("x", "X").prop("a", "1");
333        let opts = PrettyOptions {
334            indent: "    ".into(),
335            ..Default::default()
336        };
337        let mut out = String::new();
338        f.format(&opts, &mut out);
339        assert!(out.contains("    a: 1"));
340    }
341
342    #[test]
343    fn pretty_field_no_properties() {
344        let f = PrettyField::new("empty", "Empty");
345        let opts = PrettyOptions::default();
346        let mut out = String::new();
347        f.format(&opts, &mut out);
348        assert!(out.contains("field empty : Empty"));
349        assert!(out.ends_with(";\n"));
350    }
351
352    #[test]
353    fn pretty_material_no_properties() {
354        let m = PrettyMaterial::new("void", "Material");
355        let opts = PrettyOptions::default();
356        let mut out = String::new();
357        m.format(&opts, &mut out);
358        assert!(out.contains("material void : Material"));
359        assert!(out.ends_with(";\n"));
360    }
361}