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

filter: Statementstmt 0.0% 0 / 864 Branchbran 0.0% 0 / 402 Conditioncond 0.0% 0 / 155 MC/DCmcdc 0.0% 0 / 101 Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 1594 CC 202 SCAR 64.0
CC
202
Cov
0%
extract_imports
2550.0
resolve_call
210.0
_consume_flow_element
210.0
CRAP 600.4
1 package DMS::Parser::Tier1;
2 # Tier-1 decoder/encoder for DMS.
3 # Parses _dms_tier:1 documents: extracts imports, scans for decorator calls
4 # at the four position types (leading, inner, trailing, flow-inner), and
5 # emits tier-1 wrapper JSON.
6 #
7 # Design: two-pass.
8 # Pass 1 — source scan: split FM from body, parse FM, validate imports,
9 # scan body text for decorator tokens, record (position, path, call).
10 # Pass 2 — value parse: feed the decorator-stripped body to the tier-0
11 # parser; combine resulting value tree with decorator sidecar.
12 #
13 # The tier-0 parser currently rejects _dms_tier:1 in FM and also rejects
14 # reserved sigil chars at body value positions. We handle FM ourselves (pass 1)
15 # and strip decorator tokens before handing the body to the tier-0 parser.
16  
17 use strict;
18 use warnings;
19 use utf8;
20 use Encode qw(decode encode);
21  
22 our $VERSION = '0.5.3';
23  
24 # ── ASCII reserved decorator sigil characters ──────────────────────────────────
25 # (TIER1.md §"Tier-0 reserved decorator sigil set")
26 my %SIGIL_CHAR = map { $_ => 1 } split //, '!@$%^&*|~`.,><;?=';
27  
28 sub is_sigil_char { exists $SIGIL_CHAR{$_[0]} }
29  
30 # ── Extended_Pictographic ranges (frozen Unicode 15.1) ─────────────────────────
31 # Ported from dms-rs/crates/dms/src/lib.rs `EXTENDED_PICTOGRAPHIC_RANGES`.
32 my @EXTENDED_PICTOGRAPHIC_RANGES = (
33 [0x00A9, 0x00A9], [0x00AE, 0x00AE], [0x203C, 0x203C], [0x2049, 0x2049],
34 [0x2122, 0x2122], [0x2139, 0x2139], [0x2194, 0x2199], [0x21A9, 0x21AA],
35 [0x231A, 0x231B], [0x2328, 0x2328], [0x2388, 0x2388], [0x23CF, 0x23CF],
36 [0x23E9, 0x23F3], [0x23F8, 0x23FA], [0x24C2, 0x24C2], [0x25AA, 0x25AB],
37 [0x25B6, 0x25B6], [0x25C0, 0x25C0], [0x25FB, 0x25FE], [0x2600, 0x2605],
38 [0x2607, 0x2612], [0x2614, 0x2685], [0x2690, 0x2705], [0x2708, 0x2712],
39 [0x2714, 0x2714], [0x2716, 0x2716], [0x271D, 0x271D], [0x2721, 0x2721],
40 [0x2728, 0x2728], [0x2733, 0x2734], [0x2744, 0x2744], [0x2747, 0x2747],
41 [0x274C, 0x274C], [0x274E, 0x274E], [0x2753, 0x2755], [0x2757, 0x2757],
42 [0x2763, 0x2767], [0x2795, 0x2797], [0x27A1, 0x27A1], [0x27B0, 0x27B0],
43 [0x27BF, 0x27BF], [0x2934, 0x2935], [0x2B05, 0x2B07], [0x2B1B, 0x2B1C],
44 [0x2B50, 0x2B50], [0x2B55, 0x2B55], [0x3030, 0x3030], [0x303D, 0x303D],
45 [0x3297, 0x3297], [0x3299, 0x3299], [0x1F000, 0x1F0FF], [0x1F10D, 0x1F10F],
46 [0x1F12F, 0x1F12F], [0x1F16C, 0x1F171], [0x1F17E, 0x1F17F], [0x1F18E, 0x1F18E],
47 [0x1F191, 0x1F19A], [0x1F1AD, 0x1F1E5], [0x1F201, 0x1F20F], [0x1F21A, 0x1F21A],
48 [0x1F22F, 0x1F22F], [0x1F232, 0x1F23A], [0x1F23C, 0x1F23F], [0x1F249, 0x1F3FA],
49 [0x1F400, 0x1F53D], [0x1F546, 0x1F64F], [0x1F680, 0x1F6FF], [0x1F774, 0x1F77F],
50 [0x1F7D5, 0x1F7FF], [0x1F80C, 0x1F80F], [0x1F848, 0x1F84F], [0x1F85A, 0x1F85F],
51 [0x1F888, 0x1F88F], [0x1F8AE, 0x1F8FF], [0x1F90C, 0x1F93A], [0x1F93C, 0x1F945],
52 [0x1F947, 0x1FAFF], [0x1FC00, 0x1FFFD],
53 );
54  
55 # Binary search over @EXTENDED_PICTOGRAPHIC_RANGES.
56 sub _is_extended_pictographic {
57 my ($cp) = @_;
58 return 0 if $cp < 0xA9;
59 my ($lo, $hi) = (0, $#EXTENDED_PICTOGRAPHIC_RANGES);
60 while ($lo <= $hi) {
61 my $mid = int(($lo + $hi) / 2);
62 my ($rlo, $rhi) = @{$EXTENDED_PICTOGRAPHIC_RANGES[$mid]};
63 if ($cp < $rlo) { $hi = $mid - 1; }
64 elsif ($cp > $rhi) { $lo = $mid + 1; }
65 else { return 1; }
66 }
67 return 0;
68 }
69  
70 # True iff $cp is in the Reserved Emoji Set (SPEC/TIER1).
71 sub _is_reserved_emoji_codepoint {
72 my ($cp) = @_;
73 return 1 if $cp >= 0x1F1E6 && $cp <= 0x1F1FF; # Regional Indicators
74 return 1 if $cp >= 0x1F3FB && $cp <= 0x1F3FF; # Skin-tone modifiers
75 return 1 if $cp == 0x20E3; # Combining Enclosing Keycap
76 return _is_extended_pictographic($cp);
77 }
78  
79 sub _is_regional_indicator { my ($cp) = @_; $cp >= 0x1F1E6 && $cp <= 0x1F1FF }
80 sub _is_emoji_modifier { my ($cp) = @_; $cp >= 0x1F3FB && $cp <= 0x1F3FF }
81  
82 # Read one Reserved-Emoji extended grapheme cluster from a *character* string
83 # starting at character offset $pos. Returns the new position (past the cluster)
84 # or undef if no emoji cluster starts at $pos.
85 # The input $str must be a Perl character string (decoded Unicode).
86 sub _read_reserved_emoji_atom_char {
87 my ($str, $pos) = @_;
88 my $len = length($str);
89 return undef if $pos >= $len;
90  
91 my $c0 = substr($str, $pos, 1);
92 my $cp0 = ord($c0);
93 return undef unless _is_reserved_emoji_codepoint($cp0);
94  
95 my $end = $pos + 1;
96  
97 # Regional-indicator pair (UAX #29 GB12/GB13)
98 if (_is_regional_indicator($cp0)) {
99 if ($end < $len) {
100 my $c1 = substr($str, $end, 1);
101 if (_is_regional_indicator(ord($c1))) {
102 $end++;
103 }
104 }
105 return $end;
106 }
107  
108 # GB9/GB9a/GB11 loop: extend across modifiers, VS-16, keycap combiner, ZWJ+EP
109 while ($end < $len) {
110 my $c = substr($str, $end, 1);
111 my $cp = ord($c);
112 if (_is_emoji_modifier($cp) || $cp == 0xFE0F || $cp == 0x20E3) {
113 $end++;
114 next;
115 }
116 if ($cp == 0x200D) {
117 # ZWJ — continue only if followed by Extended_Pictographic
118 my $after_zwj = $end + 1;
119 if ($after_zwj < $len) {
120 my $nc = substr($str, $after_zwj, 1);
121 if (_is_extended_pictographic(ord($nc))) {
122 $end = $after_zwj + 1;
123 next;
124 }
125 }
126 last; # ZWJ not followed by E_P
127 }
128 last;
129 }
130 return $end;
131 }
132  
133 # True iff a sigil atom can start at character offset $pos in $str.
134 # An atom is either an ASCII sigil char or a Reserved-Emoji cluster start.
135 sub _is_sigil_atom_start {
136 my ($str, $pos) = @_;
137 return 0 if $pos >= length($str);
138 my $c = substr($str, $pos, 1);
139 return 1 if is_sigil_char($c);
140 return _is_reserved_emoji_codepoint(ord($c));
141 }
142  
143 # Consume one sigil atom from character string $str at position $pos.
144 # Returns new position (past the atom), or undef if not a sigil atom.
145 sub _consume_sigil_atom {
146 my ($str, $pos) = @_;
147 return undef if $pos >= length($str);
148 my $c = substr($str, $pos, 1);
149 if (is_sigil_char($c)) {
150 return $pos + 1;
151 }
152 return _read_reserved_emoji_atom_char($str, $pos);
153 }
154  
155 # Bare-key identifier chars (ASCII subset only — we only need this for
156 # the decorator name after the sigil, which must be ASCII ident).
157 sub _is_ident_start { defined($_[0]) && $_[0] =~ /[A-Za-z_]/ }
158 sub _is_ident_cont { defined($_[0]) && $_[0] =~ /[A-Za-z0-9_\-]/ }
159  
160 # ── Semver validation ──────────────────────────────────────────────────────────
161 # Accepts MAJOR.MINOR.PATCH with optional -pre and +build.
162 # Returns 1 on valid, 0 on invalid.
163 sub _valid_semver {
164 my ($s) = @_;
165 # Drop build metadata
166 $s =~ s/\+.*$//;
167 # Split pre-release
168 my ($core, $pre) = split /-/, $s, 2;
169 my @parts = split /\./, $core, -1;
170 return 0 unless @parts == 3;
171 for my $p (@parts) {
172 return 0 unless defined $p && $p =~ /^\d+$/;
173 return 0 if length($p) > 1 && substr($p, 0, 1) eq '0'; # leading zero
174 }
175 if (defined $pre) {
176 return 0 if $pre eq '';
177 for my $id (split /\./, $pre, -1) {
178 return 0 if $id eq '';
179 if ($id =~ /^\d+$/) {
180 return 0 if length($id) > 1 && substr($id, 0, 1) eq '0';
181 } else {
182 return 0 unless $id =~ /^[A-Za-z0-9\-]+$/;
183 }
184 }
185 }
186 return 1;
187 }
188  
189 # ── Import extraction and validation ──────────────────────────────────────────
190 # Extract and validate _dms_imports from a lite-mode parsed meta hashref.
191 # Returns arrayref of ImportSpec hashrefs, or dies with error message.
192 sub extract_imports {
193 my ($meta) = @_;
194  
195 # _dms_imports absent → valid empty
196 my $ORDER_KEY = "\0_keys";
197 my @meta_keys = $meta->{$ORDER_KEY} ? @{$meta->{$ORDER_KEY}} : ();
198 my $raw_list;
199 for my $k (@meta_keys) {
200 if ($k eq '_dms_imports') { $raw_list = $meta->{$k}; last; }
201 }
202 return [] unless defined $raw_list;
203  
204 # Must be a list
205 unless (ref($raw_list) eq 'ARRAY') {
206 die "0:0: _dms_imports must be a list\n";
207 }
208  
209 my @specs;
210 # collision tracking: set of (sigil, ns_repr, family) strings
211 my %seen_triples;
212  
213 for my $ei (0 .. $#$raw_list) {
214 my $entry = $raw_list->[$ei];
215 unless (ref($entry) eq 'HASH') {
216 die "0:0: _dms_imports[$ei] must be a table\n";
217 }
218 my @entry_keys = $entry->{$ORDER_KEY} ? @{$entry->{$ORDER_KEY}} : keys %$entry;
219 # Helper to get value from entry
220 my $get = sub { $entry->{$_[0]} };
221  
222 # dialect (required string)
223 my $dialect_v = $get->('dialect');
224 unless (defined $dialect_v && !ref($dialect_v)) {
225 if (!defined $dialect_v) {
226 die "0:0: _dms_imports[$ei] is missing required field 'dialect'\n";
227 }
228 die "0:0: _dms_imports[$ei].dialect must be a string\n";
229 }
230 my $dialect = "$dialect_v";
231 die "0:0: _dms_imports[$ei].dialect must be a non-empty string\n" unless length($dialect);
232  
233 # version (required string, semver shape, no range specifiers)
234 my $version_v = $get->('version');
235 unless (defined $version_v && !ref($version_v)) {
236 if (!defined $version_v) {
237 die "0:0: _dms_imports[$ei] is missing required field 'version'\n";
238 }
239 die "0:0: _dms_imports[$ei].version must be a string\n";
240 }
241 my $version = "$version_v";
242 die "0:0: _dms_imports[$ei].version must be a non-empty string\n" unless length($version);
243 # Reject range specifiers
244 my $vtrimmed = $version;
245 $vtrimmed =~ s/^\s+//;
246 if ($vtrimmed =~ /^[\^~><=]/ || $vtrimmed =~ /^>=/) {
247 die "0:0: range-specifier syntax in version not supported"
248 . " (_dms_imports[$ei].version \"$version\"):"
249 . " write a plain semver string\n";
250 }
251 unless (_valid_semver($version)) {
252 die "0:0: _dms_imports[$ei].version \"$version\" is not a valid semver string"
253 . " (expected MAJOR.MINOR.PATCH with optional -pre and +build)\n";
254 }
255  
256 # ns (optional string)
257 my $ns_v = $get->('ns');
258 my $ns;
259 if (defined $ns_v) {
260 unless (!ref($ns_v)) {
261 die "0:0: _dms_imports[$ei].ns must be a string\n";
262 }
263 $ns = "$ns_v";
264 die "0:0: _dms_imports[$ei].ns must be a non-empty string when present\n"
265 unless length($ns);
266 }
267  
268 # bind (optional table: sigil → list of family names)
269 my %bind;
270 my $bind_v = $get->('bind');
271 if (defined $bind_v) {
272 unless (ref($bind_v) eq 'HASH') {
273 die "0:0: _dms_imports[$ei].bind must be a table\n";
274 }
275 my @bind_keys = $bind_v->{$ORDER_KEY} ? @{$bind_v->{$ORDER_KEY}} : keys %$bind_v;
276 for my $sigil (@bind_keys) {
277 next if $sigil eq $ORDER_KEY;
278 # Validate sigil: each atom must be ASCII sigil char or Reserved-Emoji cluster
279 die "0:0: _dms_imports[$ei].bind has an empty sigil key\n" unless length($sigil);
280 {
281 my $spos = 0;
282 my $slen = length($sigil);
283 while ($spos < $slen) {
284 my $sc = substr($sigil, $spos, 1);
285 if ($sc eq '_') {
286 die "0:0: _dms_imports[$ei].bind key \"_\" (or containing '_') is invalid:"
287 . " underscore is not in the tier-0 reserved decorator sigil set\n";
288 }
289 my $new_pos = _consume_sigil_atom($sigil, $spos);
290 unless (defined $new_pos) {
291 die "0:0: _dms_imports[$ei].bind key \"$sigil\" contains '$sc'"
292 . " which is not in the tier-0 reserved decorator sigil set\n";
293 }
294 $spos = $new_pos;
295 }
296 }
297 # Value must be a list of strings
298 my $fams_v = $bind_v->{$sigil};
299 unless (ref($fams_v) eq 'ARRAY') {
300 die "0:0: _dms_imports[$ei].bind[\"$sigil\"] must be a list"
301 . " (use list form even for a single family)\n";
302 }
303 my @families;
304 for my $fv (@$fams_v) {
305 unless (defined $fv && !ref($fv)) {
306 die "0:0: _dms_imports[$ei].bind[\"$sigil\"] must be a list of strings\n";
307 }
308 push @families, "$fv";
309 }
310 $bind{$sigil} = \@families;
311 }
312 }
313  
314 # allow (optional table: family → list of names)
315 my %allow;
316 my $allow_v = $get->('allow');
317 if (defined $allow_v) {
318 unless (ref($allow_v) eq 'HASH') {
319 die "0:0: _dms_imports[$ei].allow must be a table\n";
320 }
321 my @ak = $allow_v->{$ORDER_KEY} ? @{$allow_v->{$ORDER_KEY}} : keys %$allow_v;
322 for my $fam (@ak) {
323 next if $fam eq $ORDER_KEY;
324 my $names_v = $allow_v->{$fam};
325 unless (ref($names_v) eq 'ARRAY') {
326 die "0:0: _dms_imports[$ei].allow[\"$fam\"] must be a list\n";
327 }
328 my @names;
329 for my $nv (@$names_v) {
330 unless (defined $nv && !ref($nv)) {
331 die "0:0: _dms_imports[$ei].allow[\"$fam\"] must be a list of strings\n";
332 }
333 push @names, "$nv";
334 }
335 $allow{$fam} = \@names;
336 }
337 }
338  
339 # deny (optional table: family → list of names)
340 my %deny;
341 my $deny_v = $get->('deny');
342 if (defined $deny_v) {
343 unless (ref($deny_v) eq 'HASH') {
344 die "0:0: _dms_imports[$ei].deny must be a table\n";
345 }
346 my @dk = $deny_v->{$ORDER_KEY} ? @{$deny_v->{$ORDER_KEY}} : keys %$deny_v;
347 for my $fam (@dk) {
348 next if $fam eq $ORDER_KEY;
349 my $names_v = $deny_v->{$fam};
350 unless (ref($names_v) eq 'ARRAY') {
351 die "0:0: _dms_imports[$ei].deny[\"$fam\"] must be a list\n";
352 }
353 my @names;
354 for my $nv (@$names_v) {
355 unless (defined $nv && !ref($nv)) {
356 die "0:0: _dms_imports[$ei].deny[\"$fam\"] must be a list of strings\n";
357 }
358 push @names, "$nv";
359 }
360 $deny{$fam} = \@names;
361 }
362 }
363  
364 # allow/deny mutual exclusion per family
365 for my $fam (keys %allow) {
366 if (exists $deny{$fam}) {
367 die "0:0: _dms_imports[$ei]: family \"$fam\" appears in both"
368 . " 'allow' and 'deny' — they are mutually exclusive for the same family\n";
369 }
370 }
371  
372 # alias (optional table: family → table: alias → canonical)
373 my %alias;
374 my $alias_v = $get->('alias');
375 if (defined $alias_v) {
376 unless (ref($alias_v) eq 'HASH') {
377 die "0:0: _dms_imports[$ei].alias must be a table\n";
378 }
379 my @afk = $alias_v->{$ORDER_KEY} ? @{$alias_v->{$ORDER_KEY}} : keys %$alias_v;
380 for my $fam (@afk) {
381 next if $fam eq $ORDER_KEY;
382 my $inner_v = $alias_v->{$fam};
383 unless (ref($inner_v) eq 'HASH') {
384 die "0:0: _dms_imports[$ei].alias[\"$fam\"] must be a table (alias → canonical)\n";
385 }
386 my @ik = $inner_v->{$ORDER_KEY} ? @{$inner_v->{$ORDER_KEY}} : keys %$inner_v;
387 my %inner_map;
388 for my $alias_name (@ik) {
389 next if $alias_name eq $ORDER_KEY;
390 my $canon_v = $inner_v->{$alias_name};
391 unless (defined $canon_v && !ref($canon_v)) {
392 die "0:0: _dms_imports[$ei].alias[\"$fam\"][\"$alias_name\"] must be a string\n";
393 }
394 $inner_map{$alias_name} = "$canon_v";
395 }
396 $alias{$fam} = \%inner_map;
397 }
398 }
399  
400 # Cross-import collision check: (sigil, ns_repr, family) must be unique
401 my $ns_repr = defined $ns ? $ns : '<unset>';
402 for my $sigil (keys %bind) {
403 for my $family (@{$bind{$sigil}}) {
404 my $triple = "$sigil\0$ns_repr\0$family";
405 if (exists $seen_triples{$triple}) {
406 my $prev_idx = $seen_triples{$triple};
407 my $prev = $specs[$prev_idx];
408 die "0:0: Decorator binding collision on (sigil='$sigil', ns=$ns_repr,"
409 . " family='$family'): import #$prev_idx dialect '${\$prev->{dialect}}'"
410 . " v${\$prev->{version}} and import #$ei dialect '$dialect' v$version"
411 . " both bind '$sigil' → '$family'. Resolve by remapping one.\n";
412 }
413 $seen_triples{$triple} = $ei;
414 }
415 }
416  
417 push @specs, {
418 dialect => $dialect,
419 version => $version,
420 ns => $ns, # undef if absent
421 bind => \%bind,
422 allow => \%allow,
423 deny => \%deny,
424 alias => \%alias,
425 };
426 }
427  
428 return \@specs;
429 }
430  
431 # ── Decorator call lexer ───────────────────────────────────────────────────────
432 # Lex a decorator call from string $s starting at offset $pos.
433 # Returns (sigil, ns_or_undef, fn_name, params_text, end_pos) or undef on failure.
434 # params_text is everything inside the outermost (...), without the parens.
435 # Multiple param groups handled by the caller (we lex only one at a time).
436 #
437 # On entry, $s[$pos] must be the first sigil char.
438 # Bound sigils come from the imports array (longest-match).
439 sub _lex_decorator_call {
440 my ($s, $pos, $bound_sigils) = @_;
441 my $len = length($s);
442  
443 # Consume sigil atoms (ASCII sigil chars and/or Reserved-Emoji clusters)
444 my $sig_start = $pos;
445 while ($pos < $len) {
446 my $new_pos = _consume_sigil_atom($s, $pos);
447 last unless defined $new_pos;
448 $pos = $new_pos;
449 }
450 my $raw_sigil = substr($s, $sig_start, $pos - $sig_start);
451 return undef unless length($raw_sigil);
452  
453 # Match longest registered prefix
454 my $sigil = undef;
455 for my $bs (sort { length($b) <=> length($a) } @$bound_sigils) {
456 if (substr($raw_sigil, 0, length($bs)) eq $bs) {
457 $sigil = $bs;
458 last;
459 }
460 }
461 return undef unless defined $sigil;
462 # Rewind to after sigil
463 $pos = $sig_start + length($sigil);
464  
465 # Consume identifier (name or ns.name)
466 return undef unless $pos < $len && _is_ident_start(substr($s, $pos, 1));
467 my $name_start = $pos;
468 while ($pos < $len && _is_ident_cont(substr($s, $pos, 1))) {
469 $pos++;
470 }
471 my $first_name = substr($s, $name_start, $pos - $name_start);
472  
473 my ($ns, $fn_name);
474 if ($pos < $len && substr($s, $pos, 1) eq '.') {
475 # Qualified: ns.fn_name
476 $pos++;
477 return undef unless $pos < $len && _is_ident_start(substr($s, $pos, 1));
478 my $fn_start = $pos;
479 while ($pos < $len && _is_ident_cont(substr($s, $pos, 1))) {
480 $pos++;
481 }
482 $ns = $first_name;
483 $fn_name = substr($s, $fn_start, $pos - $fn_start);
484 } else {
485 $ns = undef;
486 $fn_name = $first_name;
487 }
488  
489 # Collect param groups: zero or more (...) immediately following
490 my @param_groups;
491 while ($pos < $len && substr($s, $pos, 1) eq '(') {
492 my ($params_text, $new_pos) = _lex_balanced_parens($s, $pos);
493 return undef unless defined $params_text;
494 push @param_groups, $params_text;
495 $pos = $new_pos;
496 }
497 # If no explicit parens, one empty Named group
498 if (!@param_groups) {
499 push @param_groups, ''; # bare name → empty named group
500 }
501  
502 return ($sigil, $ns, $fn_name, \@param_groups, $pos);
503 }
504  
505 # Lex balanced parentheses starting at $pos (which must be '(').
506 # Returns (inner_text, pos_after_close) or (undef, undef) on error.
507 # String-aware: skips " " and ' ' content, handles \" \' escapes.
508 sub _lex_balanced_parens {
509 my ($s, $pos) = @_;
510 my $len = length($s);
511 return (undef, undef) unless substr($s, $pos, 1) eq '(';
512 $pos++; # consume opening '('
513 my $depth = 1;
514 my $start = $pos;
515 while ($pos < $len && $depth > 0) {
516 my $c = substr($s, $pos, 1);
517 if ($c eq '"') {
518 $pos++;
519 while ($pos < $len) {
520 my $ic = substr($s, $pos, 1);
521 if ($ic eq '\\') { $pos += 2; next; }
522 if ($ic eq '"') { $pos++; last; }
523 $pos++;
524 }
525 } elsif ($c eq "'") {
526 $pos++;
527 while ($pos < $len) {
528 my $ic = substr($s, $pos, 1);
529 if ($ic eq "'") { $pos++; last; }
530 $pos++;
531 }
532 } elsif ($c eq '(') {
533 $depth++;
534 $pos++;
535 } elsif ($c eq ')') {
536 $depth--;
537 $pos++ unless $depth == 0;
538 last if $depth == 0;
539 } else {
540 $pos++;
541 }
542 }
543 return (undef, undef) if $depth != 0; # unbalanced
544 my $inner = substr($s, $start, $pos - $start);
545 $pos++; # consume closing ')'
546 return ($inner, $pos);
547 }
548  
549 # ── Param group parsing ────────────────────────────────────────────────────────
550 # Parse the interior of one param group as either named (flow-table) or
551 # positional (flow-array), using the tier-0 parser.
552 # Returns a ParamGroup hashref: {kind => 'named'|'positional', value => ...}
553 sub _parse_param_group {
554 my ($inner) = @_;
555 # Empty inner → named with empty value
556 my $trimmed = $inner;
557 $trimmed =~ s/^\s+|\s+$//g;
558 if ($trimmed eq '') {
559 return { kind => 'named', value => {} };
560 }
561  
562 # Determine mode by first non-whitespace token:
563 # If it looks like `ident:` or `"key":` → named (flow-table)
564 # Otherwise → positional (flow-array)
565 my $is_named = _looks_like_named($trimmed);
566  
567 if ($is_named) {
568 # Parse as flow table: `k: { <inner> }` using the tier-0 parser
569 my $val = eval {
570 require DMS::Parser;
571 DMS::Parser::decode_lite_document("k: { $inner }")->{body}{k};
572 };
573 if ($@ || !defined $val) {
574 $val = {};
575 }
576 return { kind => 'named', value => $val };
577 } else {
578 # Parse as flow array: `k: [<inner>]`
579 my $val = eval {
580 require DMS::Parser;
581 DMS::Parser::decode_lite_document("k: [$inner]")->{body}{k};
582 };
583 if ($@ || !ref($val) || ref($val) ne 'ARRAY') {
584 $val = [];
585 }
586 return { kind => 'positional', value => $val };
587 }
588 }
589  
590 sub _looks_like_named {
591 my ($s) = @_;
592 # Named if first token is `ident:` or `"key":` etc.
593 $s =~ s/^\s+//;
594 # Quoted key
595 if ($s =~ /^"/) { return 1 if $s =~ /^"(?:[^"\\]|\\.)*"\s*:/; return 0; }
596 if ($s =~ /^'/) { return 1 if $s =~ /^'[^']*'\s*:/; return 0; }
597 # Bare key
598 return 1 if $s =~ /^[A-Za-z_][A-Za-z0-9_\-]*\s*:/;
599 return 0;
600 }
601  
602  
603 # ── Family resolution ─────────────────────────────────────────────────────────
604 # Resolve sigil + fn_name through imports.
605 # Returns (family, canonical_fn) or dies.
606 sub resolve_call {
607 my ($sigil, $ns, $fn_name, $imports) = @_;
608  
609 # Filter imports by ns
610 my @cand;
611 if (defined $ns) {
612 @cand = grep { defined($_->{ns}) && $_->{ns} eq $ns } @$imports;
613 die "0:0: unknown namespace '$ns'\n" unless @cand;
614 } else {
615 @cand = @$imports;
616 }
617  
618 my @accepted; # (family, canonical)
619 for my $imp (@cand) {
620 my $families = $imp->{bind}{$sigil};
621 next unless defined $families;
622 for my $fam (@$families) {
623 # Alias resolution
624 my $alias_map = $imp->{alias}{$fam};
625 my $canonical;
626 if ($alias_map) {
627 if (exists $alias_map->{$fn_name}) {
628 $canonical = $alias_map->{$fn_name};
629 } else {
630 # Check if fn_name is a canonical that has an alias
631 my ($alias_key) = grep { $alias_map->{$_} eq $fn_name } keys %$alias_map;
632 if (defined $alias_key) {
633 die "0:0: '$fn_name' must be written as '$alias_key' (alias declared in import)\n";
634 }
635 $canonical = $fn_name;
636 }
637 } else {
638 $canonical = $fn_name;
639 }
640  
641 # Allow/deny check
642 my $ok;
643 if (my $allow = $imp->{allow}{$fam}) {
644 $ok = grep { $_ eq $canonical } @$allow;
645 } elsif (my $deny = $imp->{deny}{$fam}) {
646 $ok = !(grep { $_ eq $canonical } @$deny);
647 if (!$ok) {
648 die "0:0: fn '$canonical' is in the deny list for family '$fam'\n";
649 }
650 } else {
651 $ok = 1;
652 }
653 push @accepted, { family => $fam, canonical => $canonical } if $ok;
654 }
655 }
656  
657 if (!@accepted) {
658 die "0:0: name '$fn_name' not found in any family bound to sigil '$sigil'\n";
659 }
660 if (@accepted > 1) {
661 # Collapse: if all agree on family+canonical, unambiguous
662 my $first = $accepted[0];
663 my $ambiguous = grep {
664 $_->{family} ne $first->{family} || $_->{canonical} ne $first->{canonical}
665 } @accepted;
666 if ($ambiguous) {
667 my @fams = do { my %s; grep { !$s{$_->{family}}++ } @accepted };
668 my $flist = join(', ', map { "'$_->{family}'" } @fams);
669 die "0:0: name '$fn_name' is ambiguous between families $flist under sigil '$sigil';"
670 . " qualify as |<ns>.$fn_name(...)\n";
671 }
672 }
673  
674 return ($accepted[0]{family}, $accepted[0]{canonical});
675 }
676  
677 # ── Source-level decorator scanner ────────────────────────────────────────────
678 # Given the body source text and the bound sigils, scan for decorator calls
679 # and record them with their positions.
680 #
681 # Returns:
682 # $clean_body — body text with decorator tokens removed (for tier-0 parsing)
683 # $raw_decorators — arrayref of raw decorator records:
684 # { position => 'leading'|'inner'|'trailing'|'floating',
685 # sigil => ..., ns => ..., fn_name => ..., param_groups => [...],
686 # path_hint => 'before:<key>' | 'at:<key>' | 'flow_index:<n>' | ... }
687 # (path_hint is a string hint used to map to the final path after parsing)
688 #
689 # Strategy: process line by line.
690 # - A line starting with a sigil char (after indent) → leading decorator
691 # - After `key: ` or `+ `, a sigil char → inner decorator; value follows
692 # - After a value on a `key:` or `+` line, a sigil char → trailing
693 # - Inside `[...]`, a sigil char before a value → flow-inner
694 #
695 # We do a single-pass scan using a state machine over the source characters.
696  
697 sub scan_body {
698 my ($body_src, $imports, $line_offset) = @_;
699 $line_offset //= 0;
700  
701 # Build list of all bound sigils from all imports
702 my %all_sigils;
703 for my $imp (@$imports) {
704 $all_sigils{$_} = 1 for keys %{$imp->{bind}};
705 }
706 my @bound_sigils = sort { length($b) <=> length($a) } keys %all_sigils;
707  
708 # We process the body text character-by-character, tracking context.
709 # For simplicity, we process line-by-line for block context and
710 # character-by-character within flow expressions.
711  
712 my @lines = split /\n/, $body_src, -1;
713 my @raw_decs;
714 my @clean_lines;
715 my $cur_line = $line_offset;
716  
717 # State: accumulated leading decorators waiting to attach to next key
718 my @pending_leading;
719  
720 for my $li (0 .. $#lines) {
721 my $line = $lines[$li];
722 $cur_line++;
723  
724 # Check if line is a decorator-only line (leading position)
725 # A leading decorator line starts with optional whitespace then a sigil atom
726 # (ASCII sigil char or Reserved-Emoji cluster start).
727 my $_leading_indent = '';
728 $_leading_indent = $1 if $line =~ /^([ \t]*)/;
729 my $_rest_for_check = substr($line, length($_leading_indent));
730 if (length($_rest_for_check) > 0 && _is_sigil_atom_start($_rest_for_check, 0)) {
731 my $indent = $_leading_indent;
732 my $rest = $_rest_for_check;
733 # Try to lex a decorator call
734 my ($sig, $ns, $fn, $pgs, $end) = eval {
735 _lex_decorator_call($rest, 0, \@bound_sigils);
736 };
737 if (defined $sig) {
738 # Check remainder after the call is empty (or whitespace/comment)
739 my $after = substr($rest, $end);
740 $after =~ s/^\s+//;
741 if ($after eq '' || $after =~ /^[#\/]/) {
742 # This is a leading decorator line
743 push @pending_leading, {
744 position => 'leading',
745 sigil => $sig,
746 ns => $ns,
747 fn_name => $fn,
748 param_groups => $pgs,
749 line => $cur_line,
750 indent => length($indent),
751 };
752 push @clean_lines, ''; # remove line
753 next;
754 }
755 }
756 }
757  
758 # Not a leading decorator — process as regular content
759 # First, flush pending_leading to the first key on this line
760 my $processed = _process_line($line, \@bound_sigils, \@pending_leading,
761 \@raw_decs, $cur_line, $li, \@lines);
762 push @clean_lines, $processed;
763 @pending_leading = (); # reset after each non-decorator line
764 }
765  
766 my $clean_body = join("\n", @clean_lines);
767 return ($clean_body, \@raw_decs);
768 }
769  
770 # Process one non-leading-only line: handle inner, trailing, and flow-inner
771 # decorators. Returns the cleaned line text.
772 sub _process_line {
773 my ($line, $bound_sigils, $pending_leading, $raw_decs, $cur_line, $li, $all_lines) = @_;
774  
775 # Detect line type: kvpair (`key: ...`), list item (`+ ...`), or other
776 # Check for: indent + key + ':' + ' '
777 if ($line =~ /^([ \t]*)([A-Za-z_"][^\n]*?:)[ \t](.*)$/ ||
778 $line =~ /^([ \t]*)(\+)[ \t](.*)$/) {
779 my $indent_str = $1;
780 my $key_part = $2;
781 my $value_part = $3;
782 my $indent = length($indent_str);
783 my $is_list_item = ($key_part eq '+');
784  
785 # Try to extract key name for path purposes
786 my $key_name = undef;
787 if (!$is_list_item) {
788 # Extract key from key_part (strip trailing ':')
789 my $kp = $key_part;
790 $kp =~ s/:$//;
791 $kp =~ s/^\s+|\s+$//g;
792 # Remove quotes if quoted
793 $kp =~ s/^"(.*)"$/$1/ || $kp =~ s/^'(.*)'$/$1/;
794 $key_name = $kp;
795 }
796  
797 # Check if value_part starts with a sigil (inner decoration)
798 my $clean_value = $value_part;
799 my $inner_dec = undef;
800 my $decoration_only = 0; # true if inner dec leaves no explicit value
801  
802 if (length($value_part) > 0 && _is_sigil_atom_start($value_part, 0)) {
803 # Try to lex decorator call at start of value_part
804 my ($sig, $ns, $fn, $pgs, $end) = eval {
805 _lex_decorator_call($value_part, 0, $bound_sigils);
806 };
807 if (defined $sig) {
808 $inner_dec = {
809 position => 'inner',
810 sigil => $sig,
811 ns => $ns,
812 fn_name => $fn,
813 param_groups => $pgs,
814 line => $cur_line,
815 indent => $indent,
816 key_name => $key_name,
817 is_list_item => $is_list_item,
818 };
819 # Strip the decorator from value_part
820 my $rest = substr($value_part, $end);
821 $rest =~ s/^\s+//;
822 $rest =~ s/\s+$//;
823 if ($rest eq '' || $rest =~ /^[#\/]/) {
824 # Decoration-only: no explicit value after decorator
825 # Use {} as placeholder so tier-0 parser gets a valid value
826 $clean_value = '{}';
827 $decoration_only = 1;
828 } else {
829 $clean_value = $rest;
830 }
831 }
832 }
833  
834 # Check for trailing decoration: after the value, a sigil char appears
835 my $trailing_dec = undef;
836 if (defined $inner_dec) {
837 # Look for trailing on the remaining value
838 ($clean_value, $trailing_dec) = _extract_trailing($clean_value, $bound_sigils,
839 $cur_line, $indent, $key_name, $is_list_item);
840 } else {
841 ($clean_value, $trailing_dec) = _extract_trailing($value_part, $bound_sigils,
842 $cur_line, $indent, $key_name, $is_list_item);
843 }
844  
845 # Check if value_part has flow-array content with inner decorators
846 # (e.g., `[1, |tag() 2, 3]`)
847 my ($final_value, $flow_decs) = _extract_flow_decorators(
848 $clean_value, $bound_sigils, $cur_line, $indent, $key_name, $is_list_item
849 );
850  
851 # Rebuild the line
852 my $new_line;
853 if ($is_list_item) {
854 $new_line = "$indent_str+ $final_value";
855 } else {
856 $new_line = "$indent_str$key_part $final_value";
857 }
858  
859 # Record decorators with key_name/path hints
860 # Flush pending leading onto this key
861 for my $ld (@$pending_leading) {
862 $ld->{key_name} = $key_name;
863 $ld->{is_list_item} = $is_list_item;
864 push @$raw_decs, $ld;
865 }
866 push @$raw_decs, $inner_dec if defined $inner_dec;
867 push @$raw_decs, $trailing_dec if defined $trailing_dec;
868 push @$raw_decs, @$flow_decs;
869  
870 return $new_line;
871 }
872  
873 # Non-kvpair line: just return as-is
874 # Flush any pending leading (they were floating, but we won't handle that now)
875 return $line;
876 }
877  
878 # Extract a trailing decorator from the end of a value string.
879 # Returns ($clean_value, $dec_or_undef).
880 sub _extract_trailing {
881 my ($val, $bound_sigils, $cur_line, $indent, $key_name, $is_list_item) = @_;
882  
883 # Strip trailing comment
884 my $comment = '';
885 if ($val =~ s/(\s*(?:#|\/\/).*?)$//) {
886 $comment = $1;
887 }
888  
889 # Check if, after the value, there's a sigil (trailing decorator).
890 # The value is everything before any trailing whitespace+sigil.
891 # We need to parse from right-to-left: find a sigil run after whitespace.
892 # Pattern: `<value> <sigil_chars><ident>[(...)]`
893 #
894 # Try: scan for the last space+sigil sequence (ASCII or emoji sigil atom)
895 if ($val =~ /^(.*?)(\s+)(\S.*)$/) {
896 my $value_part = $1;
897 my $ws = $2;
898 my $sigil_rest = $3;
899 # Only proceed if sigil_rest starts with a sigil atom
900 unless (_is_sigil_atom_start($sigil_rest, 0)) {
901 return ($val . $comment, undef);
902 }
903 # Try to lex a decorator call at start of sigil_rest
904 my ($sig, $ns, $fn, $pgs, $end) = eval {
905 _lex_decorator_call($sigil_rest, 0, $bound_sigils);
906 };
907 if (defined $sig) {
908 # Verify the rest after the call is empty/comment
909 my $after = substr($sigil_rest, $end);
910 $after =~ s/^\s+//;
911 if ($after eq '' || $after =~ /^[#\/]/) {
912 my $dec = {
913 position => 'trailing',
914 sigil => $sig,
915 ns => $ns,
916 fn_name => $fn,
917 param_groups => $pgs,
918 line => $cur_line,
919 indent => $indent,
920 key_name => $key_name,
921 is_list_item => $is_list_item,
922 };
923 return ($value_part . $comment, $dec);
924 }
925 }
926 }
927  
928 return ($val . $comment, undef);
929 }
930  
931 # Extract flow-inner decorators from a value that might be a flow array.
932 # e.g., `[1, |tag() 2, 3]` → clean `[1, 2, 3]`, decs at flow indexes
933 sub _extract_flow_decorators {
934 my ($val, $bound_sigils, $cur_line, $indent, $key_name, $is_list_item) = @_;
935  
936 # Quick check: does val look like a flow array with sigil chars?
937 my $trimmed = $val;
938 $trimmed =~ s/^\s+|\s+$//g;
939 # Quick skip: must start with [ to be a flow array
940 unless ($trimmed =~ /^\[/) {
941 return ($val, []);
942 }
943  
944 # Parse the flow array, collecting decorators
945 my @flow_decs;
946 my $new_val = _scan_flow_array($trimmed, $bound_sigils, $cur_line, $indent,
947 $key_name, $is_list_item, \@flow_decs);
948 return (defined $new_val ? $new_val : $val, \@flow_decs);
949 }
950  
951 # Scan a flow array string `[...]`, collect inner decorators, return cleaned array.
952 sub _scan_flow_array {
953 my ($src, $bound_sigils, $cur_line, $indent, $key_name, $is_list_item, $flow_decs) = @_;
954  
955 return undef unless $src =~ /^\[/;
956 my $inner = substr($src, 1, length($src) - 2); # strip [ ]
957  
958 my @elements;
959 my @clean_elements;
960 my $pos = 0;
961 my $len = length($inner);
962 my $elem_idx = 0;
963  
964 while ($pos < $len) {
965 # Skip whitespace
966 while ($pos < $len && substr($inner, $pos, 1) =~ /[ \t]/) { $pos++; }
967 last if $pos >= $len || substr($inner, $pos, 1) eq ']';
968  
969 # Check for inner decorator before this element
970 if (_is_sigil_atom_start($inner, $pos)) {
971 my ($sig, $ns, $fn, $pgs, $end) = eval {
972 _lex_decorator_call($inner, $pos, $bound_sigils);
973 };
974 if (defined $sig) {
975 # Inner decorator on the next element
976 push @$flow_decs, {
977 position => 'inner',
978 sigil => $sig,
979 ns => $ns,
980 fn_name => $fn,
981 param_groups => $pgs,
982 line => $cur_line,
983 indent => $indent,
984 key_name => $key_name,
985 is_list_item => $is_list_item,
986 flow_index => $elem_idx,
987 };
988 $pos = $end;
989 # Skip whitespace
990 while ($pos < $len && substr($inner, $pos, 1) =~ /[ \t]/) { $pos++; }
991 }
992 }
993  
994 # Consume the element value
995 my ($elem_str, $new_pos) = _consume_flow_element($inner, $pos);
996 last unless defined $elem_str;
997 push @clean_elements, $elem_str;
998 $elem_idx++;
999 $pos = $new_pos;
1000  
1001 # Skip whitespace and comma
1002 while ($pos < $len && substr($inner, $pos, 1) =~ /[ \t]/) { $pos++; }
1003 if ($pos < $len && substr($inner, $pos, 1) eq ',') { $pos++; }
1004 }
1005  
1006 return '[' . join(', ', @clean_elements) . ']';
1007 }
1008  
1009 # Consume one flow element (a simple value: string, number, bool, nested []).
1010 # Returns (element_string, new_pos) or (undef, undef).
1011 sub _consume_flow_element {
1012 my ($s, $pos) = @_;
1013 my $len = length($s);
1014 my $start = $pos;
1015 return (undef, undef) if $pos >= $len;
1016  
1017 my $c = substr($s, $pos, 1);
1018 if ($c eq '"') {
1019 # Quoted string
1020 $pos++;
1021 while ($pos < $len) {
1022 my $ic = substr($s, $pos, 1);
1023 if ($ic eq '\\') { $pos += 2; next; }
1024 if ($ic eq '"') { $pos++; last; }
1025 $pos++;
1026 }
1027 } elsif ($c eq "'") {
1028 $pos++;
1029 while ($pos < $len) {
1030 last if substr($s, $pos, 1) eq "'";
1031 $pos++;
1032 }
1033 $pos++;
1034 } elsif ($c eq '[') {
1035 my $depth = 1;
1036 $pos++;
1037 while ($pos < $len && $depth > 0) {
1038 my $ic = substr($s, $pos, 1);
1039 $depth++ if $ic eq '[';
1040 $depth-- if $ic eq ']';
1041 $pos++;
1042 }
1043 } elsif ($c eq '{') {
1044 my $depth = 1;
1045 $pos++;
1046 while ($pos < $len && $depth > 0) {
1047 my $ic = substr($s, $pos, 1);
1048 $depth++ if $ic eq '{';
1049 $depth-- if $ic eq '}';
1050 $pos++;
1051 }
1052 } else {
1053 # Bare value: consume until comma, ], whitespace
1054 while ($pos < $len) {
1055 my $ic = substr($s, $pos, 1);
1056 last if $ic =~ /[,\]\s]/;
1057 $pos++;
1058 }
1059 }
1060  
1061 my $elem = substr($s, $start, $pos - $start);
1062 $elem =~ s/\s+$//;
1063 return ($elem, $pos);
1064 }
1065  
1066 # ── FM pre-scan ───────────────────────────────────────────────────────────────
1067 # Split source into (fm_src, body_src, tier, fm_line_count).
1068 # Also pre-validate _dms_tier.
1069 sub split_source {
1070 my ($src) = @_;
1071  
1072 # Look for front matter
1073 my $fm_end = 0;
1074 my $tier = 0;
1075 my $fm_src = '';
1076 my $body_src = $src;
1077 my $fm_lines = 0;
1078  
1079 if ($src =~ /\A\s*\+\+\+\r?\n/) {
1080 # Find closing +++
1081 if ($src =~ /\A(\s*\+\+\+\r?\n)(.*?)(\+\+\+\r?\n)(.*)\z/s) {
1082 $fm_src = $2;
1083 $body_src = $4;
1084 # Count FM lines
1085 $fm_lines = ($1 =~ tr/\n//) + ($2 =~ tr/\n//) + ($3 =~ tr/\n//);
1086 }
1087 }
1088  
1089 return ($fm_src, $body_src, $fm_lines);
1090 }
1091  
1092 # ── Path mapping ──────────────────────────────────────────────────────────────
1093 # Given the raw decorator records (with key_name hints) and the parsed body,
1094 # map each decorator to its actual path in the value tree.
1095 #
1096 # Strategy: walk the raw_decs in order. For each, find the path using key_name.
1097 # Leading decorators: path is the same as the following key's path.
1098 # Inner/trailing: path is the key's path in the body.
1099 # Flow-inner: path is key's path + [index].
1100 #
1101 # We need to know the insertion order of keys to assign leading decorators.
1102 # Since we clean the body before parsing, leading decorator lines are removed,
1103 # but the key they precede is still there.
1104  
1105 sub map_decorator_paths {
1106 my ($raw_decs, $body, $imports) = @_;
1107 # Group raw_decs by key_name
1108 # For now, we resolve paths based on key_name and flow_index
1109  
1110 my @entries_map; # path_str → {path, calls, comments}
1111 my %path_to_entry;
1112  
1113 for my $rd (@$raw_decs) {
1114 my $key = $rd->{key_name};
1115 my $flow_index = $rd->{flow_index};
1116  
1117 # Build path
1118 my @path;
1119 if (defined $key && $key ne '') {
1120 push @path, { key => $key };
1121 }
1122 if (defined $flow_index) {
1123 push @path, { index => $flow_index };
1124 }
1125  
1126 # Resolve family/canonical from imports
1127 my ($family, $canonical);
1128 eval {
1129 ($family, $canonical) = resolve_call(
1130 $rd->{sigil}, $rd->{ns}, $rd->{fn_name}, $imports
1131 );
1132 };
1133 if ($@) {
1134 die $@;
1135 }
1136  
1137 # Parse param groups
1138 my @params;
1139 for my $pg (@{$rd->{param_groups}}) {
1140 push @params, _parse_param_group($pg);
1141 }
1142  
1143 my $call = {
1144 family => $family,
1145 fn => $canonical,
1146 ns => $rd->{ns},
1147 position => $rd->{position},
1148 params => \@params,
1149 params_dec => [],
1150 sigil => $rd->{sigil},
1151 };
1152  
1153 # Find or create entry for this path
1154 my $path_key = join('/', map { defined $_->{key} ? "k:$_->{key}" : "i:$_->{index}" } @path);
1155 if (!exists $path_to_entry{$path_key}) {
1156 my $entry = {
1157 path => \@path,
1158 calls => {},
1159 comments => [],
1160 };
1161 push @entries_map, $entry;
1162 $path_to_entry{$path_key} = $entry;
1163 }
1164 my $entry = $path_to_entry{$path_key};
1165 push @{$entry->{calls}{$rd->{sigil}}}, $call;
1166 }
1167  
1168 return \@entries_map;
1169 }
1170  
1171 # ── Hoist pass ────────────────────────────────────────────────────────────────
1172 # For each inner decorator call with a param named 'children' (content_slot),
1173 # check if body has content at the same path. If body is empty, hoist.
1174 # If body has content AND params have children → conflict error.
1175 sub hoist_pass {
1176 my ($body, $entries, $imports) = @_;
1177  
1178 for my $entry (@$entries) {
1179 for my $sigil_calls (values %{$entry->{calls}}) {
1180 for my $call (@$sigil_calls) {
1181 # Only hoist for inner position (decoration-only form)
1182 # Hoist if the call has a 'children' param
1183 next unless @{$call->{params}};
1184 my $first_group = $call->{params}[0];
1185 next unless $first_group->{kind} eq 'named';
1186 my $named_val = $first_group->{value};
1187 next unless ref($named_val) eq 'HASH';
1188  
1189 # Check for children key (the content_slot for html/tag family)
1190 my $ORDER_KEY = "\0_keys";
1191 my @named_keys = $named_val->{$ORDER_KEY}
1192 ? @{$named_val->{$ORDER_KEY}}
1193 : grep { $_ ne $ORDER_KEY } keys %$named_val;
1194  
1195 my $has_children = grep { $_ eq 'children' } @named_keys;
1196 next unless $has_children;
1197  
1198 my $children_val = $named_val->{'children'};
1199  
1200 # Navigate to path in body
1201 my $body_val = _body_at_path($body, $entry->{path});
1202  
1203 # Check conflict: body value is non-empty?
1204 my $body_empty = !defined($body_val) || _is_value_empty($body_val);
1205  
1206 if (!$body_empty) {
1207 die "0:0: Element |$call->{fn} has content specified via both 'children:' parameter and indent block. Pick one.\n";
1208 }
1209  
1210 # Hoist: remove children from params, set body
1211 my %new_named;
1212 my @new_order;
1213 for my $k (@named_keys) {
1214 next if $k eq 'children';
1215 $new_named{$k} = $named_val->{$k};
1216 push @new_order, $k;
1217 }
1218 $new_named{$ORDER_KEY} = \@new_order;
1219 $first_group->{value} = \%new_named;
1220  
1221 # Set body at path
1222 _set_body_at_path($body, $entry->{path}, $children_val);
1223 }
1224 }
1225 }
1226 }
1227  
1228 sub _body_at_path {
1229 my ($body, $path) = @_;
1230 my $cur = $body;
1231 for my $seg (@$path) {
1232 if (defined $seg->{key}) {
1233 return undef unless ref($cur) eq 'HASH';
1234 return undef unless exists $cur->{$seg->{key}};
1235 $cur = $cur->{$seg->{key}};
1236 } elsif (defined $seg->{index}) {
1237 return undef unless ref($cur) eq 'ARRAY';
1238 return undef unless $seg->{index} < scalar @$cur;
1239 $cur = $cur->[$seg->{index}];
1240 }
1241 }
1242 return $cur;
1243 }
1244  
1245 sub _is_value_empty {
1246 my ($v) = @_;
1247 return 1 unless defined $v;
1248 if (ref($v) eq 'HASH') {
1249 my $ORDER_KEY = "\0_keys";
1250 my @keys = grep { $_ ne $ORDER_KEY } keys %$v;
1251 return @keys == 0;
1252 }
1253 if (ref($v) eq 'ARRAY') { return @$v == 0; }
1254 return 1; # scalars treated as empty for conflict purposes
1255 }
1256  
1257 sub _set_body_at_path {
1258 my ($body, $path, $val) = @_;
1259 return unless @$path;
1260 my $cur = $body;
1261 for my $i (0 .. $#$path - 1) {
1262 my $seg = $path->[$i];
1263 if (defined $seg->{key}) {
1264 $cur = $cur->{$seg->{key}};
1265 } elsif (defined $seg->{index}) {
1266 $cur = $cur->[$seg->{index}];
1267 }
1268 }
1269 my $last = $path->[-1];
1270 if (defined $last->{key}) {
1271 $cur->{$last->{key}} = $val;
1272 } elsif (defined $last->{index}) {
1273 $cur->[$last->{index}] = $val;
1274 }
1275 }
1276  
1277 # ── Decoration-only body fill ─────────────────────────────────────────────────
1278 # For inner-position decoration-only form (`key: |tag()`), the parser sees
1279 # `key: ` with nothing after (or `key: {}` if we add a placeholder).
1280 # We need the body to have `{}` as the value for those keys.
1281 # The clean-body pass should already strip the decorator, leaving `key: `
1282 # which the parser will treat as a block header (empty table).
1283 # No action needed here — the existing parser handles this correctly.
1284  
1285 # ── Main entry point ──────────────────────────────────────────────────────────
1286 # decode_t1($src) → hashref with:
1287 # tier => 1 or 0
1288 # imports => [...ImportSpec...]
1289 # body => { tier-0 body }
1290 # decorators => [...DecoratorEntry...]
1291 # _raw_doc => the parsed tier-0 document (for body extraction)
1292 #
1293 # Dies with "LINE:COL: message\n" on error.
1294 sub decode_t1 {
1295 my ($src) = @_;
1296 require DMS::Parser;
1297  
1298 # ── Step 0: Decode bytes → Perl character string ──
1299 # encoder.pl reads raw bytes from STDIN; we need a character string for
1300 # character-level substring ops (especially for multi-byte emoji).
1301 # NFC-normalize to match the tier-0 parser's behaviour.
1302 unless (utf8::is_utf8($src)) {
1303 my $copy = $src;
1304 if (!utf8::decode($copy)) {
1305 die "0:0: source is not valid UTF-8\n";
1306 }
1307 $src = $copy;
1308 }
1309 # NFC-normalize if any non-ASCII chars present (matches Parser behaviour)
1310 if ($src =~ /[^\x00-\x7F]/) {
1311 require Unicode::Normalize;
1312 $src = Unicode::Normalize::NFC($src);
1313 }
1314  
1315 # ── Step 1: Split source into FM and body ──
1316 my ($has_fm, $fm_text, $body_text, $fm_line_count) = _split_fm($src);
1317  
1318 # ── Step 2: Detect tier ──
1319 my $tier = 0;
1320 if ($has_fm && $fm_text =~ /^[ \t]*_dms_tier[ \t]*:[ \t]*(\d+)[ \t]*$/m) {
1321 $tier = int($1);
1322 }
1323  
1324 if ($tier == 0) {
1325 # Tier-0 doc: parse normally and return tier-0 wrapper
1326 my $doc = eval { DMS::Parser::decode_lite_document($src) };
1327 if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1328 return {
1329 tier => 0,
1330 imports => [],
1331 body => $doc->{body},
1332 decorators => [],
1333 _raw_doc => $doc,
1334 };
1335 }
1336  
1337 # ── Step 3: Parse the full FM as tier-0 DMS (allowing _dms_* keys) ──
1338 # Parse as a plain DMS table (without front matter markers)
1339 my $fm_parsed = eval { DMS::Parser::decode_lite($fm_text) };
1340 if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1341  
1342 # ── Step 4: Extract and validate imports ──
1343 my $imports;
1344 eval { $imports = extract_imports($fm_parsed); };
1345 if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1346  
1347 # ── Step 5: Build clean FM (remove _dms_tier and _dms_imports) ──
1348 # We'll reconstruct a clean version for the tier-0 parser
1349 my $clean_fm = _strip_dms_reserved_keys($fm_text);
1350  
1351 # ── Step 6: Scan body for decorators ──
1352 my ($clean_body, $raw_decs) = scan_body($body_text, $imports, $fm_line_count);
1353  
1354 # ── Step 7: Parse clean source with tier-0 parser ──
1355 my $clean_src;
1356 if ($has_fm && $clean_fm =~ /\S/) {
1357 $clean_src = "+++\n${clean_fm}\n+++\n${clean_body}";
1358 } else {
1359 $clean_src = $clean_body;
1360 }
1361  
1362 my $t0_doc = eval { DMS::Parser::decode_lite_document($clean_src) };
1363 if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1364  
1365 my $body = $t0_doc->{body};
1366  
1367 # ── Step 8: Map decorator records to paths ──
1368 my $decorator_entries;
1369 eval { $decorator_entries = map_decorator_paths($raw_decs, $body, $imports); };
1370 if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1371  
1372 # Hoist pass is registry-dependent (requires dialect spec to know content_slot).
1373 # Without a registry, skip hoisting — the conformance tests use no registry.
1374 # eval { hoist_pass($body, $decorator_entries, $imports); };
1375 # if ($@) { my $err = $@; chomp $err; die "$err\n"; }
1376  
1377 return {
1378 tier => 1,
1379 imports => $imports,
1380 body => $body,
1381 decorators => $decorator_entries,
1382 _raw_doc => $t0_doc,
1383 };
1384 }
1385  
1386 # Split source into (has_fm, fm_text, body_text, fm_line_count).
1387 sub _split_fm {
1388 my ($src) = @_;
1389 if ($src =~ /\A([ \t]*\+\+\+[ \t]*\r?\n)(.*?)([ \t]*\+\+\+[ \t]*(?:\r?\n|\z))(.*)\z/s) {
1390 my ($opener, $fm, $closer, $body) = ($1, $2, $3, $4);
1391 my $lc = ($opener =~ tr/\n//) + ($fm =~ tr/\n//) + ($closer =~ tr/\n//);
1392 return (1, $fm, $body, $lc);
1393 }
1394 return (0, '', $src, 0);
1395 }
1396  
1397 # Remove _dms_tier and _dms_imports from FM text.
1398 # Works by line-scanning: skip _dms_tier line and _dms_imports block.
1399 sub _strip_dms_reserved_keys {
1400 my ($fm_text) = @_;
1401 my @lines = split /\n/, $fm_text, -1;
1402 my @out;
1403 my $i = 0;
1404 while ($i < @lines) {
1405 my $ln = $lines[$i];
1406 if ($ln =~ /^[ \t]*_dms_tier[ \t]*:/) {
1407 # Skip this line
1408 $i++;
1409 next;
1410 }
1411 if ($ln =~ /^[ \t]*_dms_imports[ \t]*:/) {
1412 # Skip this line and all following indented lines
1413 $i++;
1414 while ($i < @lines && ($lines[$i] =~ /^[ \t]+/ || $lines[$i] =~ /^[ \t]*$/)) {
1415 # Only skip if it's indented (part of the block) or blank
1416 # But we must not skip next top-level key
1417 last if $lines[$i] =~ /^[^ \t]/ && $lines[$i] !~ /^[ \t]*$/;
1418 $i++;
1419 }
1420 next;
1421 }
1422 push @out, $ln;
1423 $i++;
1424 }
1425 return join("\n", @out);
1426 }
1427  
1428 1;
1429  
1430 __END__