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
//! 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;
/// 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.
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,
/// 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
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 => {
self.write_indent();
self.output.push_str("- ");
self.last_char_newline = false;
}
Context::MappingKey => {
self.write_indent();
}
// Root level scalar and mapping value need no prefix
Context::Root | Context::MappingValue => {}
}
// 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;
}
// Add space after colon for simple values
self.output.push(' ');
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_str("|-");
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_str(">-");
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 based on context
match ctx {
Context::Sequence => {
self.write_indent();
self.output.push_str("- ");
self.last_char_newline = false;
}
Context::MappingKey => {
// Sequence as mapping key - unusual but valid
self.write_indent();
}
Context::MappingValue => {
// Value position - newline and indent for nested sequence
self.output.push('\n');
self.last_char_newline = true;
}
Context::Root => {}
}
// Handle anchor (with bounds check for security)
self.emit_anchor_if_present(anchor_id, false);
// 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 based on context
match ctx {
Context::Sequence => {
self.write_indent();
self.output.push_str("- ");
self.last_char_newline = false;
}
Context::MappingKey => {
// Mapping as mapping key - unusual but valid (complex key)
self.write_indent();
}
Context::MappingValue => {
// Value position - newline for nested mapping
self.output.push('\n');
self.last_char_newline = true;
}
Context::Root => {}
}
// Handle anchor (with bounds check for security)
self.emit_anchor_if_present(anchor_id, 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 => {
self.write_indent();
self.output.push_str("- ");
self.last_char_newline = false;
}
Context::MappingKey => {
self.write_indent();
}
Context::Root | Context::MappingValue => {}
}
// 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.output.push(' ');
// 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;
}
}
}
/// Write indentation for block scalar content (literal/folded styles).
fn write_block_scalar_lines(&mut self, value: &str) {
let indent_chars = self.indent_level.saturating_mul(self.config.indent);
for line in value.lines() {
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');
}
}
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
}
}