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