File Coverage

lib/BarefootJS/Evaluator.pm
Criterion Covered Total %
statement 64 564 11.3
branch 24 324 7.4
condition 16 139 11.5
subroutine 13 50 26.0
pod 0 20 0.0
total 117 1097 10.6


line stmt bran cond sub pod time code
1             package BarefootJS::Evaluator;
2             our $VERSION = "0.14.0";
3 6     6   38 use strict;
  6         11  
  6         255  
4 6     6   30 use warnings;
  6         12  
  6         370  
5 6     6   33 use utf8;
  6         10  
  6         39  
6 6     6   229 use feature 'signatures';
  6         12  
  6         756  
7 6     6   35 no warnings 'experimental::signatures';
  6         12  
  6         220  
8              
9 6     6   30 use B ();
  6         9  
  6         101  
10 6     6   53 use POSIX ();
  6         14  
  6         136  
11 6     6   4413 use JSON::PP ();
  6         85301  
  6         274  
12 6     6   47 use Scalar::Util qw(looks_like_number);
  6         22  
  6         34962  
13              
14             # Lightweight evaluator for the pure `ParsedExpr` subset, scoped to
15             # higher-order callback bodies (reduce / sort / map / filter / find
16             # `(…) => expr`) — issue #2018. Templates cannot carry a lambda in
17             # expression position, which is why the adapters historically special-cased
18             # these callbacks into fixed shapes (bf_sort's comparator catalogue,
19             # bf_reduce's +/* fold). Instead, the callback BODY rides as a pure
20             # `ParsedExpr` subtree (the structured IR the compiler already produces) and
21             # is evaluated here against an environment (`{acc, item, …captured free
22             # vars}`).
23             #
24             # ONE shared implementation for both Perl backends (Mojo + Xslate), living
25             # alongside SearchParams.pm in the engine-agnostic core (no CPAN deps beyond
26             # core B / POSIX / Scalar::Util). The accepted subset and its semantics are
27             # documented in spec/compiler.md ("ParsedExpr Evaluator Semantics") and pinned
28             # isomorphically by the cross-language golden vectors
29             # (packages/adapter-tests/helper-vectors/eval-vectors.json), shared with the Go
30             # evaluator (bf.go) — same input → same output.
31             #
32             # The coercion below is JS-faithful (ToNumber / ToString / ToBoolean, strict
33             # equality) and deliberately distinct from the divergent bf->string / number
34             # helpers in BarefootJS.pm, so the contract is unambiguous and the two
35             # template adapters stay byte-equal with each other and with Go.
36              
37             # evaluate($node, $env)
38             #
39             # Evaluate a decoded ParsedExpr node (a hashref keyed by `kind`) against the
40             # environment hashref ($env), returning a Perl value (number, string,
41             # JSON::PP::Boolean, undef for null, arrayref, hashref). The matching JSON
42             # entry point is eval_json() below.
43 0     0 0 0 sub evaluate ($node, $env) {
  0         0  
  0         0  
  0         0  
44 0 0       0 return undef unless ref $node eq 'HASH';
45 0   0     0 my $kind = $node->{kind} // '';
46              
47 0 0       0 if ($kind eq 'literal') {
48 0         0 return $node->{value};
49             }
50 0 0       0 if ($kind eq 'identifier') {
51 0         0 return $env->{ $node->{name} };
52             }
53 0 0       0 if ($kind eq 'binary') {
54             return _binary($node->{op},
55 0         0 evaluate($node->{left}, $env), evaluate($node->{right}, $env));
56             }
57 0 0       0 if ($kind eq 'unary') {
58 0         0 return _unary($node->{op}, evaluate($node->{argument}, $env));
59             }
60 0 0       0 if ($kind eq 'logical') {
61 0         0 my $op = $node->{op};
62 0         0 my $left = evaluate($node->{left}, $env);
63 0 0       0 if ($op eq '&&') {
64 0 0       0 return _truthy($left) ? evaluate($node->{right}, $env) : $left;
65             }
66 0 0       0 if ($op eq '||') {
67 0 0       0 return _truthy($left) ? $left : evaluate($node->{right}, $env);
68             }
69             # `??`
70 0 0       0 return defined $left ? $left : evaluate($node->{right}, $env);
71             }
72 0 0       0 if ($kind eq 'conditional') {
73             return _truthy(evaluate($node->{test}, $env))
74             ? evaluate($node->{consequent}, $env)
75 0 0       0 : evaluate($node->{alternate}, $env);
76             }
77 0 0       0 if ($kind eq 'member') {
78 0         0 return _read_property(evaluate($node->{object}, $env), $node->{property});
79             }
80 0 0       0 if ($kind eq 'index-access') {
81 0         0 return _read_index(evaluate($node->{object}, $env), evaluate($node->{index}, $env));
82             }
83 0 0       0 if ($kind eq 'call') {
84             # Nested `.map(cb)` / `.filter(cb)` (#2094) — e.g. a `.flatMap(p =>
85             # p.tags.map(t => '#'+t))` projection body that itself contains a
86             # `.map`/`.filter` call. Checked BEFORE builtin-name resolution
87             # (the callee is a `member` node, never a bare/dotted builtin
88             # identifier, so the two can't collide). Mirrors Go's
89             # evalArrayCallbackCall / evalArrayCallback.
90 0         0 my ($method, $object_node, $arrow_node) = _array_callback_call($node);
91 0 0       0 if (defined $method) {
92 0         0 return _array_callback($method, $object_node, $arrow_node, $env);
93             }
94 0         0 my $name = _builtin_name($node->{callee});
95 0 0 0     0 return undef unless defined $name && $name ne '';
96 0   0     0 my @args = map { evaluate($_, $env) } @{ $node->{args} // [] };
  0         0  
  0         0  
97 0         0 return _call_builtin($name, \@args);
98             }
99 0 0       0 if ($kind eq 'template-literal') {
100 0         0 my $out = '';
101 0   0     0 for my $p (@{ $node->{parts} // [] }) {
  0         0  
102 0 0 0     0 if (($p->{type} // '') eq 'string') {
103 0   0     0 $out .= $p->{value} // '';
104             }
105             else {
106 0         0 $out .= _to_string(evaluate($p->{expr}, $env));
107             }
108             }
109 0         0 return $out;
110             }
111 0 0       0 if ($kind eq 'array-literal') {
112 0   0     0 return [ map { evaluate($_, $env) } @{ $node->{elements} // [] } ];
  0         0  
  0         0  
113             }
114 0 0       0 if ($kind eq 'object-literal') {
115 0         0 my %out;
116 0   0     0 for my $prop (@{ $node->{properties} // [] }) {
  0         0  
117 0         0 $out{ $prop->{key} } = evaluate($prop->{value}, $env);
118             }
119 0         0 return \%out;
120             }
121 0 0 0     0 if ($kind eq 'array-method' && ($node->{method} // '') eq 'includes'
      0        
      0        
122 0   0     0 && @{ $node->{args} // [] } == 1)
123             {
124             # `.includes(x)` (#2075) — the one `array-method` in the evaluator
125             # subset, shared between `Array.prototype.includes` (SameValueZero
126             # membership) and `String.prototype.includes` (substring search),
127             # matching the receiver-type dispatch the SSR template lowering does
128             # at runtime (`bf_includes` / `$bf->includes`). Mirrors the JS
129             # reference's `includes()` (eval-reference.ts).
130 0         0 my $obj = evaluate($node->{object}, $env);
131 0         0 my $needle = evaluate($node->{args}[0], $env);
132 0 0       0 if (ref $obj eq 'ARRAY') {
133 0         0 for my $el (@$obj) {
134 0 0       0 return _bool(1) if _same_value_zero($el, $needle);
135             }
136 0         0 return _bool(0);
137             }
138 0 0       0 if (_is_string($obj)) {
139 0         0 return _bool(index($obj, _to_string($needle)) != -1);
140             }
141             # Any other receiver is not a JS `.includes` target — degrade to
142             # false rather than throwing, mirroring the reference.
143 0         0 return _bool(0);
144             }
145 0 0 0     0 if ($kind eq 'array-method' && ($node->{method} // '') eq 'join'
      0        
      0        
146 0   0     0 && @{ $node->{args} // [] } <= 1)
147             {
148             # `.join(sep?)` (#2094), a sibling of `.includes` above in the
149             # `array-method` node kind — needed for a composed case like
150             # `.flatMap(p => p.tags.map(...).join(' ')).join(', ')`. JS
151             # semantics: default separator is `,`; a `null`/`undefined`
152             # element joins as `''` (NOT the string "null"). Mirrors the Go
153             # evaluator's evalJoin.
154 0         0 my $obj = evaluate($node->{object}, $env);
155 0   0     0 my $args = $node->{args} // [];
156 0 0       0 my $sep = @$args == 1 ? _to_string(evaluate($args->[0], $env)) : ',';
157 0         0 return _join_array($obj, $sep);
158             }
159              
160             # arrow-fn / higher-order / unsupported array-method: a callback body
161             # containing these is refused upstream (BF101); never reached here.
162 0         0 return undef;
163             }
164              
165             # ---------------------------------------------------------------------------
166             # Nested `.map` / `.filter` callback recognition (#2094) — the evaluator
167             # widening that lets a callback body (already evaluated here for reduce /
168             # sort / filter / find / …) itself contain a `.map(cb)` or `.filter(cb)`
169             # call, e.g. the #1938 blog-showcase `.flatMap(p => p.tags.map(t => '#'+t))`
170             # projection. Everything else nested (`.some`/`.find`/`.every`/`.sort`/
171             # `.reduce`/`.flat`/`.flatMap`, standalone arrows) stays refused upstream —
172             # only `.map`/`.filter` are recognized here, mirroring Go's
173             # evalArrayCallbackCall / evalArrayCallback exactly.
174             # ---------------------------------------------------------------------------
175              
176             # _array_callback_call($node): if $node (a `call` node) is a `.map(arrow)` /
177             # `.filter(arrow)` call — i.e. its callee is an uncomputed `member` node
178             # whose property is "map"/"filter", and its first argument is an `arrow`
179             # node — returns `(method, object_node, arrow_node)`. Otherwise returns the
180             # empty list (so `if (my (...) = _array_callback_call($node))` is false).
181 0     0   0 sub _array_callback_call ($node) {
  0         0  
  0         0  
182 0         0 my $callee = $node->{callee};
183 0 0 0     0 return () unless ref $callee eq 'HASH' && ($callee->{kind} // '') eq 'member';
      0        
184 0 0       0 return () if $callee->{computed};
185 0   0     0 my $prop = $callee->{property} // '';
186 0 0 0     0 return () unless $prop eq 'map' || $prop eq 'filter';
187 0   0     0 my $args = $node->{args} // [];
188 0 0       0 return () unless @$args;
189 0         0 my $arrow = $args->[0];
190 0 0 0     0 return () unless ref $arrow eq 'HASH' && ($arrow->{kind} // '') eq 'arrow';
      0        
191 0         0 return ($prop, $callee->{object}, $arrow);
192             }
193              
194             # _array_callback($method, $object_node, $arrow_node, $env): evaluate the
195             # receiver (`$object_node`) against $env, then map/filter it through the
196             # arrow's body. `params` in the decoded JSON is an array ref of plain
197             # strings (e.g. `["t"]` or `["t","i"]`) — 1 param binds the element, 2
198             # params bind (element, index). The child env is a COPY of the parent env
199             # (never mutated in place across sibling iterations), with the param
200             # name(s) bound per call — matches Go's per-call `inner` env copy.
201 0     0   0 sub _array_callback ($method, $object_node, $arrow_node, $env) {
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
202 0         0 my $arr = evaluate($object_node, $env);
203 0 0       0 return undef unless ref $arr eq 'ARRAY';
204 0   0     0 my @params = @{ $arrow_node->{params} // [] };
  0         0  
205 0         0 my $body = $arrow_node->{body};
206             my $call_cb = sub {
207 0     0   0 my ($item, $index) = @_;
208 0         0 my %inner = %$env;
209 0 0       0 $inner{ $params[0] } = $item if @params >= 1;
210 0 0       0 $inner{ $params[1] } = $index if @params >= 2;
211 0         0 return evaluate($body, \%inner);
212 0         0 };
213 0 0       0 if ($method eq 'map') {
214 0         0 my @out;
215 0         0 my $i = 0;
216 0         0 for my $item (@$arr) {
217 0         0 push @out, $call_cb->($item, $i);
218 0         0 $i++;
219             }
220 0         0 return \@out;
221             }
222             # filter
223 0         0 my @out;
224 0         0 my $i = 0;
225 0         0 for my $item (@$arr) {
226 0 0       0 push @out, $item if _truthy($call_cb->($item, $i));
227 0         0 $i++;
228             }
229 0         0 return \@out;
230             }
231              
232             # _join_array($obj, $sep): `Array.prototype.join` semantics — non-ARRAY
233             # receiver -> '' (the evaluator's degrade-rather-than-die convention,
234             # matching `.includes` above); a `null`/`undefined` (Perl `undef`) element
235             # joins as '' (not the string "null"); every other element goes through
236             # `_to_string` (JS `String(x)` — a JS boolean stringifies "true"/"false", a
237             # number "42"/"NaN"/"Infinity", etc.). Mirrors Go's evalJoin.
238 0     0   0 sub _join_array ($obj, $sep) {
  0         0  
  0         0  
  0         0  
239 0 0       0 return '' unless ref $obj eq 'ARRAY';
240 0 0       0 return join($sep, map { defined $_ ? _to_string($_) : '' } @$obj);
  0         0  
241             }
242              
243             # eval_json($json, $env): decode a ParsedExpr JSON string and evaluate it.
244             # Mirrors the Go EvalExpr entry point. Requires JSON::PP only when used.
245 0     0 0 0 sub eval_json ($json, $env) {
  0         0  
  0         0  
  0         0  
246 0         0 require JSON::PP;
247 0         0 my $node = JSON::PP->new->decode($json);
248 0         0 return evaluate($node, $env);
249             }
250              
251             # ---------------------------------------------------------------------------
252             # JS value classification. JSON-decoded strings carry the string flag (POK)
253             # but no numeric flag; JSON-decoded numbers carry IOK/NOK. This lets the
254             # evaluator tell the JS *string* "10" from the JS *number* 10 — essential for
255             # the `+` overload and relational comparison — which looks_like_number alone
256             # cannot (it is true for both).
257             # ---------------------------------------------------------------------------
258              
259 50     50   42 sub _is_string ($v) {
  50         44  
  50         41  
260 50 50 33     89 return 0 if !defined $v || ref $v;
261 50         111 my $f = B::svref_2object(\$v)->FLAGS;
262 50 100 66     191 return (($f & B::SVf_POK) && !($f & (B::SVf_IOK | B::SVf_NOK))) ? 1 : 0;
263             }
264              
265 43     43   40 sub _is_number ($v) {
  43         36  
  43         71  
266 43 100 100     97 return (defined $v && !ref $v && !_is_string($v)) ? 1 : 0;
267             }
268              
269             sub _nan {
270 0     0   0 my $inf = 9**9**9;
271 0         0 return $inf - $inf;
272             }
273              
274             # ---------------------------------------------------------------------------
275             # JS coercion primitives (ToNumber / ToString / ToBoolean).
276             # ---------------------------------------------------------------------------
277              
278 0     0   0 sub _to_number ($v) {
  0         0  
  0         0  
279 0 0       0 return 0 if !defined $v;
280 0 0       0 if (ref $v eq 'JSON::PP::Boolean') { return $v ? 1 : 0 }
  0 0       0  
281 0 0       0 return _nan() if ref $v;
282 0 0       0 if (_is_string($v)) {
283 0         0 my $t = $v;
284 0         0 $t =~ s/\A\s+//;
285 0         0 $t =~ s/\s+\z//;
286 0 0       0 return 0 if $t eq '';
287 0 0       0 return looks_like_number($t) ? ($t + 0) : _nan();
288             }
289 0         0 return $v + 0;
290             }
291              
292 0     0   0 sub _to_string ($v) {
  0         0  
  0         0  
293 0 0       0 return 'null' if !defined $v;
294 0 0       0 if (ref $v eq 'JSON::PP::Boolean') { return $v ? 'true' : 'false' }
  0 0       0  
295             # JS spells the non-finite doubles "Infinity" / "-Infinity" / "NaN";
296             # Perl stringifies them "Inf" / "-Inf" / "NaN", so the non-finite cases
297             # are pinned here to stay JS-faithful (and match the Go evaluator's
298             # evalToString). Finite numbers and strings fall through to plain
299             # interpolation.
300 0 0       0 if (_is_number($v)) {
301 0         0 my $n = $v + 0;
302 0 0       0 return 'NaN' if $n != $n;
303 0 0       0 return 'Infinity' if $n == 9**9**9;
304 0 0       0 return '-Infinity' if $n == -(9**9**9);
305             }
306 0         0 return "$v";
307             }
308              
309 0     0   0 sub _truthy ($v) {
  0         0  
  0         0  
310 0 0       0 return 0 if !defined $v;
311 0 0       0 if (ref $v eq 'JSON::PP::Boolean') { return $v ? 1 : 0 }
  0 0       0  
312 0 0       0 return 1 if ref $v; # arrays / objects are always truthy in JS
313 0 0       0 if (_is_string($v)) { return $v ne '' ? 1 : 0 } # incl. the truthy "0"
  0 0       0  
314 0         0 my $n = $v + 0;
315 0 0 0     0 return ($n != 0 && $n == $n) ? 1 : 0; # nonzero and not NaN
316             }
317              
318             # _bool: wrap a Perl truthy/falsy into a JS boolean (JSON::PP::Boolean), so
319             # boolean-valued operators (relational, ===, !, Boolean()) return a real
320             # boolean rather than 1/0 — matching the Go evaluator's bool (e.g.
321             # String(a < b) is "true", and `'x' + (a < b)` is "xtrue"). The coercions
322             # above already treat JSON::PP::Boolean correctly.
323 0 0   0   0 sub _bool ($t) { $t ? JSON::PP::true() : JSON::PP::false() }
  0         0  
  0         0  
  0         0  
324              
325             # ---------------------------------------------------------------------------
326             # Operators
327             # ---------------------------------------------------------------------------
328              
329 0     0   0 sub _binary ($op, $l, $r) {
  0         0  
  0         0  
  0         0  
  0         0  
330 0 0       0 if ($op eq '+') {
331             # JS `+`: string concatenation once either operand is a string,
332             # numeric addition otherwise.
333 0 0 0     0 return _to_string($l) . _to_string($r) if _is_string($l) || _is_string($r);
334 0         0 return _to_number($l) + _to_number($r);
335             }
336 0 0       0 return _to_number($l) - _to_number($r) if $op eq '-';
337 0 0       0 return _to_number($l) * _to_number($r) if $op eq '*';
338 0 0       0 if ($op eq '/') {
339 0         0 my $ln = _to_number($l);
340 0         0 my $rn = _to_number($r);
341             # JS division by zero is finite-valued, not an error: x/0 is ±Infinity
342             # (NaN for 0/0). Perl's native `/` dies on a zero divisor, so guard it
343             # to stay JS-faithful and match the Go evaluator (Go float division
344             # already yields ±Inf / NaN).
345 0 0       0 if ($rn == 0) {
346 0 0 0     0 return _nan() if $ln == 0 || $ln != $ln;
347 0 0       0 return $ln > 0 ? 9**9**9 : -(9**9**9);
348             }
349 0         0 return $ln / $rn;
350             }
351 0 0       0 if ($op eq '%') {
352 0         0 my $rn = _to_number($r);
353 0 0       0 return _nan() if $rn == 0;
354 0         0 return POSIX::fmod(_to_number($l), $rn);
355             }
356 0 0 0     0 return _relational($op, $l, $r) if $op eq '<' || $op eq '<=' || $op eq '>' || $op eq '>=';
      0        
      0        
357 0 0       0 return _bool(_strict_eq($l, $r)) if $op eq '===';
358 0 0       0 return _bool(!_strict_eq($l, $r)) if $op eq '!==';
359             # Loose equality / bitwise / shift are out of the subset.
360 0         0 return undef;
361             }
362              
363 0     0   0 sub _relational ($op, $l, $r) {
  0         0  
  0         0  
  0         0  
  0         0  
364             # JS Abstract Relational Comparison: both strings → compare by code unit;
365             # otherwise coerce both to numbers (a NaN operand makes it false).
366 0         0 my $c;
367 0 0 0     0 if (_is_string($l) && _is_string($r)) {
368 0 0       0 $c = $l lt $r ? -1 : $l gt $r ? 1 : 0;
    0          
369             }
370             else {
371 0         0 my $ln = _to_number($l);
372 0         0 my $rn = _to_number($r);
373 0 0 0     0 return _bool(0) if $ln != $ln || $rn != $rn; # NaN → false
374 0 0       0 $c = $ln < $rn ? -1 : $ln > $rn ? 1 : 0;
    0          
375             }
376 0 0       0 return _bool($c < 0) if $op eq '<';
377 0 0       0 return _bool($c <= 0) if $op eq '<=';
378 0 0       0 return _bool($c > 0) if $op eq '>';
379 0 0       0 return _bool($c >= 0) if $op eq '>=';
380 0         0 return _bool(0);
381             }
382              
383 13     13   13 sub _strict_eq ($l, $r) {
  13         12  
  13         11  
  13         10  
384             # Strict `===`: equal JS type and value, no coercion.
385 13         15 my $ln = _is_number($l);
386 13         15 my $rn = _is_number($r);
387 13 100 100     21 if ($ln && $rn) {
388 3         5 my ($lf, $rf) = ($l + 0, $r + 0);
389 3 50 33     7 return 0 if $lf != $lf || $rf != $rf; # NaN
390 3 100       16 return $lf == $rf ? 1 : 0;
391             }
392 10 100       15 return 0 if $ln != $rn; # one numeric, one not
393 9 50       15 if (!defined $l) { return !defined $r ? 1 : 0 }
  1 100       5  
394 8 100       12 return 0 if !defined $r;
395 6         7 my $lb = ref $l eq 'JSON::PP::Boolean';
396 6         7 my $rb = ref $r eq 'JSON::PP::Boolean';
397 6 50 33     15 if ($lb || $rb) {
398 0 0 0     0 return 0 unless $lb && $rb;
399 0 0       0 return ((!!$l) == (!!$r)) ? 1 : 0;
400             }
401 6 100 33     7 return ($l eq $r ? 1 : 0) if _is_string($l) && _is_string($r);
    50          
402 6         0 return 0;
403             }
404              
405             # _same_value_zero: `Array.prototype.includes` membership test — `===`
406             # except `NaN` equals itself (and +0/-0 are not distinguished, which the
407             # JSON-decoded values here can't represent anyway). Reuses `_strict_eq`'s
408             # type/value rules and only special-cases the two-NaN case that `_strict_eq`
409             # (deliberately, for `===`) reports as unequal.
410 13     13   11 sub _same_value_zero ($l, $r) {
  13         13  
  13         41  
  13         11  
411 13 100 100     17 if (_is_number($l) && _is_number($r)) {
412 3         5 my ($lf, $rf) = ($l + 0, $r + 0);
413 3 50 33     6 return 1 if $lf != $lf && $rf != $rf; # NaN sameValueZero NaN
414             }
415 13         20 return _strict_eq($l, $r);
416             }
417              
418 0     0     sub _unary ($op, $v) {
  0            
  0            
  0            
419 0 0         return _bool(!_truthy($v)) if $op eq '!';
420 0 0         return -_to_number($v) if $op eq '-';
421 0 0         return _to_number($v) if $op eq '+';
422 0           return undef;
423             }
424              
425             # ---------------------------------------------------------------------------
426             # Built-in calls (the deterministic allowlist). Locale-sensitive builtins
427             # (localeCompare) are deliberately excluded to keep the backends isomorphic.
428             # ---------------------------------------------------------------------------
429              
430             # _builtin_name: resolve a `call` callee to its builtin name (e.g.
431             # "Math.max"), or '' when the callee is not an allowlisted builtin reference.
432 0     0     sub _builtin_name ($callee) {
  0            
  0            
433 0 0         return '' unless ref $callee eq 'HASH';
434 0   0       my $kind = $callee->{kind} // '';
435 0 0         if ($kind eq 'identifier') {
436 0   0       return $callee->{name} // '';
437             }
438 0 0 0       if ($kind eq 'member' && !$callee->{computed}) {
439 0           my $obj = $callee->{object};
440 0 0 0       return '' unless ref $obj eq 'HASH' && ($obj->{kind} // '') eq 'identifier';
      0        
441 0   0       return ($obj->{name} // '') . '.' . ($callee->{property} // '');
      0        
442             }
443 0           return '';
444             }
445              
446             # _math_round: half rounds toward +Infinity (JS Math.round: 2.5→3, -2.5→-2),
447             # matching the existing round helper rather than half-away-from-zero.
448 0     0     sub _math_round ($n) {
  0            
  0            
449 0           return POSIX::floor($n + 0.5);
450             }
451              
452 0     0     sub _call_builtin ($name, $args) {
  0            
  0            
  0            
453 0 0         if ($name eq 'Math.max') {
454 0           my $m = -(9**9**9); # JS Math.max() with no args is -Infinity
455 0           for my $a (@$args) {
456 0           my $n = _to_number($a);
457 0 0         return $n if $n != $n; # any NaN argument ⇒ NaN (JS / Go)
458 0 0         $m = $n if $n > $m;
459             }
460 0           return $m;
461             }
462 0 0         if ($name eq 'Math.min') {
463 0           my $m = 9**9**9; # JS Math.min() with no args is +Infinity
464 0           for my $a (@$args) {
465 0           my $n = _to_number($a);
466 0 0         return $n if $n != $n; # any NaN argument ⇒ NaN (JS / Go)
467 0 0         $m = $n if $n < $m;
468             }
469 0           return $m;
470             }
471 0 0         return abs(_to_number($args->[0])) if $name eq 'Math.abs';
472 0 0         return POSIX::floor(_to_number($args->[0])) if $name eq 'Math.floor';
473 0 0         return POSIX::ceil(_to_number($args->[0])) if $name eq 'Math.ceil';
474 0 0         return _math_round(_to_number($args->[0])) if $name eq 'Math.round';
475 0 0         return _to_string($args->[0]) if $name eq 'String';
476 0 0         return _to_number($args->[0]) if $name eq 'Number';
477 0 0         return _bool(_truthy($args->[0])) if $name eq 'Boolean';
478             # Any other callee is outside the subset (refused upstream).
479 0           return undef;
480             }
481              
482             # ---------------------------------------------------------------------------
483             # Member / index access
484             # ---------------------------------------------------------------------------
485              
486 0     0     sub _read_property ($obj, $key) {
  0            
  0            
  0            
487 0 0         return undef unless defined $obj;
488 0 0         if (ref $obj eq 'HASH') {
489 0 0         return exists $obj->{$key} ? $obj->{$key} : undef;
490             }
491 0 0         if (ref $obj eq 'ARRAY') {
492 0 0         return $key eq 'length' ? scalar(@$obj) : undef;
493             }
494 0 0         return undef if ref $obj;
495             # `.length` is a string property only — a numeric scalar (123) has no
496             # `.length` in the subset (JS `(123).length` is undefined → null), so
497             # guard on _is_string rather than coercing the number to a string.
498             # Matches the Go evaluator (numbers fall through to nil there).
499 0 0 0       return length($obj) if $key eq 'length' && _is_string($obj);
500 0           return undef;
501             }
502              
503 0     0     sub _read_index ($obj, $index) {
  0            
  0            
  0            
504 0 0         if (ref $obj eq 'ARRAY') {
505 0           my $f = _to_number($index);
506 0           my $i = int($f);
507 0 0 0       return undef if $i != $f || $i < 0 || $i >= @$obj;
      0        
508 0           return $obj->[$i];
509             }
510 0 0         if (ref $obj eq 'HASH') {
511 0           return $obj->{ _to_string($index) };
512             }
513 0           return undef;
514             }
515              
516             # ---------------------------------------------------------------------------
517             # Evaluator-driven higher-order folds (the generalization of bf_reduce /
518             # bf_sort onto the evaluator) — the runtime half both Perl backends share.
519             # ---------------------------------------------------------------------------
520              
521             # fold($items, $body, $acc_name, $item_name, $init, $direction, $base_env)
522             #
523             # Fold an arrayref into a value via the evaluator. The reducer $body is a
524             # pure ParsedExpr node evaluated against `{$acc_name => acc, $item_name =>
525             # item}` plus the captured free vars in $base_env per element; $init seeds the
526             # accumulator and $direction is "left" (reduce) or "right" (reduceRight).
527             # Generalizes bf_reduce — any reducer body, not just the +/* arithmetic
528             # catalogue, and acc may appear anywhere. $base_env is optional; the
529             # acc/item keys shadow any same-named base key. Mirrors Go's FoldEval.
530 0     0 0   sub fold ($items, $body, $acc_name, $item_name, $init, $direction = 'left', $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
  0            
  0            
531 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
532 0 0 0       @arr = reverse @arr if ($direction // '') eq 'right';
533             # Seed the env from the captured free vars once; acc / item are
534             # overwritten each iteration (constant base keys carry through).
535 0 0         my %env = $base_env ? %$base_env : ();
536 0           my $acc = $init;
537 0           for my $item (@arr) {
538 0           $env{$acc_name} = $acc;
539 0           $env{$item_name} = $item;
540 0           $acc = evaluate($body, \%env);
541             }
542 0           return $acc;
543             }
544              
545             # sort_by($items, $cmp, $param_a, $param_b, $base_env)
546             #
547             # Return a new arrayref ordered by a ParsedExpr comparator $cmp evaluated
548             # against `{$param_a => a, $param_b => b}` plus the captured free vars in
549             # $base_env to a number (negative / zero / positive, like a JS comparator).
550             # Generalizes bf_sort — any comparator body. $base_env is optional. Stable
551             # and non-mutating. Mirrors Go's SortEval.
552 0     0 0   sub sort_by ($items, $cmp, $param_a, $param_b, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
553             # Non-array receiver → empty arrayref, matching the nil-tolerant
554             # BarefootJS->sort helper convention (and avoiding an undef-deref footgun
555             # for callers that use the result as an arrayref). Value-compatible with
556             # the Go SortEval, whose nil slice iterates as empty too.
557 0 0         return [] unless ref $items eq 'ARRAY';
558 0 0         my %env = $base_env ? %$base_env : ();
559             # Decorate each element with its original index and tie-break on it when
560             # the comparator returns 0, so stability is explicit and independent of
561             # the `sort` pragma / build (portable to the declared minimum Perl, and
562             # matching Go's sort.SliceStable).
563 0           my @decorated = map { [ $_, $items->[$_] ] } 0 .. $#$items;
  0            
564             my @sorted = sort {
565 0           $env{$param_a} = $a->[1];
  0            
566 0           $env{$param_b} = $b->[1];
567 0           my $c = _to_number(evaluate($cmp, \%env));
568             # Explicit sign test rather than `<=> 0`: a NaN comparator result
569             # warns / is undefined under `<=>`, whereas `< 0` / `> 0` are both
570             # false for NaN, yielding 0 (no reordering) — matching JS (NaN
571             # comparator ⇒ keep order) and the Go SortEval sign test. The
572             # original-index tie-break then preserves input order for equal keys.
573 0 0         ($c < 0 ? -1 : $c > 0 ? 1 : 0) || ($a->[0] <=> $b->[0])
    0          
    0          
574             } @decorated;
575 0           return [ map { $_->[1] } @sorted ];
  0            
576             }
577              
578             # JSON entry points for the adapters: decode the callback body once, then fold /
579             # sort. Mirror the Go `bf_reduce_eval` / `bf_sort_eval` template funcs, which the
580             # adapters emit with a serialized-ParsedExpr body argument.
581 0     0 0   sub fold_json ($items, $body_json, $acc_name, $item_name, $init, $direction = 'left', $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
  0            
  0            
582 0           require JSON::PP;
583 0           return fold($items, JSON::PP->new->decode($body_json), $acc_name, $item_name, $init, $direction, $base_env);
584             }
585              
586 0     0 0   sub sort_by_json ($items, $cmp_json, $param_a, $param_b, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
587 0           require JSON::PP;
588 0           return sort_by($items, JSON::PP->new->decode($cmp_json), $param_a, $param_b, $base_env);
589             }
590              
591             # ---------------------------------------------------------------------------
592             # Higher-order predicates (#2018, P2) — the generalization of bf_filter /
593             # bf_find / bf_find_index / bf_every / bf_some onto the evaluator. The
594             # predicate $pred is a pure ParsedExpr evaluated against `{$param => item}`
595             # plus the captured free vars in $base_env per element, lifting the
596             # field-equality / truthiness restriction to any pure predicate body. Each
597             # mirrors the corresponding Go helper (FilterEval / EveryEval / SomeEval /
598             # FindEval / FindIndexEval). $base_env is optional.
599             # ---------------------------------------------------------------------------
600              
601             # filter — new arrayref of the elements the predicate keeps. Non-array receiver
602             # → empty arrayref (the BarefootJS->filter nil-tolerant convention).
603 0     0 0   sub filter ($items, $pred, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
604 0 0         return [] unless ref $items eq 'ARRAY';
605 0 0         my %env = $base_env ? %$base_env : ();
606 0           my @out;
607 0           for my $item (@$items) {
608 0           $env{$param} = $item;
609 0 0         push @out, $item if _truthy(evaluate($pred, \%env));
610             }
611 0           return \@out;
612             }
613              
614             # every — 1 iff the predicate holds for every element (vacuously 1 for an empty
615             # receiver, like JS).
616 0     0 0   sub every ($items, $pred, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
617 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
618 0 0         my %env = $base_env ? %$base_env : ();
619 0           for my $item (@arr) {
620 0           $env{$param} = $item;
621 0 0         return 0 unless _truthy(evaluate($pred, \%env));
622             }
623 0           return 1;
624             }
625              
626             # some — 1 iff the predicate holds for any element (0 for an empty receiver).
627 0     0 0   sub some ($items, $pred, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
628 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
629 0 0         my %env = $base_env ? %$base_env : ();
630 0           for my $item (@arr) {
631 0           $env{$param} = $item;
632 0 0         return 1 if _truthy(evaluate($pred, \%env));
633             }
634 0           return 0;
635             }
636              
637             # find — first matching element, or undef. $forward false searches from the end
638             # (findLast).
639 0     0 0   sub find ($items, $pred, $param, $forward = 1, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
640 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
641 0 0         @arr = reverse @arr unless $forward;
642 0 0         my %env = $base_env ? %$base_env : ();
643 0           for my $item (@arr) {
644 0           $env{$param} = $item;
645 0 0         return $item if _truthy(evaluate($pred, \%env));
646             }
647 0           return undef;
648             }
649              
650             # find_index — index of the first matching element, or -1. $forward false →
651             # findLastIndex (the index is into the original array either way).
652 0     0 0   sub find_index ($items, $pred, $param, $forward = 1, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
653 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
654 0 0         my %env = $base_env ? %$base_env : ();
655 0 0         my @idx = $forward ? ( 0 .. $#arr ) : reverse( 0 .. $#arr );
656 0           for my $i (@idx) {
657 0           $env{$param} = $arr[$i];
658 0 0         return $i if _truthy(evaluate($pred, \%env));
659             }
660 0           return -1;
661             }
662              
663             # flat_map — project each element through $proj (a pure ParsedExpr) and flatten
664             # the results one level. A projection yielding an arrayref contributes its
665             # elements; any other value contributes itself (JS `.flatMap` keeps a non-array
666             # return as a single element). Generalizes bf->flat_map / flat_map_tuple to any
667             # pure projection. Mirrors Go's FlatMapEval. $base_env is optional.
668 0     0 0   sub flat_map ($items, $proj, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
669 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
670 0 0         my %env = $base_env ? %$base_env : ();
671 0           my @out;
672 0           for my $item (@arr) {
673 0           $env{$param} = $item;
674 0           my $v = evaluate($proj, \%env);
675 0 0         if (ref $v eq 'ARRAY') { push @out, @$v }
  0            
676 0           else { push @out, $v }
677             }
678 0           return \@out;
679             }
680              
681             # map_items — project each element through $proj (a pure ParsedExpr), keeping
682             # each result as one element (no flatten): JS value-producing `.map(cb)`
683             # (#2073). Named map_items (not `map`) so the Perl builtin stays unshadowed.
684             # Mirrors Go's MapEval. $base_env is optional.
685 0     0 0   sub map_items ($items, $proj, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
686 0 0         my @arr = ref $items eq 'ARRAY' ? @$items : ();
687 0 0         my %env = $base_env ? %$base_env : ();
688 0           my @out;
689 0           for my $item (@arr) {
690 0           $env{$param} = $item;
691 0           push @out, evaluate($proj, \%env);
692             }
693 0           return \@out;
694             }
695              
696             # ---------------------------------------------------------------------------
697             # JSON-string seams — the adapters emit `bf->filter_eval($recv, '', …)`;
698             # the predicate body arrives as a JSON string here, decoded then handed to the
699             # helper above (mirroring fold_json / sort_by_json).
700             # ---------------------------------------------------------------------------
701              
702 0     0 0   sub filter_json ($items, $pred_json, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
703 0           require JSON::PP;
704 0           return filter($items, JSON::PP->new->decode($pred_json), $param, $base_env);
705             }
706              
707 0     0 0   sub every_json ($items, $pred_json, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
708 0           require JSON::PP;
709 0           return every($items, JSON::PP->new->decode($pred_json), $param, $base_env);
710             }
711              
712 0     0 0   sub some_json ($items, $pred_json, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
713 0           require JSON::PP;
714 0           return some($items, JSON::PP->new->decode($pred_json), $param, $base_env);
715             }
716              
717 0     0 0   sub find_json ($items, $pred_json, $param, $forward = 1, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
718 0           require JSON::PP;
719 0           return find($items, JSON::PP->new->decode($pred_json), $param, $forward, $base_env);
720             }
721              
722 0     0 0   sub find_index_json ($items, $pred_json, $param, $forward = 1, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
  0            
723 0           require JSON::PP;
724 0           return find_index($items, JSON::PP->new->decode($pred_json), $param, $forward, $base_env);
725             }
726              
727 0     0 0   sub flat_map_json ($items, $proj_json, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
728 0           require JSON::PP;
729 0           return flat_map($items, JSON::PP->new->decode($proj_json), $param, $base_env);
730             }
731              
732 0     0 0   sub map_json ($items, $proj_json, $param, $base_env = undef) {
  0            
  0            
  0            
  0            
  0            
733 0           require JSON::PP;
734 0           return map_items($items, JSON::PP->new->decode($proj_json), $param, $base_env);
735             }
736              
737             1;