m3l-cli 0.9.0

M3L CLI tool — parse and validate .m3l.md schema files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use std::path::Path;

use crate::build_ast_with;

pub fn run_format(input_path: &Path) -> Result<String, String> {
    // The formatter reproduces the *source document*, not its semantic closure,
    // so inherited fields must stay in the parent. Inlining them here re-emitted
    // every parent field under the child while keeping the `: Parent` header —
    // the fields then doubled on each successive format.
    let ast = build_ast_with(
        input_path,
        m3l_core::ResolveOptions {
            inline_inherited: false,
        },
    )?;
    Ok(format_ast(&ast))
}

fn format_ast(ast: &m3l_core::M3lAst) -> String {
    let mut lines: Vec<String> = Vec::new();

    // Namespace
    if let Some(ref name) = ast.project.name {
        lines.push(format!("# Namespace: {name}"));
        lines.push(String::new());
    }

    // Models
    for model in &ast.models {
        format_model(&mut lines, model);
        lines.push(String::new());
    }

    // Enums
    for e in &ast.enums {
        format_enum(&mut lines, e);
        lines.push(String::new());
    }

    // Interfaces
    for iface in &ast.interfaces {
        lines.push(format!("## {} ::interface", iface.name));
        format_model_body(&mut lines, iface);
        lines.push(String::new());
    }

    // Views
    for view in &ast.views {
        lines.push(format!("## {} ::view", view.name));
        format_model_body(&mut lines, view);
        lines.push(String::new());
    }

    // Remove trailing empty lines
    while lines.last().is_some_and(|l| l.is_empty()) {
        lines.pop();
    }

    lines.join("\n")
}

fn format_model(lines: &mut Vec<String>, model: &m3l_core::ModelNode) {
    let mut header = format!("## {}", model.name);
    if !model.inherits.is_empty() {
        header.push_str(&format!(" : {}", model.inherits.join(", ")));
    }
    if !model.attributes.is_empty() {
        for attr in &model.attributes {
            header.push_str(&format!(" @{}", attr.name));
            if let Some(args_str) = format_attr_args(attr) {
                header.push_str(&args_str);
            }
        }
    }
    lines.push(header);
    format_model_body(lines, model);
}

/// Emit a description as blockquote lines, one per source line.
///
/// A description carrying newlines must never be written as a single line —
/// the embedded newline splits the output and every line after the first is
/// orphaned, so it disappears on the next parse.
fn push_description(lines: &mut Vec<String>, desc: &str, prefix: &str) {
    for desc_line in desc.split('\n') {
        lines.push(format!("{prefix}> {desc_line}"));
    }
}

fn format_model_body(lines: &mut Vec<String>, model: &m3l_core::ModelNode) {
    if let Some(ref desc) = model.description {
        push_description(lines, desc, "");
    }
    for field in &model.fields {
        format_field(lines, field, 0);
    }
}

fn format_field(lines: &mut Vec<String>, field: &m3l_core::FieldNode, indent: usize) {
    let prefix = "  ".repeat(indent);
    let mut line = format!("{prefix}- {}", field.name);

    if let Some(ref ft) = field.field_type {
        line.push_str(&format!(": {ft}"));
        if let Some(ref params) = field.params {
            let param_strs: Vec<String> = params
                .iter()
                .map(|p| match p {
                    m3l_core::ParamValue::String(s) => s.clone(),
                    m3l_core::ParamValue::Number(n) => n.to_string(),
                })
                .collect();
            line.push_str(&format!("({})", param_strs.join(", ")));
        }
    }
    // `Type?[]?` — a leading `?` marks the array's items nullable, a trailing
    // `?` after `[]` marks the array itself nullable (lexer: array ⇒ nullable
    // reads the trailing marker, array_item_nullable reads the leading one).
    // For a non-array field, either marker means the scalar type is nullable.
    if field.array {
        if field.array_item_nullable {
            line.push('?');
        }
        line.push_str("[]");
        if field.nullable {
            line.push('?');
        }
    } else if field.nullable {
        line.push('?');
    }

    if let Some(ref dv) = field.default_value {
        if field.default_value_quoted == Some(true) {
            line.push_str(&format!(" = \"{dv}\""));
        } else if field.default_value_backtick == Some(true) {
            line.push_str(&format!(" = `{dv}`"));
        } else {
            line.push_str(&format!(" = {dv}"));
        }
    }

    for attr in &field.attributes {
        line.push_str(&format!(" @{}", attr.name));
        if let Some(args_str) = format_attr_args(attr) {
            line.push_str(&args_str);
        }
    }

    lines.push(line);

    // Descriptions go in blockquote continuation lines rather than a trailing
    // `# ...` comment: the comment form put a raw newline mid-line for
    // multi-line descriptions. The blockquote form is the source form and
    // handles one line and many identically.
    if let Some(ref desc) = field.description {
        push_description(lines, desc, &format!("{prefix}  "));
    }

    // Inline enum values — emitted under the recommended `values:` key so they
    // read as enum values rather than extended-format attributes (§3.1.7).
    // Without this the whole inline enum vanished on format.
    if let Some(ref enum_values) = field.enum_values {
        lines.push(format!("{prefix}  - values:"));
        for val in enum_values {
            lines.push(format_enum_value(val, indent + 2));
        }
    }

    // Nested fields
    if let Some(ref sub_fields) = field.fields {
        for sf in sub_fields {
            format_field(lines, sf, indent + 1);
        }
    }
}

fn format_enum(lines: &mut Vec<String>, e: &m3l_core::EnumNode) {
    lines.push(format!("## {} ::enum", e.name));
    if let Some(ref desc) = e.description {
        push_description(lines, desc, "");
    }
    for val in &e.values {
        lines.push(format_enum_value(val, 0));
    }
}

/// Render one enum value in the canonical shape
/// `- name: type = value "label" @attr(args)` (§3.1.8), omitting the parts the
/// value does not carry.
///
/// Every part must be emitted: a formatter that drops `type`/`value`/attributes
/// deletes them from the user's model on the first `m3l format`.
fn format_enum_value(val: &m3l_core::EnumValue, indent: usize) -> String {
    let prefix = "  ".repeat(indent);
    let mut rhs = String::new();

    match (&val.value_type, &val.value) {
        (Some(t), Some(v)) => rhs.push_str(&format!("{t} = {}", render_json_scalar(v))),
        (Some(t), None) => rhs.push_str(t),
        // A bare stored value with no declared type would re-parse as a *type*,
        // so it stays behind `=` to keep the two roles distinct.
        (None, Some(v)) => rhs.push_str(&format!("= {}", render_json_scalar(v))),
        (None, None) => {}
    }

    if let Some(ref desc) = val.description {
        if !rhs.is_empty() {
            rhs.push(' ');
        }
        rhs.push_str(&format!("\"{desc}\""));
    }

    if let Some(ref attrs) = val.attributes {
        for attr in attrs {
            if !rhs.is_empty() {
                rhs.push(' ');
            }
            rhs.push_str(&format!("@{}", attr.name));
            if let Some(args_str) = format_attr_args(attr) {
                rhs.push_str(&args_str);
            }
        }
    }

    // The colon form is required whenever anything follows the name: the
    // colon-less `- name "label"` shape only parses when the label is the
    // *entire* remainder, so `- name "label" @attr` would be swallowed into
    // the name.
    if rhs.is_empty() {
        format!("{prefix}- {}", val.name)
    } else {
        format!("{prefix}- {}: {rhs}", val.name)
    }
}

fn render_json_scalar(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

fn format_arg(arg: &m3l_core::AttrArgValue, quoted: bool) -> String {
    match arg {
        // A backtick-delimited argument's backticks are already part of `s`
        // (see `parse_attr_args_string_with_origin`), so it's never `quoted`
        // here — only a `"..."`/`'...'`-stripped string is.
        m3l_core::AttrArgValue::String(s) if quoted => format!("\"{s}\""),
        m3l_core::AttrArgValue::String(s) => s.clone(),
        m3l_core::AttrArgValue::Number(n) => n.to_string(),
        m3l_core::AttrArgValue::Bool(b) => b.to_string(),
    }
}

/// Render an attribute's `(args)` suffix, reproducing each arg's original
/// quoting from `args_quoted` (§HD-16 — `AttrArgValue` is untagged so it can't
/// carry that flag itself). `None` when the attribute has no args at all.
fn format_attr_args(attr: &m3l_core::FieldAttribute) -> Option<String> {
    let args = attr.args.as_ref()?;
    let arg_strs: Vec<String> = args
        .iter()
        .enumerate()
        .map(|(i, arg)| {
            let quoted = attr
                .args_quoted
                .as_ref()
                .and_then(|q| q.get(i))
                .copied()
                .unwrap_or(false);
            format_arg(arg, quoted)
        })
        .collect();
    Some(format!("({})", arg_strs.join(", ")))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Formatting must be information-preserving: parsing the formatted output
    /// has to yield the same enum values as parsing the original. Anything the
    /// formatter cannot re-emit is silently deleted from a user's model the
    /// first time they run `m3l format`.
    fn roundtrip_enum_values(src: &str) -> (Vec<m3l_core::EnumValue>, Vec<m3l_core::EnumValue>) {
        let ast = m3l_core::resolve(&[m3l_core::parse_string(src, "t.m3l.md")], None);
        let formatted = format_ast(&ast);
        let reparsed = m3l_core::resolve(&[m3l_core::parse_string(&formatted, "t.m3l.md")], None);
        (
            ast.enums
                .first()
                .map(|e| e.values.clone())
                .unwrap_or_default(),
            reparsed
                .enums
                .first()
                .map(|e| e.values.clone())
                .unwrap_or_default(),
        )
    }

    #[test]
    fn format_preserves_enum_value_attributes() {
        let (before, after) = roundtrip_enum_values(
            "## PaymentMethod ::enum\n- cash: \"현금\"\n- legacy: \"이관 정리\" @system",
        );
        assert_eq!(before, after, "enum value attributes must survive format");
    }

    #[test]
    fn format_preserves_enum_value_type_and_stored_value() {
        let (before, after) = roundtrip_enum_values(
            "## OrderStatus ::enum\n- pending: integer = 100 \"대기\"\n- done: integer = 200 \"완료\" @system",
        );
        assert_eq!(
            before, after,
            "enum value type/stored value must survive format"
        );
    }

    #[test]
    fn format_preserves_enum_attribute_args() {
        let (before, after) = roundtrip_enum_values(
            "## Status ::enum\n- archived: \"보관\" @deprecated(\"use closed\")",
        );
        assert_eq!(before, after, "attribute args must survive format");
    }

    #[test]
    fn format_preserves_stored_value_without_type() {
        // Nested enum values can carry a stored value with no declared type.
        let (before, after) = roundtrip_enum_values("## Code ::enum\n  - a: A_1\n  - b: B_2");
        assert_eq!(before, after, "untyped stored value must survive format");
    }

    #[test]
    fn format_preserves_inline_enum_values() {
        let src = "## Order\n- method: enum = \"cash\"\n  - values:\n    - cash: \"현금\"\n    - legacy: \"이관\" @system";
        let ast = m3l_core::resolve(&[m3l_core::parse_string(src, "t.m3l.md")], None);
        let formatted = format_ast(&ast);
        let reparsed = m3l_core::resolve(&[m3l_core::parse_string(&formatted, "t.m3l.md")], None);
        assert_eq!(
            ast.models[0].fields[0].enum_values, reparsed.models[0].fields[0].enum_values,
            "inline enum values must survive format:\n{formatted}"
        );
    }

    /// `array` + `nullable`/`array_item_nullable`: parses `Type?[]?` (leading `?`
    /// = item-nullable, trailing `?` after `[]` = array-nullable). The formatter
    /// must reproduce both flags at their own position, not just one of them
    /// or the other's position (ISSUE-m3l-20260829-format-roundtrip-fidelity-gaps).
    fn roundtrip_array_flags(field_decl: &str) -> (bool, bool) {
        let src = format!("## T\n- f: {field_decl}");
        let ast = m3l_core::resolve(&[m3l_core::parse_string(&src, "t.m3l.md")], None);
        let formatted = format_ast(&ast);
        let reparsed = m3l_core::resolve(&[m3l_core::parse_string(&formatted, "t.m3l.md")], None);
        let field = &reparsed.models[0].fields[0];
        (field.nullable, field.array_item_nullable)
    }

    #[test]
    fn format_preserves_item_nullable_without_array_nullable() {
        let (nullable, item_nullable) = roundtrip_array_flags("string?[]");
        assert!(!nullable, "array itself must stay non-nullable");
        assert!(item_nullable, "item-nullable marker must survive format");
    }

    #[test]
    fn format_preserves_array_nullable_without_item_nullable() {
        let (nullable, item_nullable) = roundtrip_array_flags("string[]?");
        assert!(nullable, "array-nullable marker must survive format");
        assert!(!item_nullable, "items must stay non-nullable");
    }

    #[test]
    fn format_preserves_both_nullable_markers_independently() {
        let (nullable, item_nullable) = roundtrip_array_flags("string?[]?");
        assert!(nullable, "array-nullable marker must survive format");
        assert!(item_nullable, "item-nullable marker must survive format");
    }

    /// A field's first attribute's `args`/`args_quoted`, round-tripped through
    /// one format pass — `AttrArgValue` is `#[serde(untagged)]`, so without
    /// `args_quoted` a quoted and bareword string arg parse to the identical
    /// value and the formatter can't tell them apart on the second pass
    /// (ISSUE-m3l-20260829-format-roundtrip-fidelity-gaps, cause 1).
    fn roundtrip_attr_args(
        field_decl: &str,
    ) -> (Option<Vec<m3l_core::AttrArgValue>>, Option<Vec<bool>>) {
        let src = format!("## T\n- f: {field_decl}");
        let ast = m3l_core::resolve(&[m3l_core::parse_string(&src, "t.m3l.md")], None);
        let formatted = format_ast(&ast);
        let reparsed = m3l_core::resolve(&[m3l_core::parse_string(&formatted, "t.m3l.md")], None);
        let attr = &reparsed.models[0].fields[0].attributes[0];
        (attr.args.clone(), attr.args_quoted.clone())
    }

    #[test]
    fn format_preserves_quoted_attribute_arg() {
        let (args, quoted) = roundtrip_attr_args(r#"string @reference("Category")"#);
        assert_eq!(
            args,
            Some(vec![m3l_core::AttrArgValue::String("Category".into())])
        );
        assert_eq!(quoted, Some(vec![true]), "quoted arg must stay quoted");
    }

    #[test]
    fn format_preserves_unquoted_attribute_arg() {
        let (args, quoted) = roundtrip_attr_args("string @reference(Category)");
        assert_eq!(
            args,
            Some(vec![m3l_core::AttrArgValue::String("Category".into())])
        );
        assert!(
            quoted.is_none_or(|q| !q[0]),
            "bareword arg must not gain quotes"
        );
    }

    /// A field's default-value shape, round-tripped through one format pass —
    /// covers causes 3 (`Literal` quote-origin) and the backtick-`Expression`
    /// case discovered while fixing it (ISSUE-m3l-20260829-format-roundtrip-fidelity-gaps).
    fn roundtrip_default_value(
        field_decl: &str,
    ) -> (
        Option<String>,
        Option<m3l_core::DefaultValueType>,
        Option<bool>,
        Option<bool>,
    ) {
        let src = format!("## T\n- f: {field_decl}");
        let ast = m3l_core::resolve(&[m3l_core::parse_string(&src, "t.m3l.md")], None);
        let formatted = format_ast(&ast);
        let reparsed = m3l_core::resolve(&[m3l_core::parse_string(&formatted, "t.m3l.md")], None);
        let field = &reparsed.models[0].fields[0];
        (
            field.default_value.clone(),
            field.default_value_type.clone(),
            field.default_value_quoted,
            field.default_value_backtick,
        )
    }

    #[test]
    fn format_preserves_quoted_default_literal() {
        let (value, ty, quoted, backtick) = roundtrip_default_value(r#"string = "active""#);
        assert_eq!(value.as_deref(), Some("active"));
        assert_eq!(ty, Some(m3l_core::DefaultValueType::Literal));
        assert_eq!(quoted, Some(true), "quoted default must stay quoted");
        assert_eq!(backtick, None);
    }

    #[test]
    fn format_preserves_bareword_default_literal() {
        let (value, ty, quoted, backtick) = roundtrip_default_value("string = active");
        assert_eq!(value.as_deref(), Some("active"));
        assert_eq!(ty, Some(m3l_core::DefaultValueType::Literal));
        assert_eq!(quoted, None, "bareword default must not gain quotes");
        assert_eq!(backtick, None);
    }

    #[test]
    fn format_preserves_backtick_default_expression() {
        // Bare `price * qty` re-parses past its first non-word character —
        // without the backtick restored, the second format pass silently
        // truncates the default to `price`.
        let (value, ty, quoted, backtick) = roundtrip_default_value("decimal = `price * qty`");
        assert_eq!(value.as_deref(), Some("price * qty"));
        assert_eq!(ty, Some(m3l_core::DefaultValueType::Expression));
        assert_eq!(quoted, None);
        assert_eq!(
            backtick,
            Some(true),
            "backtick expression must keep its delimiters"
        );
    }

    #[test]
    fn format_preserves_paren_default_expression() {
        // `now()` is Expression too (parenthesized call), but never had
        // backticks — must not gain them.
        let (value, ty, quoted, backtick) = roundtrip_default_value("timestamp = now()");
        assert_eq!(value.as_deref(), Some("now()"));
        assert_eq!(ty, Some(m3l_core::DefaultValueType::Expression));
        assert_eq!(quoted, None);
        assert_eq!(
            backtick, None,
            "paren-call expression must not gain backticks"
        );
    }
}