blib/lib/DMS/Parser/Emitter.pm untested

filter: Statementstmt 0.0% 0 / 538 Branchbran 0.0% 0 / 276 Conditioncond 0.0% 0 / 130 MC/DCmcdc 0.0% 0 / 76 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 1083 CC 139 SCAR 46.7
CC
139
Cov
0%
_emit_table_block
272.0
_emit_value_inline
272.0
_is_flow_safe
182.0
CRAP 107.1
1 package DMS::Parser::Emitter;
2 # DMS encode emitter — re-emit a parsed Document as DMS source.
3 #
4 # Mirrors the Rust reference (language/rust/crates/dms/src/lib.rs::encode).
5 # Pure Perl; no parser dependency at parse time. Used by both
6 # DMS::Parser::encode and DMS::Parser::XS::encode — the document shape
7 # is identical between the two backends, so the emitter walks them the
8 # same way.
9 #
10 # Contract (SPEC §encode):
11 # decode(encode(decode(source))) is data-equivalent to decode(source),
12 # has the same comments at the same attached paths, and uses the same
13 # literal forms for values where preserved (integer base, string form).
14 #
15 # Round-trip stability:
16 # encode(decode(encode(decode(source)))) is byte-equal to encode(decode(source)).
17 #
18 # SPEC v0.14 renamed to_dms/to_dms_lite to encode/encode_lite. The old
19 # names remain as deprecated aliases for one release.
20 #
21 # A Document is a hashref:
22 # { meta => undef|tied-hash, body => value, comments => [...],
23 # original_forms => [ [path_aref, lit_href], ... ] }
24  
25 use strict;
26 use warnings;
27 use utf8;
28 use Scalar::Util qw(blessed);
29 use POSIX qw(isnan isinf);
30 use Carp ();
31  
32 our $VERSION = '0.5.3';
33  
34 my $INDENT_STR = ' ';
35  
36 # Public entry point. $doc is the decode_document return value.
37 # SPEC §encode (v0.14): renamed from to_dms() to encode().
38 sub encode {
39 my ($doc) = @_;
40 return _emit($doc, 0);
41 }
42  
43 # Lite-mode entry point — emits canonical DMS source with no comments
44 # and no original-form preservation (decimal integers, basic-quoted
45 # strings). Mirrors the Rust reference's `encode_lite`. SPEC §encode.
46 #
47 # `decode(encode_lite(doc))` is data-equivalent to `doc`; it is
48 # *not* required to round-trip comments or literal forms.
49 sub encode_lite {
50 my ($doc) = @_;
51 return _emit($doc, 1);
52 }
53  
54 # Deprecated aliases (SPEC v0.14 renamed to_dms/to_dms_lite to
55 # encode/encode_lite). Kept for one release. Carp once per process to
56 # avoid flooding callers that loop.
57 { my $warned;
58 sub to_dms {
59 unless ($warned++) {
60 Carp::carp(
61 'DMS::Parser::Emitter::to_dms() is deprecated; use encode() instead. '
62 . 'SPEC v0.14 renamed to_dms() to encode().');
63 }
64 goto &encode;
65 }
66 }
67 { my $warned;
68 sub to_dms_lite {
69 unless ($warned++) {
70 Carp::carp(
71 'DMS::Parser::Emitter::to_dms_lite() is deprecated; use encode_lite() instead. '
72 . 'SPEC v0.14 renamed to_dms_lite() to encode_lite().');
73 }
74 goto &encode_lite;
75 }
76 }
77  
78 sub _emit {
79 my ($doc, $lite) = @_;
80 # SPEC §"Unordered tables": full-mode `encode` refuses to round-trip
81 # a Document that contains a DMS::Parser::UnorderedTable. The Document tree
82 # has no stable iteration order, so re-emission cannot be byte-stable.
83 # Lite mode is allowed (canonical emit, no order promise).
84 if (!$lite && _contains_unordered($doc->{body})) {
85 die "encode (full-mode round-trip) refuses Document with DMS::Parser::UnorderedTable; "
86 . "use decode_document (ordered) or encode_lite. SPEC §Unordered tables.\n";
87 }
88 if (!$lite && defined($doc->{meta}) && _contains_unordered($doc->{meta})) {
89 die "encode (full-mode round-trip) refuses Document with DMS::Parser::UnorderedTable; "
90 . "use decode_document (ordered) or encode_lite. SPEC §Unordered tables.\n";
91 }
92 my $self = bless {
93 out => '',
94 comments_by_path => {}, # path-key -> { leading=>[], trailing=>scalar/undef, floating=>[] }
95 forms_by_path => {}, # path-key -> $lit
96 lite => $lite ? 1 : 0,
97 doc => $doc,
98 }, __PACKAGE__;
99 # In lite mode, the per-path comment + original-form maps stay
100 # empty: the walk then emits canonical form even when `doc.comments`
101 # / `doc.original_forms` are populated. Mirrors the Rust emitter's
102 # `new_lite` constructor.
103 if (!$self->{lite}) {
104 # Bucket comments + original_forms by path-key (joined string).
105 for my $ac (@{ $doc->{comments} || [] }) {
106 my $pk = _path_key($ac->{path});
107 $self->{comments_by_path}{$pk} ||= { leading => [], inner => [], trailing => [], floating => [] };
108 my $entry = $self->{comments_by_path}{$pk};
109 my $pos = $ac->{position};
110 if ($pos eq 'leading') {
111 push @{ $entry->{leading} }, $ac->{comment};
112 } elsif ($pos eq 'inner') {
113 push @{ $entry->{inner} }, $ac->{comment};
114 } elsif ($pos eq 'trailing') {
115 push @{ $entry->{trailing} }, $ac->{comment};
116 } else {
117 push @{ $entry->{floating} }, $ac->{comment};
118 }
119 }
120 for my $pair (@{ $doc->{original_forms} || [] }) {
121 my ($p, $lit) = @$pair;
122 my $pk = _path_key($p);
123 $self->{forms_by_path}{$pk} = $lit if !exists $self->{forms_by_path}{$pk};
124 }
125 }
126  
127 $self->_emit_document;
128 return $self->{out};
129 }
130  
131 # --- path-key encoding ---
132 # A path is an arrayref of plain string segments (table keys) and
133 # DMS::Parser::Index objects (list indices). We encode each segment with a
134 # distinct prefix so the join is unambiguous (a string key "0" doesn't
135 # collide with index 0).
136 sub _path_key {
137 my ($p) = @_;
138 return join("\0", map {
139 ref($_) eq 'DMS::Parser::Index' ? "I:" . $$_ : "K:$_"
140 } @$p);
141 }
142  
143 sub _emit_document {
144 my $self = shift;
145 my $doc = $self->{doc};
146  
147 # Front matter: emit the `+++` block when meta is defined OR when
148 # any `__fm__`-prefixed comment exists. Spec §to_dms allows omitting
149 # an empty-meta block when no FM comments either, but emitting `+++\n+++\n`
150 # for an empty-meta doc with no FM comments would be wrong; the
151 # has_meta test below guards that.
152 # Lite mode emits no comments, so FM comments don't force a `+++`
153 # block — only an explicit `meta = Some(...)` does. Mirrors the
154 # Rust reference (lib.rs::emit_document `!self.lite && ...`).
155 my $has_fm_comments = 0;
156 if (!$self->{lite}) {
157 for my $ac (@{ $doc->{comments} || [] }) {
158 my $first = $ac->{path}[0];
159 if (defined($first) && !ref($first) && $first eq '__fm__') {
160 $has_fm_comments = 1; last;
161 }
162 }
163 }
164 my $fm_present = defined $doc->{meta};
165 if ($fm_present || $has_fm_comments) {
166 $self->{out} .= "+++\n";
167 my $fm_path = ['__fm__'];
168 if (defined $doc->{meta}) {
169 $self->_emit_table_block($doc->{meta}, $fm_path, 0);
170 } else {
171 $self->_emit_floating($fm_path, 0);
172 }
173 $self->{out} .= "+++\n\n";
174 }
175  
176 my $body_path = [];
177 my $body = $doc->{body};
178 if (_is_table($body)) {
179 $self->_emit_table_block($body, $body_path, 0);
180 } elsif (_is_list($body)) {
181 $self->_emit_list_block($body, $body_path, 0);
182 } else {
183 # Scalar root.
184 my $nc = $self->{comments_by_path}{ _path_key($body_path) };
185 if ($nc) {
186 for my $c (@{ $nc->{leading} }) {
187 $self->_emit_comment_line($c, 0);
188 }
189 }
190 $self->_emit_value_inline($body, $body_path);
191 $self->_emit_trailing_for($body_path);
192 $self->{out} .= "\n";
193 if ($nc) {
194 for my $c (@{ $nc->{floating} }) {
195 $self->_emit_comment_line($c, 0);
196 }
197 }
198 }
199 }
200  
201 sub _is_table {
202 my ($v) = @_;
203 return 0 if !defined $v;
204 # SPEC §"Unordered tables": DMS::Parser::UnorderedTable is a blessed hashref
205 # marker. Treat it as a table for emission purposes; the full-mode
206 # to_dms guard above prevents it from reaching here in round-trip.
207 if (blessed($v)) {
208 return ref($v) eq 'DMS::Parser::UnorderedTable';
209 }
210 return ref($v) eq 'HASH';
211 }
212  
213 sub _is_list {
214 my ($v) = @_;
215 return 0 if !defined $v;
216 return 0 if blessed($v);
217 return ref($v) eq 'ARRAY';
218 }
219  
220 sub _table_keys {
221 my ($t) = @_;
222 # Fast path: when the table is a Tie::IxHash, bypass tie magic and
223 # read the keys AV directly. The tied object is a blessed arrayref
224 # `[idx_hv_rv, keys_av_rv, vals_av_rv, iter]` per Tie::IxHash's
225 # documented internal shape. `keys %$t` works too but goes through
226 # every entry's mg_find — measurably slower on a 5000-pair tree.
227 my $tied = tied(%$t);
228 if ($tied && ref($tied) eq 'Tie::IxHash') {
229 return @{ $tied->[1] };
230 }
231 # DMS::Parser::UnorderedTable (plain blessed hash) or plain HV: arbitrary
232 # iteration order is the documented contract for lite mode.
233 return keys %$t;
234 }
235  
236 # Recursive walk: returns true if any nested table (or the value itself)
237 # is a DMS::Parser::UnorderedTable. Used by `to_dms` (full mode) to refuse
238 # round-trip on unordered Documents per SPEC §"Unordered tables".
239 sub _contains_unordered {
240 my ($v) = @_;
241 return 0 if !defined $v;
242 if (blessed($v)) {
243 # DMS::Parser::UnorderedTable is itself the marker — we don't need to
244 # walk into it because finding the outer one is enough; any
245 # nested UnorderedTable would still be detected via the body.
246 return 1 if ref($v) eq 'DMS::Parser::UnorderedTable';
247 # Other blessed sentinels (DMS::Parser::Integer, DMS::Parser::Bool, dates,
248 # DMS::Parser::Float) are leaves.
249 return 0;
250 }
251 if (ref($v) eq 'HASH') {
252 for my $k (keys %$v) {
253 next if $k eq "\0_keys";
254 return 1 if _contains_unordered($v->{$k});
255 }
256 return 0;
257 }
258 if (ref($v) eq 'ARRAY') {
259 for my $item (@$v) {
260 return 1 if _contains_unordered($item);
261 }
262 return 0;
263 }
264 return 0;
265 }
266  
267 sub _emit_table_block {
268 my ($self, $t, $path, $indent) = @_;
269 # Lite-mode hot path: no comments, no original_forms, so the per-kvpair
270 # path/path-key construction and comment-map lookups are pure overhead.
271 # Skipping them saves ~35% of emit wall time on a 5000-kvpair Helm
272 # chart values.yaml fixture (the path-building inner-array copy plus
273 # _path_key string-join was the dominant cost).
274 if ($self->{lite}) {
275 my $pad = $INDENT_STR x $indent;
276 for my $k (_table_keys($t)) {
277 my $v = $t->{$k};
278 my $r = ref($v);
279 # Inline the common scalar cases. The realistic fixture is
280 # >90% plain-string + a few bool/int values; dispatching to
281 # _emit_value_inline + _emit_string per kvpair was the
282 # dominant cost after the path-key skip.
283 if (!$r) {
284 my $key_fmt = ($k =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/)
285 ? $k : _format_key($k);
286 if ($v !~ /[\\"\x00-\x1F]/) {
287 $self->{out} .= "${pad}${key_fmt}: \"${v}\"\n";
288 } else {
289 $self->{out} .= "${pad}${key_fmt}: \"" . _escape_basic($v) . "\"\n";
290 }
291 next;
292 }
293 if ($r eq 'DMS::Parser::Bool') {
294 my $key_fmt = ($k =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/)
295 ? $k : _format_key($k);
296 $self->{out} .= $pad . $key_fmt . ': '
297 . ($$v ? "true\n" : "false\n");
298 next;
299 }
300 if ($r eq 'DMS::Parser::Integer') {
301 my $key_fmt = ($k =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/)
302 ? $k : _format_key($k);
303 $self->{out} .= "${pad}${key_fmt}: ${$v}\n";
304 next;
305 }
306 my $can_block =
307 (_is_table($v) && scalar(_table_keys($v))) ||
308 (_is_list($v) && scalar(@$v));
309 $self->{out} .= $pad;
310 $self->{out} .= _format_key($k);
311 $self->{out} .= ':';
312 if ($can_block) {
313 $self->{out} .= "\n";
314 if (_is_table($v)) {
315 $self->_emit_table_block($v, undef, $indent + 1);
316 } else {
317 $self->_emit_list_block($v, undef, $indent + 1);
318 }
319 } else {
320 $self->{out} .= ' ';
321 $self->_emit_value_inline($v, undef);
322 $self->{out} .= "\n";
323 }
324 }
325 return;
326 }
327 for my $k (_table_keys($t)) {
328 my $v = $t->{$k};
329 my $child_path = [ @$path, $k ];
330 my $child_pk = _path_key($child_path);
331 my $nc = $self->{comments_by_path}{$child_pk};
332 if ($nc) {
333 for my $c (@{ $nc->{leading} }) {
334 $self->_emit_comment_line($c, $indent);
335 }
336 }
337 my $has_trailing = $nc && @{ $nc->{trailing} };
338 my $has_inner = $self->_has_inner($child_path);
339 my $can_block =
340 (_is_table($v) && scalar(_table_keys($v))) ||
341 (_is_list($v) && scalar(@$v));
342 my $needs_block = $can_block && !($has_trailing && $self->_is_flow_safe($v, $child_path));
343 $self->{out} .= $INDENT_STR x $indent;
344 $self->{out} .= _format_key($k);
345 $self->{out} .= ':';
346 if ($needs_block) {
347 if ($has_inner) {
348 $self->{out} .= ' ';
349 $self->_emit_inner_for($child_path);
350 # Trim trailing space left by _emit_inner_for.
351 $self->{out} =~ s/ \z//;
352 }
353 $self->{out} .= "\n";
354 if (_is_table($v)) { $self->_emit_table_block($v, $child_path, $indent + 1); }
355 else { $self->_emit_list_block($v, $child_path, $indent + 1); }
356 } else {
357 $self->{out} .= ' ';
358 $self->_emit_inner_for($child_path);
359 $self->_emit_value_inline($v, $child_path);
360 $self->_emit_trailing_for($child_path);
361 $self->{out} .= "\n";
362 }
363 }
364 $self->_emit_floating($path, $indent);
365 }
366  
367 sub _emit_list_block {
368 my ($self, $items, $path, $indent) = @_;
369 if ($self->{lite}) {
370 my $pad = $INDENT_STR x $indent;
371 for (my $i = 0; $i < @$items; $i++) {
372 my $v = $items->[$i];
373 $self->{out} .= $pad;
374 $self->{out} .= '+';
375 if (_is_table($v) && scalar(_table_keys($v))) {
376 $self->{out} .= "\n";
377 $self->_emit_table_block($v, undef, $indent + 1);
378 } elsif (_is_list($v) && scalar(@$v)) {
379 $self->{out} .= "\n";
380 $self->_emit_list_block($v, undef, $indent + 1);
381 } else {
382 $self->{out} .= ' ';
383 $self->_emit_value_inline($v, undef);
384 $self->{out} .= "\n";
385 }
386 }
387 return;
388 }
389 for (my $i = 0; $i < @$items; $i++) {
390 my $v = $items->[$i];
391 my $child_path = [ @$path, DMS::Parser::Index->new($i) ];
392 my $child_pk = _path_key($child_path);
393 my $nc = $self->{comments_by_path}{$child_pk};
394 if ($nc) {
395 for my $c (@{ $nc->{leading} }) {
396 $self->_emit_comment_line($c, $indent);
397 }
398 }
399 $self->{out} .= $INDENT_STR x $indent;
400 $self->{out} .= '+';
401 my $has_inner = $self->_has_inner($child_path);
402 if (_is_table($v) && scalar(_table_keys($v))) {
403 if ($has_inner) {
404 $self->{out} .= ' ';
405 $self->_emit_inner_for($child_path);
406 $self->{out} =~ s/ \z//;
407 }
408 $self->_emit_trailing_for($child_path);
409 $self->{out} .= "\n";
410 $self->_emit_table_block($v, $child_path, $indent + 1);
411 } elsif (_is_list($v) && scalar(@$v)) {
412 if ($has_inner) {
413 $self->{out} .= ' ';
414 $self->_emit_inner_for($child_path);
415 $self->{out} =~ s/ \z//;
416 }
417 $self->_emit_trailing_for($child_path);
418 $self->{out} .= "\n";
419 $self->_emit_list_block($v, $child_path, $indent + 1);
420 } else {
421 $self->{out} .= ' ';
422 $self->_emit_inner_for($child_path);
423 $self->_emit_value_inline($v, $child_path);
424 $self->_emit_trailing_for($child_path);
425 $self->{out} .= "\n";
426 }
427 }
428 $self->_emit_floating($path, $indent);
429 }
430  
431 sub _emit_value_inline {
432 my ($self, $v, $path) = @_;
433 if (blessed($v)) {
434 my $cls = ref($v);
435 if ($cls eq 'DMS::Parser::Bool') { $self->{out} .= $v->value ? 'true' : 'false'; }
436 elsif ($cls eq 'DMS::Parser::Integer') { $self->_emit_integer($v, $path); }
437 elsif ($cls eq 'DMS::Parser::Float') { $self->_emit_float($v->value); }
438 elsif ($cls eq 'DMS::Parser::OffsetDateTime'
439 || $cls eq 'DMS::Parser::LocalDateTime'
440 || $cls eq 'DMS::Parser::LocalDate'
441 || $cls eq 'DMS::Parser::LocalTime') { $self->{out} .= $v->value; }
442 else { die "to_dms: unknown blessed class $cls"; }
443 return;
444 }
445 if (_is_list($v)) {
446 if (!@$v) { $self->{out} .= '[]'; return; }
447 $self->{out} .= '[';
448 my $lite = $self->{lite};
449 for (my $i = 0; $i < @$v; $i++) {
450 $self->{out} .= ', ' if $i > 0;
451 my $sub = $lite ? undef : [ @$path, DMS::Parser::Index->new($i) ];
452 $self->_emit_value_inline($v->[$i], $sub);
453 }
454 $self->{out} .= ']';
455 return;
456 }
457 if (_is_table($v)) {
458 my @keys = _table_keys($v);
459 if (!@keys) { $self->{out} .= '{}'; return; }
460 $self->{out} .= '{';
461 my $first = 1;
462 my $lite = $self->{lite};
463 for my $k (@keys) {
464 $self->{out} .= ', ' unless $first;
465 $first = 0;
466 $self->{out} .= _format_key($k);
467 $self->{out} .= ': ';
468 my $sub = $lite ? undef : [ @$path, $k ];
469 $self->_emit_value_inline($v->{$k}, $sub);
470 }
471 $self->{out} .= '}';
472 return;
473 }
474 # Plain scalar = string.
475 if (!defined $v) { die "to_dms: got undef value"; }
476 $self->_emit_string("$v", $path);
477 }
478  
479 sub _emit_integer {
480 my ($self, $iv, $path) = @_;
481 if ($self->{lite}) {
482 # DMS::Parser::Integer is `bless \$v, 'DMS::Parser::Integer'` where $v is an IV.
483 # Direct deref + string concat skips the bstr() method dispatch.
484 $self->{out} .= "${$iv}";
485 return;
486 }
487 my $lit_ref = $self->{forms_by_path}{ _path_key($path) };
488 if ($lit_ref && exists $lit_ref->{integer_lit}) {
489 $self->{out} .= $lit_ref->{integer_lit};
490 return;
491 }
492 # Default: canonical decimal. DMS::Parser::Integer's bstr stringifies the IV.
493 $self->{out} .= $iv->bstr;
494 }
495  
496 sub _emit_float {
497 my ($self, $f) = @_;
498 if (isnan($f)) { $self->{out} .= 'nan'; return; }
499 if (isinf($f)) { $self->{out} .= ($f > 0 ? 'inf' : '-inf'); return; }
500 # ryu-shortest equivalent: try increasing %.Ng until round-trip works.
501 for my $p (1..17) {
502 my $s = sprintf("%.${p}g", $f);
503 if (0 + $s == $f) {
504 $s =~ s/e\+/e/;
505 $s =~ s/e-0+(\d)/e-$1/;
506 $s =~ s/e0+(\d)/e$1/;
507 if ($s !~ /[.eE]/) { $s .= '.0'; }
508 $self->{out} .= $s;
509 return;
510 }
511 }
512 $self->{out} .= sprintf("%.17g", $f);
513 }
514  
515 sub _emit_string {
516 my ($self, $s, $path) = @_;
517 if ($self->{lite}) {
518 $self->{out} .= '"';
519 $self->{out} .= _escape_basic($s);
520 $self->{out} .= '"';
521 return;
522 }
523 my $lit_ref = $self->{forms_by_path}{ _path_key($path) };
524 my $form;
525 if ($lit_ref && exists $lit_ref->{string_form}) {
526 $form = $lit_ref->{string_form};
527 }
528 if (!$form || $form->{kind} eq 'basic') {
529 $self->{out} .= '"';
530 $self->{out} .= _escape_basic($s);
531 $self->{out} .= '"';
532 return;
533 }
534 if ($form->{kind} eq 'literal') {
535 $self->{out} .= "'";
536 $self->{out} .= $s;
537 $self->{out} .= "'";
538 return;
539 }
540 if ($form->{kind} eq 'heredoc') {
541 # The stored body is post-modifier. For idempotent modifiers this
542 # is fine, but `_fold_paragraphs` joins lines within a paragraph
543 # with spaces — so we pre-expand each `\n` to `\n\n` so the
544 # re-applied modifier preserves line boundaries on round-trip.
545 my $body = $s;
546 my $has_fold = 0;
547 for my $m (@{ $form->{modifiers} || [] }) {
548 if ($m->{name} eq '_fold_paragraphs') { $has_fold = 1; last; }
549 }
550 if ($has_fold) {
551 $body =~ s/\n/\n\n/g;
552 }
553 $self->_emit_heredoc($body, $form->{flavor}, $form->{label}, $form->{modifiers} || []);
554 return;
555 }
556 die "to_dms: unknown string form: $form->{kind}";
557 }
558  
559 sub _emit_heredoc {
560 my ($self, $body, $flavor, $label, $modifiers) = @_;
561 # Compute the kvpair's indent from the most recent newline in $self->{out}.
562 my $bytes = $self->{out};
563 my $last_nl = rindex($bytes, "\n");
564 my $line_start = $last_nl < 0 ? 0 : $last_nl + 1;
565 my $kv_indent_spaces = 0;
566 while ($line_start + $kv_indent_spaces < length($bytes)
567 && substr($bytes, $line_start + $kv_indent_spaces, 1) eq ' ') {
568 $kv_indent_spaces++;
569 }
570 my $body_indent_str = ' ' x ($kv_indent_spaces + length($INDENT_STR));
571 my $term_indent_str = $body_indent_str;
572 my $opener = ($flavor eq 'basic_triple') ? '"""' : "'''";
573 $self->{out} .= $opener;
574 $self->{out} .= $label if defined $label;
575 for my $m (@$modifiers) {
576 $self->{out} .= ' ';
577 $self->{out} .= $m->{name};
578 $self->{out} .= '(';
579 my $first = 1;
580 for my $a (@{ $m->{args} || [] }) {
581 $self->{out} .= ', ' unless $first;
582 $first = 0;
583 $self->_emit_modifier_arg($a);
584 }
585 $self->{out} .= ')';
586 }
587 $self->{out} .= "\n";
588 if (length($body) == 0) {
589 # nothing — terminator on its own line follows
590 } else {
591 for my $line (split /\n/, $body, -1) {
592 if (length($line) == 0) {
593 $self->{out} .= "\n";
594 } else {
595 $self->{out} .= $body_indent_str;
596 $self->{out} .= $line;
597 $self->{out} .= "\n";
598 }
599 }
600 }
601 $self->{out} .= $term_indent_str;
602 if (defined $label) {
603 $self->{out} .= $label;
604 } else {
605 $self->{out} .= ($flavor eq 'basic_triple') ? '"""' : "'''";
606 }
607 }
608  
609 sub _emit_modifier_arg {
610 my ($self, $v) = @_;
611 if (blessed($v)) {
612 my $cls = ref($v);
613 if ($cls eq 'DMS::Parser::Bool') { $self->{out} .= $v->value ? 'true' : 'false'; }
614 elsif ($cls eq 'DMS::Parser::Integer') { $self->{out} .= $v->bstr; }
615 elsif ($cls eq 'DMS::Parser::Float') { $self->_emit_float($v->value); }
616 elsif ($cls eq 'DMS::Parser::OffsetDateTime'
617 || $cls eq 'DMS::Parser::LocalDateTime'
618 || $cls eq 'DMS::Parser::LocalDate'
619 || $cls eq 'DMS::Parser::LocalTime') { $self->{out} .= $v->value; }
620 else { die "modifier arg: unknown blessed class $cls"; }
621 return;
622 }
623 if (_is_list($v)) { $self->{out} .= '[]'; return; }
624 if (_is_table($v)) { $self->{out} .= '{}'; return; }
625 # Plain scalar = string. Modifier args use basic-quoted always.
626 $self->{out} .= '"';
627 $self->{out} .= _escape_basic("$v");
628 $self->{out} .= '"';
629 }
630  
631 sub _emit_comment_line {
632 my ($self, $c, $indent) = @_;
633 my $text = $c->{content};
634 my $prefix = $INDENT_STR x $indent;
635 if (index($text, "\n") < 0) {
636 $self->{out} .= $prefix;
637 $self->{out} .= $text;
638 $self->{out} .= "\n";
639 return;
640 }
641 # Multi-line: only the first line gets re-indented; subsequent body
642 # lines keep their original whitespace verbatim.
643 my @lines = split /\n/, $text, -1;
644 for (my $i = 0; $i < @lines; $i++) {
645 if ($i == 0) {
646 $self->{out} .= $prefix;
647 $self->{out} .= $lines[$i];
648 } else {
649 $self->{out} .= "\n";
650 $self->{out} .= $lines[$i];
651 }
652 }
653 $self->{out} .= "\n";
654 }
655  
656 sub _emit_trailing_for {
657 my ($self, $path) = @_;
658 return if $self->{lite};
659 my $nc = $self->{comments_by_path}{ _path_key($path) };
660 return if !$nc || !@{ $nc->{trailing} };
661 my $first = 1;
662 for my $c (@{ $nc->{trailing} }) {
663 $self->{out} .= ($first ? ' ' : ' ');
664 $first = 0;
665 $self->{out} .= $c->{content};
666 }
667 }
668  
669 sub _emit_inner_for {
670 my ($self, $path) = @_;
671 return if $self->{lite};
672 my $nc = $self->{comments_by_path}{ _path_key($path) };
673 return if !$nc;
674 for my $c (@{ $nc->{inner} }) {
675 $self->{out} .= $c->{content};
676 $self->{out} .= ' ';
677 }
678 }
679  
680 sub _has_inner {
681 my ($self, $path) = @_;
682 return 0 if $self->{lite};
683 my $nc = $self->{comments_by_path}{ _path_key($path) };
684 return $nc && @{ $nc->{inner} };
685 }
686  
687 sub _emit_floating {
688 my ($self, $path, $indent) = @_;
689 return if $self->{lite};
690 my $nc = $self->{comments_by_path}{ _path_key($path) };
691 return if !$nc;
692 for my $c (@{ $nc->{floating} }) {
693 $self->_emit_comment_line($c, $indent);
694 }
695 }
696  
697 # Returns true if $v rooted at $path is safe to emit as a flow form: no
698 # heredoc strings (heredocs need their own line) and no descendant has
699 # an attached comment (flow has nowhere to put it). Used to decide
700 # flow-vs-block when a trailing comment forces flow form.
701 sub _is_flow_safe {
702 my ($self, $v, $path) = @_;
703 my $pk_prefix = _path_key($path);
704 # Any descendant comment ⇒ unsafe. Skipped in lite mode (no
705 # comments are emitted anyway). Mirrors Rust lib.rs::is_flow_safe.
706 if (!$self->{lite}) {
707 for my $ac (@{ $self->{doc}{comments} || [] }) {
708 next if scalar(@{ $ac->{path} }) <= scalar(@$path);
709 my $apk = _path_key($ac->{path});
710 my $prefix = $pk_prefix eq '' ? '' : "$pk_prefix\0";
711 if ($pk_prefix eq '') {
712 # any non-empty path is descendant of root
713 return 0;
714 } elsif (substr($apk, 0, length($prefix)) eq $prefix) {
715 return 0;
716 }
717 }
718 }
719 if (!ref($v) && !blessed($v)) {
720 # plain string: check heredoc form
721 my $lit = $self->{forms_by_path}{ _path_key($path) };
722 if ($lit && exists $lit->{string_form} && $lit->{string_form}{kind} eq 'heredoc') {
723 return 0;
724 }
725 return 1;
726 }
727 if (blessed($v)) { return 1; }
728 if (_is_list($v)) {
729 for (my $i = 0; $i < @$v; $i++) {
730 my $sub = [ @$path, DMS::Parser::Index->new($i) ];
731 return 0 if !$self->_is_flow_safe($v->[$i], $sub);
732 }
733 return 1;
734 }
735 if (_is_table($v)) {
736 for my $k (_table_keys($v)) {
737 my $sub = [ @$path, $k ];
738 return 0 if !$self->_is_flow_safe($v->{$k}, $sub);
739 }
740 return 1;
741 }
742 return 1;
743 }
744  
745 sub _escape_basic {
746 my ($s) = @_;
747 # Fast path: most strings need no escaping. Skip the per-char split
748 # if the string contains no `\`, no `"`, and no control chars.
749 return $s if $s !~ /[\\"\x00-\x1F]/;
750 my $out = '';
751 for my $ch (split //, $s) {
752 my $code = ord($ch);
753 if ($ch eq '\\') { $out .= '\\\\'; }
754 elsif ($ch eq '"') { $out .= '\\"'; }
755 elsif ($ch eq "\n") { $out .= '\\n'; }
756 elsif ($ch eq "\r") { $out .= '\\r'; }
757 elsif ($ch eq "\t") { $out .= '\\t'; }
758 elsif ($ch eq "\b") { $out .= '\\b'; }
759 elsif ($ch eq "\f") { $out .= '\\f'; }
760 elsif ($code < 0x20) { $out .= sprintf('\\u%04X', $code); }
761 else { $out .= $ch; }
762 }
763 return $out;
764 }
765  
766 sub _is_bare_key_char_emit {
767 my ($c) = @_;
768 return 1 if $c eq '_' || $c eq '-';
769 my $o = ord($c);
770 if ($o < 128) {
771 return $c =~ /[A-Za-z0-9]/;
772 }
773 # Match the parser's frozen Unicode 15.1 XID_Continue snapshot so that
774 # to_dms emits a key bare iff the parser would accept it bare. Avoids
775 # producing surface forms that drift with the host's Unicode tables.
776 require DMS::Parser;
777 return DMS::Parser::_is_xid_continue($o);
778 }
779  
780 sub _format_key {
781 my ($k) = @_;
782 # ASCII fast path. Real-world keys are >99% plain ASCII identifiers;
783 # the regex bails out at the first non-bare char without splitting
784 # the string into single-char SVs. Saves per-key allocations.
785 return $k if $k =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/;
786 if (length($k) > 0) {
787 my $bare = 1;
788 for my $ch (split //, $k) {
789 if (!_is_bare_key_char_emit($ch)) { $bare = 0; last; }
790 }
791 return $k if $bare;
792 }
793 # Quoted: prefer literal if no single quote, no LF/CR.
794 if (index($k, "'") < 0 && index($k, "\n") < 0 && index($k, "\r") < 0) {
795 return "'$k'";
796 }
797 return '"' . _escape_basic($k) . '"';
798 }
799  
800 1;
801  
802 __END__