quillmark-core 0.68.0

Core types and functionality for Quillmark
Documentation
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Canonical Markdown emission for [`Document`].
//!
//! This module implements [`Document::to_markdown`], which converts a typed
//! in-memory `Document` back into canonical Quillmark Markdown.
//!
//! ## YAML emission strategy
//!
//! `serde-saphyr::SerializerOptions::quote_all` was evaluated (spike, 2026-04-21)
//! and found to emit single-quoted strings for ordinary scalars like `"on"` and
//! `"01234"` — switching to double quotes only when the string contains a single
//! quote, backslash, or control character.  That behaviour is correct for
//! round-trip type-fidelity (single-quoted YAML strings are re-parsed as strings),
//! but the Quillmark spec (§5.2) requires **always double-quoted, JSON-style
//! escaping**.  Because `SerializerOptions` provides no "force double-quote" knob,
//! the YAML value block is generated by a hand-written emitter in this module.
//!
//! The hand-written emitter is small (< 120 lines), covers exactly the
//! `QuillValue` type variants, and gives complete control over quoting style and
//! indentation without pulling in additional abstractions.

use serde_json::Value as JsonValue;

use super::frontmatter::FrontmatterItem;
use super::prescan::{CommentPathSegment, NestedComment};
use super::{Card, Document, Sentinel};

// ── Public entry point ────────────────────────────────────────────────────────

impl Document {
    /// Emit canonical Quillmark Markdown from this document.
    ///
    /// # Contract
    ///
    /// 1. **Type-fidelity round-trip.** `Document::from_markdown(&doc.to_markdown())`
    ///    returns a `Document` equal to `doc` by value *and* by type variant.
    ///    `QuillValue::String("on")` round-trips as a string, never as a bool.
    ///    `QuillValue::String("01234")` round-trips as a string, never as an
    ///    integer.  This guarantee is the whole point of owning emission.
    ///
    /// 2. **Emit-idempotent.** `to_markdown` is a pure function of `doc`; two
    ///    calls on the same `doc` return byte-equal strings.
    ///
    /// Byte-equality with the *original source* is **not** guaranteed.
    ///
    /// # Emission rules (§5.2)
    ///
    /// - Line endings: `\n` only.  CRLF normalization happens on import.
    /// - Frontmatter: `---\n`, `QUILL: <ref>` first, remaining fields in
    ///   `IndexMap` insertion order, `---\n`, blank line.
    /// - Cards: one blank line before each, fence `---\nCARD: <tag>\n<fields>\n---\n<body>`.
    /// - Body: emitted verbatim after frontmatter (and cards).
    /// - Mappings and sequences: **block style** at every nesting level.
    /// - Booleans: `true` / `false`.
    /// - Null: `null`.
    /// - Numbers: bare literals (integer or float as stored in `serde_json::Value`).
    /// - **Strings: always double-quoted**, JSON-style escaping
    ///   (`\"`, `\\`, `\n`, `\t`, `\uXXXX` for control chars).  This is the
    ///   load-bearing rule that guarantees type fidelity.
    /// - Multi-line strings: double-quoted with `\n` escape sequences.  No block
    ///   scalars (`|`, `>`) in v1.
    ///
    /// # Open decisions (resolved)
    ///
    /// - **Nested-map order.** `QuillValue` is backed by `serde_json::Value`
    ///   whose object type (`serde_json::Map`) preserves insertion order when the
    ///   `serde_json/preserve_order` feature is enabled (it is in this workspace).
    ///   Insertion order is therefore preserved for nested maps at emit time.
    ///
    /// - **Empty containers.**
    ///   - Empty object (`{}`) → the key is **omitted** from emit entirely.
    ///   - Empty array (`[]`) → emitted as `key: []\n`.
    ///
    /// # What is lost
    ///
    /// - **YAML comments**: stripped during parsing; not stored in `Document`.
    /// - **Custom tags** (`!fill`): the tag is dropped; the scalar value is
    ///   preserved.  On re-emit the tag does not appear.
    /// - **Original quoting style**: all strings are re-emitted double-quoted
    ///   regardless of how they were written in the source.
    pub fn to_markdown(&self) -> String {
        let mut out = String::new();

        // ── Main card (first fence + global body) ─────────────────────────────
        emit_card_fence(&mut out, self.main());
        out.push_str(self.main().body());

        // ── Composable cards ──────────────────────────────────────────────────
        // `emit_card` normalises the separator before each fence, so edited
        // bodies (which may lack a trailing blank line) still round-trip.
        for card in self.cards() {
            ensure_f2_before_fence(&mut out);
            emit_card_fence(&mut out, card);
            if !card.body().is_empty() {
                out.push_str(card.body());
            }
        }

        out
    }
}

// ── Card emission ─────────────────────────────────────────────────────────────

/// Emit a card's metadata fence (between `---\n` markers), including the
/// sentinel line and every frontmatter item.
fn emit_card_fence(out: &mut String, card: &Card) {
    out.push_str("---\n");

    // Sentinel line.
    match card.sentinel() {
        Sentinel::Main(r) => {
            out.push_str("QUILL: ");
            out.push_str(&r.to_string());
            out.push('\n');
        }
        Sentinel::Card(tag) => {
            out.push_str("CARD: ");
            out.push_str(tag);
            out.push('\n');
        }
    }

    // Frontmatter items in order.
    let nested = card.frontmatter().nested_comments();
    for item in card.frontmatter().items() {
        match item {
            FrontmatterItem::Field { key, value, fill } => {
                let path = vec![CommentPathSegment::Key(key.clone())];
                emit_field(out, key, value.as_json(), 0, *fill, &path, nested);
            }
            FrontmatterItem::Comment { text } => {
                out.push_str("# ");
                out.push_str(text);
                out.push('\n');
            }
        }
    }

    out.push_str("---\n");
}

/// Ensures `out` ends with a `\n\n` suffix suitable for the F2 precondition
/// of the next metadata fence.
///
/// Under the F2-separator-never-stored invariant, stored bodies may end with
/// their content (no newline), a content line terminator (`\n`), or an
/// author-intended blank line (`\n\n`, `\n\n\n`, …). In every case we append
/// exactly one `\n` to produce the F2 blank line. If the body doesn't already
/// end in `\n`, we also append a line terminator first so content lines are
/// terminated in the emitted markdown.
///
/// Empty `out` satisfies F2 via the "line 1" clause (MARKDOWN.md §3 F2) and
/// needs no separator.
fn ensure_f2_before_fence(out: &mut String) {
    if out.is_empty() {
        return;
    }
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out.push('\n');
}

// ── YAML value emission ───────────────────────────────────────────────────────

/// Emit comments captured at `path` whose `position` matches `position`,
/// each as a `# text` line indented by `indent` spaces.
fn emit_pending_comments(
    out: &mut String,
    path: &[CommentPathSegment],
    position: usize,
    indent: usize,
    nested: &[NestedComment],
) {
    for c in nested {
        if c.position == position && c.container_path.as_slice() == path {
            push_indent(out, indent);
            out.push_str("# ");
            out.push_str(&c.text);
            out.push('\n');
        }
    }
}

/// Emit a `key: <value>\n` pair at `indent` spaces.
///
/// `path` is the path to *this* field (parent path + this key). It's used as
/// the *container* path when recursing into the value: nested comments
/// captured at this path are interleaved between the value's children.
///
/// - Empty objects are **omitted** (caller skips them).
/// - Empty arrays emit `key: []\n`.
/// - All other values follow the block-style rules.
/// - When `fill` is `true`, the emitted form is `key: !fill <value>` for
///   scalars, `key: !fill\n  - …` for non-empty sequences,
///   `key: !fill []` for empty sequences, and `key: !fill` for null.
///   Mappings are rejected at parse and never reach this path.
fn emit_field(
    out: &mut String,
    key: &str,
    value: &JsonValue,
    indent: usize,
    fill: bool,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    if fill {
        push_indent(out, indent);
        out.push_str(key);
        match value {
            JsonValue::Null => out.push_str(": !fill\n"),
            JsonValue::Bool(_) | JsonValue::Number(_) | JsonValue::String(_) => {
                out.push_str(": !fill ");
                emit_scalar(out, value);
                out.push('\n');
            }
            JsonValue::Array(items) if items.is_empty() => {
                out.push_str(": !fill []\n");
            }
            JsonValue::Array(items) => {
                out.push_str(": !fill\n");
                emit_sequence_children(out, items, indent + 2, path, nested);
            }
            JsonValue::Object(_) => {
                // Parser rejects !fill on mappings; recovery path only.
                out.push_str(": ");
                emit_scalar(out, value);
                out.push('\n');
            }
        }
        return;
    }
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            // Empty object → omit the key entirely.
            return;
        }
        JsonValue::Object(map) => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(":\n");
            emit_mapping_children(out, map, indent + 2, path, nested);
        }
        JsonValue::Array(items) if items.is_empty() => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(": []\n");
        }
        JsonValue::Array(items) => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(":\n");
            emit_sequence_children(out, items, indent + 2, path, nested);
        }
        _ => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(": ");
            emit_scalar(out, value);
            out.push('\n');
        }
    }
}

/// Emit the children of a mapping value with comment interleaving.
///
/// `child_indent` is the indent at which each child key sits; nested
/// comments inside this mapping are emitted at the same indent. `path` is
/// the path to the mapping container (its key in the parent).
fn emit_mapping_children(
    out: &mut String,
    map: &serde_json::Map<String, JsonValue>,
    child_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    for (i, (k, v)) in map.iter().enumerate() {
        emit_pending_comments(out, path, i, child_indent, nested);
        let mut child_path = path.to_vec();
        child_path.push(CommentPathSegment::Key(k.clone()));
        emit_field(out, k, v, child_indent, false, &child_path, nested);
    }
    emit_pending_comments(out, path, map.len(), child_indent, nested);
}

/// Emit the children of a sequence value with comment interleaving.
///
/// `base_indent` is the indent at which each `- ` sits; nested comments
/// inside this sequence are emitted at the same indent.
fn emit_sequence_children(
    out: &mut String,
    items: &[JsonValue],
    base_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    for (i, item) in items.iter().enumerate() {
        emit_pending_comments(out, path, i, base_indent, nested);
        let mut child_path = path.to_vec();
        child_path.push(CommentPathSegment::Index(i));
        emit_sequence_item(out, item, base_indent, &child_path, nested);
    }
    emit_pending_comments(out, path, items.len(), base_indent, nested);
}

/// Emit a single `- <value>\n` sequence item at `base_indent` spaces.
///
/// `path` is the path to *this* item (parent path + item index).
fn emit_sequence_item(
    out: &mut String,
    value: &JsonValue,
    base_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            // Empty nested object in a sequence: emit as `- {}`
            push_indent(out, base_indent);
            out.push_str("- {}\n");
        }
        JsonValue::Object(map) => {
            // Block mapping inside a sequence.
            // First key on same line as `- `, subsequent keys indented by 2.
            // Comments inside this mapping use this item's path as the
            // container. There is no slot to emit a "before-first-key"
            // comment naturally, so we emit them as a leading line above
            // the `- ` prefix at the same indent.
            emit_pending_comments(out, path, 0, base_indent, nested);
            let mut first = true;
            for (i, (k, v)) in map.iter().enumerate() {
                if !first {
                    emit_pending_comments(out, path, i, base_indent + 2, nested);
                }
                let mut child_path = path.to_vec();
                child_path.push(CommentPathSegment::Key(k.clone()));
                if first {
                    push_indent(out, base_indent);
                    out.push_str("- ");
                    emit_field_inline(out, k, v, base_indent + 2, &child_path, nested);
                    first = false;
                } else {
                    emit_field(out, k, v, base_indent + 2, false, &child_path, nested);
                }
            }
            emit_pending_comments(out, path, map.len(), base_indent + 2, nested);
        }
        JsonValue::Array(inner) if inner.is_empty() => {
            push_indent(out, base_indent);
            out.push_str("- []\n");
        }
        JsonValue::Array(inner) => {
            // Nested sequence: emit `- ` for first item, then recurse.
            push_indent(out, base_indent);
            out.push_str("-\n");
            emit_sequence_children(out, inner, base_indent + 2, path, nested);
        }
        _ => {
            push_indent(out, base_indent);
            out.push_str("- ");
            emit_scalar(out, value);
            out.push('\n');
        }
    }
}

/// Emit a `key: <value>\n` pair where the key is already on a `- ` line.
/// The key/value go on the same line as the `- ` prefix (caller already wrote it).
fn emit_field_inline(
    out: &mut String,
    key: &str,
    value: &JsonValue,
    child_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            // key: {}
            out.push_str(key);
            out.push_str(": {}\n");
        }
        JsonValue::Object(map) => {
            out.push_str(key);
            out.push_str(":\n");
            emit_mapping_children(out, map, child_indent, path, nested);
        }
        JsonValue::Array(items) if items.is_empty() => {
            out.push_str(key);
            out.push_str(": []\n");
        }
        JsonValue::Array(items) => {
            out.push_str(key);
            out.push_str(":\n");
            emit_sequence_children(out, items, child_indent + 2, path, nested);
        }
        _ => {
            out.push_str(key);
            out.push_str(": ");
            emit_scalar(out, value);
            out.push('\n');
        }
    }
}

/// Emit a scalar value (no key, no newline) onto `out`.
fn emit_scalar(out: &mut String, value: &JsonValue) {
    match value {
        JsonValue::Null => out.push_str("null"),
        JsonValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        JsonValue::Number(n) => out.push_str(&n.to_string()),
        JsonValue::String(s) => emit_double_quoted(out, s),
        // Arrays/objects should not reach here via emit_field — handled above.
        // As a fallback, emit JSON representation.
        other => out.push_str(&other.to_string()),
    }
}

/// Emit a string as a JSON-style double-quoted YAML scalar.
///
/// Escape rules (same as JSON string encoding):
/// - `\` → `\\`
/// - `"` → `\"`
/// - `\n` → `\n`
/// - `\r` → `\r`
/// - `\t` → `\t`
/// - Other control characters (U+0000–U+001F, U+007F–U+009F) → `\uXXXX`
fn emit_double_quoted(out: &mut String, s: &str) {
    out.push('"');
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 || (0x7F..=0x9F).contains(&(c as u32)) => {
                // Control characters: \u00XX
                let n = c as u32;
                if n <= 0xFF {
                    out.push_str(&format!("\\u{:04X}", n));
                } else {
                    out.push_str(&format!("\\u{:04X}", n));
                }
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

// ── Utilities ─────────────────────────────────────────────────────────────────

fn push_indent(out: &mut String, spaces: usize) {
    for _ in 0..spaces {
        out.push(' ');
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    #[test]
    fn double_quoted_basic() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "hello");
        assert_eq!(s, r#""hello""#);
    }

    #[test]
    fn double_quoted_ambiguous_strings() {
        // These must remain strings on re-parse — the double-quoting is the guarantee.
        for ambiguous in &[
            "on", "off", "yes", "no", "true", "false", "null", "~", "01234", "1e10",
        ] {
            let mut s = String::new();
            emit_double_quoted(&mut s, ambiguous);
            assert!(
                s.starts_with('"') && s.ends_with('"'),
                "should be double-quoted: {}",
                s
            );
            // Verify the content is correct (no extra escaping for these).
            assert_eq!(&s[1..s.len() - 1], *ambiguous);
        }
    }

    #[test]
    fn double_quoted_escapes() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "a\\b\"c\nd\te");
        assert_eq!(s, r#""a\\b\"c\nd\te""#);
    }

    #[test]
    fn double_quoted_control_chars() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "\x01\x1F");
        assert_eq!(s, "\"\\u0001\\u001F\"");
    }

    fn p(key: &str) -> Vec<CommentPathSegment> {
        vec![CommentPathSegment::Key(key.to_string())]
    }

    #[test]
    fn empty_object_omitted() {
        let value = QuillValue::from_json(serde_json::json!({}));
        let mut out = String::new();
        emit_field(
            &mut out,
            "empty_map",
            value.as_json(),
            0,
            false,
            &p("empty_map"),
            &[],
        );
        assert_eq!(out, ""); // omitted
    }

    #[test]
    fn empty_array_emitted() {
        let value = QuillValue::from_json(serde_json::json!([]));
        let mut out = String::new();
        emit_field(
            &mut out,
            "empty_seq",
            value.as_json(),
            0,
            false,
            &p("empty_seq"),
            &[],
        );
        assert_eq!(out, "empty_seq: []\n");
    }

    #[test]
    fn fill_null_emits_bare_tag() {
        let value = QuillValue::from_json(serde_json::Value::Null);
        let mut out = String::new();
        emit_field(
            &mut out,
            "recipient",
            value.as_json(),
            0,
            true,
            &p("recipient"),
            &[],
        );
        assert_eq!(out, "recipient: !fill\n");
    }

    #[test]
    fn fill_string_emits_tag_with_value() {
        let value = QuillValue::from_json(serde_json::json!("placeholder"));
        let mut out = String::new();
        emit_field(&mut out, "dept", value.as_json(), 0, true, &p("dept"), &[]);
        assert_eq!(out, "dept: !fill \"placeholder\"\n");
    }

    #[test]
    fn fill_integer_emits_tag_with_value() {
        let value = QuillValue::from_json(serde_json::json!(42));
        let mut out = String::new();
        emit_field(
            &mut out,
            "count",
            value.as_json(),
            0,
            true,
            &p("count"),
            &[],
        );
        assert_eq!(out, "count: !fill 42\n");
    }
}