fast-yaml-core 0.6.4

Core YAML 1.2.2 parser and emitter
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Generic streaming formatter with pluggable backend.
//!
//! This module contains the core formatting logic abstracted over
//! different memory allocation strategies via the `FormatterBackend` trait.

use std::borrow::Cow;
use std::fmt::Write;

use saphyr_parser::{Event, ScalarStyle, Span, Tag};

use super::traits::{AnchorStoreOps, ContextStackOps, FormatterBackend};
use super::{Context, INDENT_SPACES, MAX_ANCHOR_ID, MAX_DEPTH};
use crate::emitter::EmitterConfig;

/// Return the YAML chomp indicator suffix for a block scalar value.
///
/// - `"+"` (keep) if `value` ends with two or more newlines (trailing blank lines)
/// - `""` (clip, default) if `value` ends with exactly one newline
/// - `"-"` (strip) if `value` does not end with a newline
fn chomp_indicator(value: &str) -> &'static str {
    if value.ends_with("\n\n") {
        "+"
    } else if value.ends_with('\n') {
        ""
    } else {
        "-"
    }
}

/// Generic streaming formatter with pluggable backend.
///
/// This struct contains ALL formatting logic and is parameterized over
/// the backend type `B: FormatterBackend`. Through monomorphization,
/// this compiles to specialized code for each backend with zero runtime cost.
#[allow(clippy::struct_excessive_bools)]
pub struct StreamingFormatter<'a, B: FormatterBackend> {
    config: &'a EmitterConfig,
    output: String,
    indent_level: usize,
    /// Tracks whether we need to emit a newline before the next value
    pending_newline: bool,
    /// Tracks whether the last character written was a newline.
    /// Avoids O(n) `ends_with` scans by maintaining state.
    last_char_newline: bool,
    /// Space after mapping key colon is deferred until the value is known.
    /// Cleared without emitting when the value is a nested collection.
    pending_space: bool,
    /// The first key of a mapping opened inline after "- " must not call
    /// `write_indent` — the dash already placed the cursor at the right column.
    first_key_after_dash: bool,
    /// The first item of a sequence opened inline after an outer "- " must not
    /// call `write_indent` — the outer dash already positioned the cursor.
    first_item_after_dash: bool,
    /// Backend providing context stack and anchor storage
    backend: B,
}

impl<'a, B: FormatterBackend> StreamingFormatter<'a, B> {
    /// Creates a new formatter with the given configuration and backend.
    ///
    /// # Arguments
    ///
    /// * `config` - Emitter configuration (indent, `explicit_start`, etc.)
    /// * `output_capacity` - Initial capacity for output buffer
    /// * `backend` - Backend providing context stack and anchor storage
    pub fn new(config: &'a EmitterConfig, output_capacity: usize, backend: B) -> Self {
        Self {
            config,
            output: String::with_capacity(output_capacity),
            indent_level: 0,
            pending_newline: false,
            last_char_newline: true, // Empty buffer conceptually "ends with" newline
            pending_space: false,
            first_key_after_dash: false,
            first_item_after_dash: false,
            backend,
        }
    }

    /// Returns the current YAML structure context.
    ///
    /// # Invariant
    /// The context stack is initialized with `Context::Root` and is never
    /// fully emptied. The `unwrap_or` is a defensive fallback.
    fn current_context(&self) -> Context {
        *self
            .backend
            .context_stack()
            .last()
            .unwrap_or(&Context::Root)
    }

    /// Emits an anchor marker (&anchorN) if `anchor_id` is valid.
    ///
    /// # Arguments
    ///
    /// * `anchor_id` - The anchor ID to emit (must be in range `1..=MAX_ANCHOR_ID`)
    /// * `emit_newline` - If true, emits newline after anchor; if false, emits space
    ///
    /// # Returns
    ///
    /// Returns true if an anchor was emitted, false otherwise.
    fn emit_anchor_if_present(&mut self, anchor_id: usize, emit_newline: bool) -> bool {
        if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
            self.backend.anchor_store_mut().ensure_capacity(anchor_id);
            let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
            self.output.push('&');
            self.output.push_str(name);
            if emit_newline {
                self.output.push('\n');
                self.last_char_newline = true;
            } else {
                self.output.push(' ');
                self.last_char_newline = false;
            }
            true
        } else {
            false
        }
    }

    /// Processes a parser event and updates formatter state.
    pub fn format_event(&mut self, event: Event<'_>, _span: Span) {
        match event {
            Event::DocumentStart(explicit) => {
                if explicit || self.config.explicit_start {
                    self.output.push_str("---");
                    self.pending_newline = true;
                    self.last_char_newline = false;
                }
            }

            Event::DocumentEnd => {
                if !self.last_char_newline && !self.output.is_empty() {
                    self.output.push('\n');
                    self.last_char_newline = true;
                }
            }

            Event::Scalar(value, style, anchor_id, tag) => {
                self.emit_scalar(&value, style, anchor_id, tag.as_ref());
            }

            Event::SequenceStart(anchor_id, tag) => {
                self.start_sequence(anchor_id, tag.as_ref());
            }

            Event::SequenceEnd => {
                self.end_sequence();
            }

            Event::MappingStart(anchor_id, tag) => {
                self.start_mapping(anchor_id, tag.as_ref());
            }

            Event::MappingEnd => {
                self.end_mapping();
            }

            Event::Alias(anchor_id) => {
                self.emit_alias(anchor_id);
            }

            // Events that require no action
            Event::StreamStart | Event::StreamEnd | Event::Nothing => {}
        }
    }

    fn emit_scalar(
        &mut self,
        value: &str,
        style: ScalarStyle,
        anchor_id: usize,
        _tag: Option<&Cow<'_, Tag>>,
    ) {
        let ctx = self.current_context();

        // Handle pending newline from document start or collection start
        if self.pending_newline {
            self.output.push('\n');
            self.pending_newline = false;
            self.last_char_newline = true;
        }

        // Write indentation and prefix based on context
        match ctx {
            Context::Sequence => {
                if self.first_item_after_dash {
                    self.first_item_after_dash = false;
                } else {
                    self.write_indent();
                }
                self.output.push_str("- ");
                self.last_char_newline = false;
            }
            Context::MappingKey => {
                if self.first_key_after_dash {
                    self.first_key_after_dash = false;
                } else {
                    self.write_indent();
                }
            }
            // Root level scalar needs no prefix; mapping value emits pending space
            Context::Root => {}
            Context::MappingValue => {
                if self.pending_space {
                    self.output.push(' ');
                    self.pending_space = false;
                    self.last_char_newline = false;
                }
            }
        }

        // Handle anchor if present (with bounds check for security)
        self.emit_anchor_if_present(anchor_id, false);

        // Emit value with appropriate style
        self.emit_value_with_style(value, style);

        // Handle context transitions
        match ctx {
            Context::MappingKey => {
                self.output.push(':');
                // Transition to expecting value
                if let Some(last) = self.backend.context_stack_mut().last_mut() {
                    *last = Context::MappingValue;
                }
                // Defer the space — emitted only when the value is a scalar.
                // If the value is a nested collection, pending_space is cleared
                // without emitting so we avoid a trailing space before the newline.
                self.pending_space = true;
                self.last_char_newline = false;
            }
            Context::MappingValue => {
                self.output.push('\n');
                self.last_char_newline = true;
                // Transition back to expecting key
                if let Some(last) = self.backend.context_stack_mut().last_mut() {
                    *last = Context::MappingKey;
                }
            }
            Context::Sequence | Context::Root => {
                self.output.push('\n');
                self.last_char_newline = true;
            }
        }
    }

    fn emit_value_with_style(&mut self, value: &str, style: ScalarStyle) {
        match style {
            ScalarStyle::Plain => {
                // Fix special floats for YAML 1.2 compliance
                let fixed = super::fix_special_float_value(value);
                self.output.push_str(fixed);
                self.last_char_newline = false;
            }
            ScalarStyle::SingleQuoted => {
                self.output.push('\'');
                // Single quotes: escape single quotes by doubling
                for c in value.chars() {
                    if c == '\'' {
                        self.output.push_str("''");
                    } else {
                        self.output.push(c);
                    }
                }
                self.output.push('\'');
                self.last_char_newline = false;
            }
            ScalarStyle::DoubleQuoted => {
                self.output.push('"');
                // Double quotes: escape special characters
                for c in value.chars() {
                    match c {
                        '"' => self.output.push_str("\\\""),
                        '\\' => self.output.push_str("\\\\"),
                        '\n' => self.output.push_str("\\n"),
                        '\r' => self.output.push_str("\\r"),
                        '\t' => self.output.push_str("\\t"),
                        '\0' => self.output.push_str("\\0"),
                        _ => self.output.push(c),
                    }
                }
                self.output.push('"');
                self.last_char_newline = false;
            }
            ScalarStyle::Literal => {
                self.output.push('|');
                self.output.push_str(chomp_indicator(value));
                self.output.push('\n');
                self.write_block_scalar_lines(value);
                // write_block_scalar_lines always ends with newline
                self.last_char_newline = true;
            }
            ScalarStyle::Folded => {
                self.output.push('>');
                self.output.push_str(chomp_indicator(value));
                self.output.push('\n');
                self.write_block_scalar_lines(value);
                // write_block_scalar_lines always ends with newline
                self.last_char_newline = true;
            }
        }
    }

    fn start_sequence(&mut self, anchor_id: usize, _tag: Option<&Cow<'_, Tag>>) {
        let ctx = self.current_context();

        // Handle pending newline
        if self.pending_newline {
            self.output.push('\n');
            self.pending_newline = false;
            self.last_char_newline = true;
        }

        // Write prefix and anchor inline per context to avoid anchors on wrong line.
        match ctx {
            Context::Sequence => {
                if self.first_item_after_dash {
                    self.first_item_after_dash = false;
                } else {
                    self.write_indent();
                }
                self.output.push_str("- ");
                self.last_char_newline = false;
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    // Emit anchor inline after "- "; then a newline.
                    // Children need fresh indentation — do NOT set first_item_after_dash.
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                    self.output.push('\n');
                    self.last_char_newline = true;
                } else {
                    // No anchor: first child sits right after "- ".
                    self.first_item_after_dash = true;
                }
            }
            Context::MappingKey => {
                // Sequence as mapping key - unusual but valid
                self.write_indent();
                self.emit_anchor_if_present(anchor_id, false);
            }
            Context::MappingValue => {
                // Value position - emit anchor inline if present, then newline.
                // The pending_space after colon is consumed here: if an anchor is present,
                // emit "key: &anchor\n"; otherwise emit "key:\n" (no trailing space).
                self.pending_space = false;
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    self.output.push(' ');
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                }
                self.output.push('\n');
                self.last_char_newline = true;
            }
            Context::Root => {
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                    self.output.push('\n');
                    self.last_char_newline = true;
                }
            }
        }

        // Update context for mapping value -> key transition
        if ctx == Context::MappingValue
            && let Some(last) = self.backend.context_stack_mut().last_mut()
        {
            *last = Context::MappingKey;
        }

        // Push sequence context and increase indent (with depth limit)
        if self.backend.context_stack().len() < MAX_DEPTH {
            self.backend.context_stack_mut().push(Context::Sequence);
            self.indent_level += 1;
        }
    }

    fn end_sequence(&mut self) {
        self.backend.context_stack_mut().pop();
        self.indent_level = self.indent_level.saturating_sub(1);
    }

    fn start_mapping(&mut self, anchor_id: usize, _tag: Option<&Cow<'_, Tag>>) {
        let ctx = self.current_context();

        // Handle pending newline
        if self.pending_newline {
            self.output.push('\n');
            self.pending_newline = false;
            self.last_char_newline = true;
        }

        // Write prefix and anchor inline per context to avoid anchors on wrong line.
        match ctx {
            Context::Sequence => {
                if self.first_item_after_dash {
                    self.first_item_after_dash = false;
                } else {
                    self.write_indent();
                }
                self.output.push_str("- ");
                self.last_char_newline = false;
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    // Emit anchor inline after "- "; then a newline.
                    // Anchor occupies the "- " line, so the first key goes on its own
                    // indented line — do NOT set first_key_after_dash.
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                    self.output.push('\n');
                    self.last_char_newline = true;
                    self.first_key_after_dash = false;
                } else {
                    // No anchor: first key sits right after "- "; no extra indent.
                    self.first_key_after_dash = true;
                }
            }
            Context::MappingKey => {
                // Mapping as mapping key - unusual but valid (complex key)
                self.write_indent();
                self.emit_anchor_if_present(anchor_id, false);
            }
            Context::MappingValue => {
                // Value position - emit anchor inline if present, then newline.
                // The pending_space after colon is consumed here: if an anchor is present,
                // emit "key: &anchor\n"; otherwise emit "key:\n" (no trailing space).
                self.pending_space = false;
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    self.output.push(' ');
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                }
                self.output.push('\n');
                self.last_char_newline = true;
            }
            Context::Root => {
                if anchor_id > 0 && anchor_id <= MAX_ANCHOR_ID {
                    self.backend.anchor_store_mut().ensure_capacity(anchor_id);
                    let name = self.backend.anchor_store_mut().set_if_empty(anchor_id);
                    self.output.push('&');
                    self.output.push_str(name);
                    self.output.push('\n');
                    self.last_char_newline = true;
                }
            }
        }

        // Update context for mapping value -> key transition
        if ctx == Context::MappingValue
            && let Some(last) = self.backend.context_stack_mut().last_mut()
        {
            *last = Context::MappingKey;
        }

        // Push mapping context and increase indent (with depth limit)
        if self.backend.context_stack().len() < MAX_DEPTH {
            self.backend.context_stack_mut().push(Context::MappingKey);
            self.indent_level += 1;
        }
    }

    fn end_mapping(&mut self) {
        self.backend.context_stack_mut().pop();
        self.indent_level = self.indent_level.saturating_sub(1);
    }

    fn emit_alias(&mut self, anchor_id: usize) {
        let ctx = self.current_context();

        // Handle pending newline
        if self.pending_newline {
            self.output.push('\n');
            self.pending_newline = false;
            self.last_char_newline = true;
        }

        // Write prefix based on context
        match ctx {
            Context::Sequence => {
                if self.first_item_after_dash {
                    self.first_item_after_dash = false;
                } else {
                    self.write_indent();
                }
                self.output.push_str("- ");
                self.last_char_newline = false;
            }
            Context::MappingKey => {
                self.write_indent();
            }
            Context::Root => {}
            Context::MappingValue => {
                if self.pending_space {
                    self.output.push(' ');
                    self.pending_space = false;
                    self.last_char_newline = false;
                }
            }
        }

        // Emit the alias reference
        self.output.push('*');
        if let Some(name) = self.backend.anchor_store().get(anchor_id) {
            self.output.push_str(name);
        } else {
            // Fallback: generate name directly into output
            let _ = write!(self.output, "anchor{anchor_id}");
        }
        self.last_char_newline = false;

        // Handle context transitions
        match ctx {
            Context::MappingKey => {
                self.output.push(':');
                if let Some(last) = self.backend.context_stack_mut().last_mut() {
                    *last = Context::MappingValue;
                }
                self.pending_space = true;
                // last_char_newline remains false
            }
            Context::MappingValue => {
                self.output.push('\n');
                self.last_char_newline = true;
                if let Some(last) = self.backend.context_stack_mut().last_mut() {
                    *last = Context::MappingKey;
                }
            }
            Context::Sequence | Context::Root => {
                self.output.push('\n');
                self.last_char_newline = true;
            }
        }
    }

    /// Derive YAML block scalar chomp indicator from content.
    ///
    /// - `"+"` (keep): value ends with two or more newlines
    /// - `"-"` (strip): value does not end with a newline
    /// - `""` (clip): value ends with exactly one newline
    fn chomp_indicator(value: &str) -> &'static str {
        if value.ends_with("\n\n") {
            "+"
        } else if !value.ends_with('\n') {
            "-"
        } else {
            ""
        }
    }

    /// Write indentation for block scalar content (literal/folded styles).
    ///
    /// Empty lines are emitted as bare `\n` (no trailing spaces) to match
    /// the non-streaming path in `emitter.rs`.
    fn write_block_scalar_lines(&mut self, value: &str) {
        let indent_chars = self.indent_level.saturating_mul(self.config.indent);

        // Track the last non-empty line position to handle keep (+) chomp.
        // value.lines() drops trailing empty entries produced by trailing newlines.
        let last_non_empty = value.trim_end_matches('\n');

        for line in value.lines() {
            // Blank lines inside block scalars must not receive indentation — that
            // would create trailing whitespace, which is a lint violation.
            if !line.is_empty() {
                if indent_chars <= INDENT_SPACES.len() {
                    self.output.push_str(&INDENT_SPACES[..indent_chars]);
                } else {
                    self.output.push_str(&" ".repeat(indent_chars));
                }
                self.output.push_str(line);
            }
            self.output.push('\n');
        }

        // For keep (+) chomp: value.lines() drops trailing empty entries.
        // After the last non-empty line, emit the extra blank lines that lines() skipped.
        // Example: "text\n\n" → lines() yields ["text"], but we need "text\n\n".
        // The loop above already emitted one \n after the last content line,
        // so we emit (trailing_count - 1) additional newlines.
        if value.ends_with("\n\n") {
            let trailing_count = value.len() - last_non_empty.len();
            for _ in 1..trailing_count {
                self.output.push('\n');
            }
        }
    }

    fn write_indent(&mut self) {
        if self.indent_level > 1 {
            let indent_chars = (self.indent_level - 1).saturating_mul(self.config.indent);

            if indent_chars <= INDENT_SPACES.len() {
                self.output.push_str(&INDENT_SPACES[..indent_chars]);
            } else {
                self.output.push_str(&" ".repeat(indent_chars));
            }
            self.last_char_newline = false;
        }
    }

    /// Completes formatting and returns the output string.
    pub fn finish(mut self) -> String {
        // Ensure output ends with newline
        if !self.output.is_empty() && !self.last_char_newline {
            self.output.push('\n');
        }
        self.output
    }
}