blib/lib/DMS/XS/encoder.pl untested

filter: Statementstmt 0.0% 0 / 237 Branchbran 0.0% 0 / 108 Conditioncond 0.0% 0 / 30 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 401 CC 36 SCAR 51.8
CC
36
Cov
0%
encode_json_value
420.0
quote_json
90.0
shortest_float
42.0
CRAP 177.3
1 #!/usr/bin/env perl
2 # XS-backed DMS conformance encoder. Mirrors language/perl/encoder.pl
3 # byte-for-byte; the only difference is the parser module.
4 # With --roundtrip, instead emit DMS source via encode (round-trip mode).
5 use strict;
6 use warnings;
7 use utf8;
8 use FindBin;
9 use lib "$FindBin::Bin/lib";
10 use lib "$FindBin::Bin/blib/lib";
11 use lib "$FindBin::Bin/blib/arch";
12 use DMS::XS::Parser;
13 use Tie::IxHash;
14 use Scalar::Util qw(blessed looks_like_number);
15 use POSIX qw(isnan isinf);
16 use Time::HiRes ();
17
18 binmode(STDIN);
19 binmode(STDERR, ':utf8');
20
21 # CLI flag parsing — see encoder.pl (pure-Perl) for protocol notes.
22 # Mirrors Rust / Go reference encoders. SPEC: dms-tests/TESTS.md §3a.
23 my $roundtrip = 0;
24 my $bench_iters = 0;
25 my $bench_warmup = 3;
26 my $mode = defined $ENV{DMS_MODE} && $ENV{DMS_MODE} ne ''
27 ? $ENV{DMS_MODE} : 'full';
28 my $ignore_order = exists $ENV{DMS_IGNORE_ORDER} ? 1 : 0;
29 my $argi = 0;
30 while ($argi < @ARGV) {
31 my $arg = $ARGV[$argi];
32 if ($arg eq '--roundtrip') { $roundtrip = 1; }
33 elsif ($arg eq '--ignore-order') { $ignore_order = 1; }
34 elsif ($arg eq '--bench-iters') {
35 $bench_iters = $ARGV[++$argi] // 0;
36 }
37 elsif ($arg eq '--bench-warmup') {
38 $bench_warmup = $ARGV[++$argi] // 3;
39 }
40 elsif ($arg eq '--mode') {
41 $mode = $ARGV[++$argi] // 'full';
42 }
43 else { print STDERR "unknown arg: $arg\n"; exit 2; }
44 $argi++;
45 }
46 $bench_iters += 0;
47 $bench_warmup += 0;
48 if ($mode ne 'full' && $mode ne 'lite') {
49 print STDERR "0:0: --mode must be full|lite, got \"$mode\"\n";
50 exit 1;
51 }
52 my $lite = ($mode eq 'lite');
53
54 # Fast path: parse + JSON-emit happens entirely in C, including stdin
55 # slurp and stdout write. Skips two SV<->C buffer copies (input slurp
56 # into an SV, output SV that Perl `print`s) plus the SV/HV/AV/Tie::IxHash
57 # construction that decode_document does. For wide flat documents
58 # (flat50k bench) that round trip is the dominant cost. Set STDOUT to
59 # pure :raw — encode_stdin_to_stdout writes pre-validated UTF-8 bytes
60 # directly via PerlIO and we don't want the :utf8 layer to re-check or
61 # transcode them. The roundtrip path still needs the full Perl tree
62 # (comments, original_forms, etc.) so it falls through to decode_document
63 # below; that path keeps the :utf8 layer.
64 #
65 # encode_stdin_to_stdout internally calls dms_parse_document_lite — it's
66 # the lite-mode fast path. We take it only under DMS_MODE=lite so that
67 # DMS_MODE=full actually exercises the full parser (Tie::IxHash tables
68 # + comment AST + original_forms construction) on the conformance
69 # corpus. SPEC §"Parsing modes — full and lite".
70 #
71 # We bypass the C fast path when we need the parsed Document in Perl:
72 # - bench mode loops emit (needs $doc),
73 # - roundtrip needs specific emitters that operate on the Perl tree,
74 # - DMS_MODE=full needs the full parser path,
75 # - --ignore-order needs DMS::UnorderedTable wrapping in Perl.
76 # The C fast path handles empty stdin by emitting "{}" and exiting 0,
77 # which still satisfies the "empty stdin → exit 0" probe contract.
78 if (!$roundtrip && $bench_iters == 0 && !$ignore_order && $lite) {
79 binmode(STDOUT, ':raw');
80 eval { DMS::XS::Parser::encode_stdin_to_stdout(); };
81 if ($@) {
82 my $err = $@;
83 chomp $err;
84 print STDERR "$err\n";
85 exit 1;
86 }
87 exit 0;
88 }
89
90 binmode(STDOUT, ':raw:utf8'); # ':raw' disables Windows CRLF translation
91
92 my $src = do { local $/; <STDIN> };
93
94 # Empty stdin → exit 0 (startup probe; matches Go/Rust ref encoders).
95 # Reachable here only in bench / roundtrip paths; default path handled
96 # by the C fast path above.
97 if (!defined $src || $src =~ /\A\s*\z/) {
98 exit 0;
99 }
100
101 my $doc;
102 # SPEC §"Unordered tables": dispatch to the *_unordered entry point
103 # when --ignore-order is set. The XS C parser doesn't have a native
104 # unordered backing — the shim parses ordered, then walks the tree
105 # replacing every table with a DMS::UnorderedTable plain hashref. Front
106 # matter remains ordered (per spec).
107 #
108 # SPEC §"Parsing modes — full and lite": `--mode lite` (or DMS_MODE=lite)
109 # routes through decode_document_lite even on the tagged-JSON path. Tagged
110 # JSON is mode-invariant (same value tree); the dispatch lets conformance
111 # exercise both parsers under one driver.
112 eval {
113 if ($lite && $ignore_order) {
114 $doc = DMS::XS::Parser::decode_lite_document_unordered($src);
115 }
116 elsif ($lite) {
117 $doc = DMS::XS::Parser::decode_document_lite($src);
118 }
119 elsif ($ignore_order) {
120 $doc = DMS::XS::Parser::decode_document_unordered($src);
121 }
122 else {
123 $doc = DMS::XS::Parser::decode_document($src);
124 }
125 };
126 if ($@) {
127 my $err = $@;
128 chomp $err;
129 print STDERR "$err\n";
130 exit 1;
131 }
132
133 # Bench mode: parse once (above, untimed), loop the emit step. Default
134 # mode emits tagged JSON; --roundtrip emits via encode / encode_lite.
135 # See dms-tests/TESTS.md §3a.
136 if ($bench_iters > 0) {
137 run_bench($doc, $roundtrip, $lite, $bench_iters, $bench_warmup);
138 exit 0;
139 }
140
141 if ($roundtrip) {
142 my $out;
143 eval {
144 $out = $lite
145 ? DMS::XS::Parser::encode_lite($doc)
146 : DMS::XS::Parser::encode($doc);
147 1;
148 } or do {
149 my $err = $@;
150 chomp $err;
151 print STDERR "$err\n";
152 exit 1;
153 };
154 print $out;
155 exit 0;
156 }
157
158 # Default mode under bench-iters=0 doesn't reach here (handled by the C
159 # fast path above), but the bench loop's per-iter emit reuses the same
160 # tagged-JSON helpers below.
161 my $out;
162 if (!defined $doc->{meta}) {
163 $out = encode_json_value($doc->{body}, 0);
164 } else {
165 $out = encode_document_wrap($doc->{meta}, $doc->{body}, 0);
166 }
167 print "$out\n";
168 exit 0;
169
170 # One emit step for the bench loop. Discards the result — caller only
171 # cares about wall-time. Default-mode timing measures the Perl-level
172 # tagged-JSON path (not the C fast path); that's intentional: comparing
173 # the C fast path against languages that do all work in their host VM
174 # would be apples-to-oranges.
175 sub _bench_emit {
176 my ($doc, $roundtrip, $lite) = @_;
177 if ($roundtrip) {
178 return $lite
179 ? DMS::XS::Parser::encode_lite($doc)
180 : DMS::XS::Parser::encode($doc);
181 }
182 if (!defined $doc->{meta}) {
183 return encode_json_value($doc->{body}, 0);
184 }
185 return encode_document_wrap($doc->{meta}, $doc->{body}, 0);
186 }
187
188 sub run_bench {
189 my ($doc, $roundtrip, $lite, $iters, $warmup) = @_;
190 for (my $w = 0; $w < $warmup; $w++) {
191 my $s = _bench_emit($doc, $roundtrip, $lite);
192 my $_unused_w = length($s);
193 }
194 for (my $j = 0; $j < $iters; $j++) {
195 my $t0 = Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC());
196 my $s = _bench_emit($doc, $roundtrip, $lite);
197 my $t1 = Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC());
198 my $_unused = length($s);
199 my $ns = int(($t1 - $t0) * 1e9);
200 print "iter $j $ns\n";
201 }
202 }
203
204 sub encode_document_wrap {
205 my ($meta, $body, $indent) = @_;
206 my $pad = ' ' x $indent;
207 my $inner = ' ' x ($indent + 1);
208 my @parts;
209 push @parts, $inner . quote_json('_meta') . ': '
210 . encode_json_value($meta, $indent + 1);
211 push @parts, $inner . quote_json('_body') . ': '
212 . encode_json_value($body, $indent + 1);
213 return "{\n" . join(",\n", @parts) . "\n$pad}";
214 }
215
216 sub shortest_float {
217 my ($v) = @_;
218 if (isnan($v)) { return 'nan'; }
219 if (isinf($v)) { return $v > 0 ? 'inf' : '-inf'; }
220 for my $p (1..17) {
221 my $s = sprintf("%.${p}g", $v);
222 if (0 + $s == $v) {
223 $s =~ s/e\+/e/;
224 $s =~ s/e-0+(\d)/e-$1/;
225 $s =~ s/e0+(\d)/e$1/;
226 if ($s !~ /[.eE]/) { $s .= '.0'; }
227 return $s;
228 }
229 }
230 return sprintf("%.17g", $v);
231 }
232
233 sub quote_json {
234 my ($s) = @_;
235 my $out = '"';
236 for my $ch (split //, $s) {
237 my $code = ord($ch);
238 if ($ch eq '"') { $out .= '\\"'; }
239 elsif ($ch eq '\\') { $out .= '\\\\'; }
240 elsif ($ch eq "\n") { $out .= '\\n'; }
241 elsif ($ch eq "\r") { $out .= '\\r'; }
242 elsif ($ch eq "\t") { $out .= '\\t'; }
243 elsif ($ch eq "\b") { $out .= '\\b'; }
244 elsif ($ch eq "\f") { $out .= '\\f'; }
245 elsif ($code < 0x20) { $out .= sprintf('\\u%04x', $code); }
246 else { $out .= $ch; }
247 }
248 return $out . '"';
249 }
250
251 sub encode_json_value {
252 my ($v, $indent) = @_;
253 my $pad = ' ' x $indent;
254 my $inner = ' ' x ($indent + 1);
255 if (blessed($v)) {
256 my $cls = ref($v);
257 # SPEC §"Unordered tables": blessed plain hashref. Emit as a JSON
258 # object using whatever order Perl's hash returns (no stability).
259 if ($cls eq 'DMS::UnorderedTable') {
260 my @keys = keys %$v;
261 return '{}' if !@keys;
262 my @parts;
263 for (my $i = 0; $i < @keys; $i++) {
264 my $k = $keys[$i];
265 my $val = encode_json_value($v->{$k}, $indent + 1);
266 my $line = $inner . quote_json($k) . ': ' . $val;
267 $line .= ',' if $i < $#keys;
268 push @parts, $line;
269 }
270 return "{\n" . join("\n", @parts) . "\n$pad}";
271 }
272 if ($cls eq 'DMS::Bool') {
273 my $bv = $v->value ? 'true' : 'false';
274 return tagged_json('bool', $bv, $indent);
275 }
276 if ($cls eq 'DMS::Integer') {
277 return tagged_json('integer', $v->value->bstr, $indent);
278 }
279 if ($cls eq 'DMS::Float') {
280 return tagged_json('float', shortest_float($v->value), $indent);
281 }
282 if ($cls eq 'DMS::OffsetDateTime') {
283 return tagged_json('offset-datetime', $v->value, $indent);
284 }
285 if ($cls eq 'DMS::LocalDateTime') {
286 return tagged_json('local-datetime', $v->value, $indent);
287 }
288 if ($cls eq 'DMS::LocalDate') {
289 return tagged_json('local-date', $v->value, $indent);
290 }
291 if ($cls eq 'DMS::LocalTime') {
292 return tagged_json('local-time', $v->value, $indent);
293 }
294 die "unknown blessed value class $cls";
295 }
296 if (ref($v) eq 'HASH') {
297 my @keys = keys %$v;
298 return '{}' if !@keys;
299 my @parts;
300 for (my $i = 0; $i < @keys; $i++) {
301 my $k = $keys[$i];
302 my $val = encode_json_value($v->{$k}, $indent + 1);
303 my $line = $inner . quote_json($k) . ': ' . $val;
304 $line .= ',' if $i < $#keys;
305 push @parts, $line;
306 }
307 return "{\n" . join("\n", @parts) . "\n$pad}";
308 }
309 if (ref($v) eq 'ARRAY') {
310 return '[]' if !@$v;
311 my @parts;
312 for (my $i = 0; $i < @$v; $i++) {
313 my $val = encode_json_value($v->[$i], $indent + 1);
314 my $line = $inner . $val;
315 $line .= ',' if $i < $#$v;
316 push @parts, $line;
317 }
318 return "[\n" . join("\n", @parts) . "\n$pad]";
319 }
320 if (!defined($v)) { die "got undef value"; }
321 return tagged_json('string', "$v", $indent);
322 }
323
324 sub tagged_json {
325 my ($t, $v, $indent) = @_;
326 my $inner = ' ' x ($indent + 1);
327 my $pad = ' ' x $indent;
328 return "{\n${inner}\"type\": " . quote_json($t) . ",\n${inner}\"value\": " . quote_json($v) . "\n${pad}}";
329 }