BarefootJS
view release on metacpan or search on metacpan
lib/BarefootJS/Evaluator.pm view on Meta::CPAN
# whose property is "map"/"filter", and its first argument is an `arrow`
# node â returns `(method, object_node, arrow_node)`. Otherwise returns the
# empty list (so `if (my (...) = _array_callback_call($node))` is false).
sub _array_callback_call ($node) {
my $callee = $node->{callee};
return () unless ref $callee eq 'HASH' && ($callee->{kind} // '') eq 'member';
return () if $callee->{computed};
my $prop = $callee->{property} // '';
return () unless $prop eq 'map' || $prop eq 'filter';
my $args = $node->{args} // [];
return () unless @$args;
my $arrow = $args->[0];
return () unless ref $arrow eq 'HASH' && ($arrow->{kind} // '') eq 'arrow';
return ($prop, $callee->{object}, $arrow);
}
# _array_callback($method, $object_node, $arrow_node, $env): evaluate the
# receiver (`$object_node`) against $env, then map/filter it through the
# arrow's body. `params` in the decoded JSON is an array ref of plain
# strings (e.g. `["t"]` or `["t","i"]`) â 1 param binds the element, 2
# params bind (element, index). The child env is a COPY of the parent env
# (never mutated in place across sibling iterations), with the param
# name(s) bound per call â matches Go's per-call `inner` env copy.
sub _array_callback ($method, $object_node, $arrow_node, $env) {
my $arr = evaluate($object_node, $env);
return undef unless ref $arr eq 'ARRAY';
my @params = @{ $arrow_node->{params} // [] };
my $body = $arrow_node->{body};
my $call_cb = sub {
my ($item, $index) = @_;
my %inner = %$env;
$inner{ $params[0] } = $item if @params >= 1;
$inner{ $params[1] } = $index if @params >= 2;
return evaluate($body, \%inner);
};
if ($method eq 'map') {
my @out;
my $i = 0;
for my $item (@$arr) {
push @out, $call_cb->($item, $i);
$i++;
}
return \@out;
}
# filter
my @out;
my $i = 0;
for my $item (@$arr) {
push @out, $item if _truthy($call_cb->($item, $i));
$i++;
}
return \@out;
}
# _join_array($obj, $sep): `Array.prototype.join` semantics â non-ARRAY
# receiver -> '' (the evaluator's degrade-rather-than-die convention,
# matching `.includes` above); a `null` (Perl `undef`) or `undefined`
# (`UNDEF`) element joins as '' (not the string "null"); every other element
# goes through
# `_to_string` (JS `String(x)` â a JS boolean stringifies "true"/"false", a
# number "42"/"NaN"/"Infinity", etc.). Mirrors Go's evalJoin.
sub _join_array ($obj, $sep) {
return '' unless ref $obj eq 'ARRAY';
return join($sep, map { _is_nullish($_) ? '' : _to_string($_) } @$obj);
}
# eval_json($json, $env): decode a ParsedExpr JSON string and evaluate it.
# Mirrors the Go EvalExpr entry point. Requires JSON::PP only when used.
sub eval_json ($json, $env) {
require JSON::PP;
my $node = JSON::PP->new->decode($json);
return evaluate($node, $env);
}
# ---------------------------------------------------------------------------
# JS value classification. JSON-decoded strings carry the string flag (POK)
# but no numeric flag; JSON-decoded numbers carry IOK/NOK. This lets the
# evaluator tell the JS *string* "10" from the JS *number* 10 â essential for
# the `+` overload and relational comparison â which looks_like_number alone
# cannot (it is true for both).
# ---------------------------------------------------------------------------
sub _is_string ($v) {
return 0 if !defined $v || ref $v;
my $f = B::svref_2object(\$v)->FLAGS;
return (($f & B::SVf_POK) && !($f & (B::SVf_IOK | B::SVf_NOK))) ? 1 : 0;
}
sub _is_number ($v) {
return (defined $v && !ref $v && !_is_string($v)) ? 1 : 0;
}
# Perl's builtin `length` counts UTF-8 BYTES unless the scalar already
# carries the internal UTF8 flag (set when the caller decoded it, e.g. via
# `JSON::PP->new->utf8->decode`) â a byte count diverges from JS `.length`
# (UTF-16 code units) on ANY non-ASCII input, not just astral characters
# (#2196 Level 1). Count Unicode codepoints instead: agrees with JS for
# every BMP character; astral characters (emoji, CJK-ext) still diverge
# from JS's 2-code-unit count (documented, separate known limitation) but
# now agree with the other four backends (Go/Ruby/Python/PHP), which all
# already count codepoints.
sub _codepoint_length ($s) {
return length($s) if utf8::is_utf8($s);
my $copy = $s;
utf8::decode($copy); # no-op on already-decoded or invalid-UTF-8 input
return length($copy);
}
sub _nan {
my $inf = 9**9**9;
return $inf - $inf;
}
# ---------------------------------------------------------------------------
# JS coercion primitives (ToNumber / ToString / ToBoolean).
# ---------------------------------------------------------------------------
# _double: the IEEE double nearest $n. A JS number is a double, but a perl
# built with -Duselongdouble or -Dusequadmath keeps a wider NV, so `0.1 + 0.2`
# is 0.3 there and a round-trip check passes at a precision JS doesn't have
# (#3445). Rounding where a number enters and after each arithmetic step keeps
# those perls on JS's values; with an 8-byte NV it is the identity.
use constant WIDE_NV => length(pack 'F', 0) > 8;
sub _double ($n) { WIDE_NV ? unpack('d', pack('d', $n)) : $n }
sub _to_number ($v) {
return 0 if !defined $v;
return _nan() if _is_undef($v);
if (ref $v eq 'JSON::PP::Boolean') { return $v ? 1 : 0 }
return _nan() if ref $v;
return _string_to_number($v) if _is_string($v);
# Already a number: no `+ 0`, which would turn a -0 into +0.
return _double($v);
}
# _string_to_number: JS StringToNumber (ECMA-262 StringNumericLiteral),
# ASCII digits only. The string is trimmed and `''` is 0; a signed decimal
# literal with an optional exponent, the exact spelling `Infinity`, and an
# unsigned `0x` / `0o` / `0b` integer are their values; anything else
# (`infinity`, `nan`, `1_000`, `-0x10`) is NaN. Perl's own numification
# (`looks_like_number`) accepts `inf` / `nan`, reads `"0x10"` as 0 and
# `"-0"` as +0, so it is not used here.
my %RADIX = (x => 16, o => 8, b => 2);
# _radix_to_number: the digits of a JS `0x` / `0o` / `0b` integer as the
# double nearest its value, ties to even; NaN for a digit outside the base.
# JS rounds the mathematical value once (#3824 step 3), so the digits are
# read as bits: the first 53 significant bits, the next one (the round bit)
# and whether any later bit is set (the sticky bit). Accumulating them in a
# Perl number rounds every prefix past 64 bits instead. A value past the
# largest double is Infinity.
my %RADIX_BITS = (16 => 4, 8 => 3, 2 => 1);
sub _radix_to_number ($digits, $base) {
my $kept = 0; # the first 54 significant bits (53 + the round bit)
my $significant = 0;
my $sticky = 0;
for my $digit (split //, $digits) {
my $d = hex $digit;
return _nan() if $d >= $base;
for (my $shift = $RADIX_BITS{$base} - 1; $shift >= 0; $shift--) {
my $bit = ($d >> $shift) & 1;
next if $significant == 0 && $bit == 0;
if ($significant < 54) {
$kept = $kept * 2 + $bit;
}
elsif ($bit) {
$sticky = 1;
}
$significant++;
}
}
return _double($kept) if $significant <= 53;
my $round = $kept % 2;
my $mantissa = ($kept - $round) / 2;
$mantissa++ if $round && ($sticky || $mantissa % 2);
# mantissa <= 2^53 is exact, and a power of two scales it exactly or
# overflows to Infinity.
my $exponent = $significant - 53;
return 9**9**9 if $exponent > 1100;
return _double($mantissa * (2**$exponent));
}
sub _string_to_number ($s) {
my $t = $s;
$t =~ s/\A\s+//;
$t =~ s/\s+\z//;
return 0 if $t eq '';
if ($t =~ /\A0([xXoObB])([0-9a-fA-F]+)\z/) {
return _radix_to_number($2, $RADIX{lc $1});
}
if ($t =~ /\A([+-]?)Infinity\z/) {
return $1 eq '-' ? -(9**9**9) : 9**9**9;
}
return _nan() unless $t =~ /\A([+-]?)(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/;
my $n = _double($t + 0);
# `"-0"` (and `"-0.0"`, `"-0e5"`) is negative zero; Perl numifies it to +0.
return ($1 eq '-' && $n == 0) ? -(unpack('d', pack('d', 0))) : $n;
}
sub _to_string ($v) {
return 'null' if !defined $v;
return 'undefined' if _is_undef($v);
if (ref $v eq 'JSON::PP::Boolean') { return $v ? 'true' : 'false' }
# Array.prototype.toString is join(","): a nil element (`null` or
# `undefined`) prints as "", and a nested array flattens through its own
# join. A plain object prints as "[object Object]".
return join(',', map { _is_nullish($_) ? '' : _to_string($_) } @$v) if ref $v eq 'ARRAY';
return '[object Object]' if ref $v eq 'HASH';
return _format_number($v + 0) if _is_number($v);
return "$v";
}
# _is_object: an array or a plain object, which ToPrimitive turns into its
# ToString, so a `+` over it concatenates.
sub _is_object ($v) {
my $r = ref $v;
return ($r eq 'ARRAY' || $r eq 'HASH') ? 1 : 0;
}
# _format_number: JS `Number::toString`. Perl's own stringification is
# `%.15g`, which drops digits (`0.1 + 0.2` -> "0.3"), spells the non-finite
# doubles "Inf" / "NaN", and pads a small exponent (`1.23456789e-06`).
# Integers below 2**53 print exactly; everything else takes the shortest
# `%.Ng` that round-trips as a double and re-spells it with ECMA-262's notation rules:
# decimal within [1e-6, 1e21), otherwise an unpadded lower-case exponent
# (`1.23456789e-7`, `1.23456789e+21`) (#3380).
sub _format_number ($n) {
$n = _double($n);
return 'NaN' if $n != $n;
return 'Infinity' if $n == 9**9**9;
return '-Infinity' if $n == -(9**9**9);
return '0' if $n == 0;
return sprintf('%.0f', $n) if $n == int($n) && abs($n) < 9007199254740992;
my $s;
for my $p (1 .. 17) {
$s = sprintf('%.*g', $p, $n);
last if _double($s + 0) == $n;
}
return _js_notation($s);
}
# _js_notation: re-spell a shortest round-trip decimal (`[-]d[.ddd][e[+-]x]`)
# with ECMA-262's Number::toString notation rules. `$digits` holds the
# significant digits, `$point` where the decimal point falls in them.
sub _js_notation ($shortest) {
my $sign = $shortest =~ s/\A-// ? '-' : '';
my ($mantissa, $exp) = split /e/i, $shortest, 2;
my ($int, $frac) = split /\./, $mantissa, 2;
$frac //= '';
my $raw = $int . $frac;
my $point = length($int) + (defined $exp ? $exp + 0 : 0);
(my $digits = $raw) =~ s/\A0+//;
$point -= length($raw) - length($digits);
$digits =~ s/0+\z//;
$digits = '0' if $digits eq '';
my $k = length $digits;
my $out;
if ($k <= $point && $point <= 21) {
$out = $digits . ('0' x ($point - $k));
} elsif ($point > 0 && $point <= 21) {
$out = substr($digits, 0, $point) . '.' . substr($digits, $point);
} elsif ($point > -6 && $point <= 0) {
$out = '0.' . ('0' x -$point) . $digits;
} else {
my $e = $point - 1;
$out = substr($digits, 0, 1) . ($k > 1 ? '.' . substr($digits, 1) : '')
. 'e' . ($e >= 0 ? '+' : '-') . abs($e);
}
return $sign . $out;
}
sub _truthy ($v) {
return 0 if _is_nullish($v);
if (ref $v eq 'JSON::PP::Boolean') { return $v ? 1 : 0 }
return 1 if ref $v; # arrays / objects are always truthy in JS
if (_is_string($v)) { return $v ne '' ? 1 : 0 } # incl. the truthy "0"
my $n = $v + 0;
return ($n != 0 && $n == $n) ? 1 : 0; # nonzero and not NaN
}
# _bool: wrap a Perl truthy/falsy into a JS boolean (JSON::PP::Boolean), so
# boolean-valued operators (relational, ===, !, Boolean()) return a real
# boolean rather than 1/0 â matching the Go evaluator's bool (e.g.
# String(a < b) is "true", and `'x' + (a < b)` is "xtrue"). The coercions
# above already treat JSON::PP::Boolean correctly.
sub _bool ($t) { $t ? JSON::PP::true() : JSON::PP::false() }
# ---------------------------------------------------------------------------
# Operators
# ---------------------------------------------------------------------------
sub _binary ($op, $l, $r) {
if ($op eq '+') {
# JS `+`: string concatenation once either operand is a string after
# ToPrimitive (an array or object converts to its ToString), numeric
# addition otherwise.
return _to_string($l) . _to_string($r)
if _is_string($l) || _is_string($r) || _is_object($l) || _is_object($r);
my ($ln, $rn) = (_to_number($l), _to_number($r));
my $sum = _double($ln + $rn);
# Perl adds two integral doubles as integers, which drops the sign of
# `-0 + -0`; IEEE addition keeps it.
return -(unpack('d', pack('d', 0))) if $sum == 0 && POSIX::signbit($ln) && POSIX::signbit($rn);
return $sum;
}
return _double(_to_number($l) - _to_number($r)) if $op eq '-';
return _double(_to_number($l) * _to_number($r)) if $op eq '*';
if ($op eq '/') {
return _divide(_to_number($l), _to_number($r));
}
return _remainder(_to_number($l), _to_number($r)) if $op eq '%';
return _relational($op, $l, $r) if $op eq '<' || $op eq '<=' || $op eq '>' || $op eq '>=';
return _bool(_strict_eq($l, $r)) if $op eq '===';
return _bool(!_strict_eq($l, $r)) if $op eq '!==';
# Loose equality / bitwise / shift are out of the subset.
return undef;
}
# _divide: JS `/` over two numbers, as a double. Division by zero is
# finite-valued, not an error: x/0 is ±Infinity, signed by both operands
# (`1 / -0` is -Infinity), and 0/0 or NaN/0 is NaN. Perl's native `/` dies
# on a zero divisor. Shared with the template runtime's `divide` (#3454).
sub _divide ($ln, $rn) {
if ($rn == 0) {
return _nan() if $ln == 0 || $ln != $ln;
my $negative = ($ln < 0) != (POSIX::signbit($rn) ? 1 : 0);
return $negative ? -(9**9**9) : 9**9**9;
}
return _double($ln / $rn);
}
# _remainder: JS `%` over two numbers, the truncated remainder: it takes the
# dividend's sign (`-7 % 2` is -1) and keeps a fraction (`7.5 % 2` is 1.5),
# where Perl's native `%` floors and works on integers. A zero divisor, or a
# NaN / infinite dividend, gives NaN. Shared with the template runtime's
# `mod` (#3474).
sub _remainder ($ln, $rn) {
return _nan() if $rn == 0;
return POSIX::fmod($ln, $rn);
}
sub _relational ($op, $l, $r) {
# JS Abstract Relational Comparison: both strings â compare by code unit;
# otherwise coerce both to numbers (a NaN operand makes it false).
my $c;
if (_is_string($l) && _is_string($r)) {
$c = _compare_utf16($l, $r);
}
else {
my $ln = _to_number($l);
my $rn = _to_number($r);
return _bool(0) if $ln != $ln || $rn != $rn; # NaN â false
$c = $ln < $rn ? -1 : $ln > $rn ? 1 : 0;
}
return _bool($c < 0) if $op eq '<';
return _bool($c <= 0) if $op eq '<=';
return _bool($c > 0) if $op eq '>';
return _bool($c >= 0) if $op eq '>=';
return _bool(0);
}
# _compare_utf16: JS string order, by UTF-16 code unit. Perl's `cmp` orders
# characters by code point, which differs where an astral character (whose
# leading surrogate is 0xD800-0xDBFF) meets a BMP character above the
# surrogates (`"ð" lt "。"` is true in JS); and a string without Perl's
# UTF8 flag holds UTF-8 bytes, which `cmp` would read as Latin-1 against a
# flagged one. Both are decoded and re-packed as big-endian UTF-16, whose
# bytes compare in code-unit order.
sub _compare_utf16 ($l, $r) {
return $l cmp $r unless $l =~ /[^\x00-\x7f]/ || $r =~ /[^\x00-\x7f]/;
return _utf16_be($l) cmp _utf16_be($r);
}
sub _utf16_be ($s) {
utf8::decode($s) unless utf8::is_utf8($s); # no-op on invalid UTF-8
return join '', map {
my $o = ord;
$o > 0xFFFF
? pack('n2', 0xD800 + (($o - 0x10000) >> 10), 0xDC00 + (($o - 0x10000) & 0x3FF))
: pack('n', $o)
} split //, $s;
}
sub _strict_eq ($l, $r) {
# Strict `===`: equal JS type and value, no coercion.
my $ln = _is_number($l);
my $rn = _is_number($r);
if ($ln && $rn) {
# Compared as doubles: an arithmetic result is already rounded to
# one, but a literal or env value on a wide-NV perl is not (#3445).
my ($lf, $rf) = (_double($l + 0), _double($r + 0));
return 0 if $lf != $lf || $rf != $rf; # NaN
return $lf == $rf ? 1 : 0;
}
return 0 if $ln != $rn; # one numeric, one not
# `null` is only itself and `undefined` only itself.
if (!defined $l) { return !defined $r ? 1 : 0 }
return 0 if !defined $r;
return (_is_undef($l) && _is_undef($r)) ? 1 : 0 if _is_undef($l) || _is_undef($r);
my $lb = ref $l eq 'JSON::PP::Boolean';
my $rb = ref $r eq 'JSON::PP::Boolean';
if ($lb || $rb) {
return 0 unless $lb && $rb;
return ((!!$l) == (!!$r)) ? 1 : 0;
}
# An object or array is equal only to itself: the same reference, not
# another structure with the same contents.
if (ref $l || ref $r) {
return (ref $l && ref $r && refaddr($l) == refaddr($r)) ? 1 : 0;
}
return ($l eq $r ? 1 : 0) if _is_string($l) && _is_string($r);
return 0;
}
# _same_value_zero: `Array.prototype.includes` membership test â `===`
# except `NaN` equals itself (and +0/-0 are not distinguished, which the
# JSON-decoded values here can't represent anyway). Reuses `_strict_eq`'s
# type/value rules and only special-cases the two-NaN case that `_strict_eq`
# (deliberately, for `===`) reports as unequal.
sub _same_value_zero ($l, $r) {
if (_is_number($l) && _is_number($r)) {
my ($lf, $rf) = ($l + 0, $r + 0);
return 1 if $lf != $lf && $rf != $rf; # NaN sameValueZero NaN
}
return _strict_eq($l, $r);
}
sub _unary ($op, $v) {
return _bool(!_truthy($v)) if $op eq '!';
# JS `-x` keeps the sign of zero: negate the double, never a Perl IV,
# whose zero has no sign (`-0` is 0).
return -(unpack('d', pack('d', _to_number($v)))) if $op eq '-';
return _to_number($v) if $op eq '+';
return undef;
}
# ---------------------------------------------------------------------------
# Built-in calls (the deterministic allowlist). Locale-sensitive builtins
# (localeCompare) are deliberately excluded to keep the backends isomorphic.
# ---------------------------------------------------------------------------
# _builtin_name: resolve a `call` callee to its builtin name (e.g.
# "Math.max"), or '' when the callee is not an allowlisted builtin reference.
sub _builtin_name ($callee) {
return '' unless ref $callee eq 'HASH';
my $kind = $callee->{kind} // '';
if ($kind eq 'identifier') {
return $callee->{name} // '';
}
if ($kind eq 'member' && !$callee->{computed}) {
my $obj = $callee->{object};
return '' unless ref $obj eq 'HASH' && ($obj->{kind} // '') eq 'identifier';
return ($obj->{name} // '') . '.' . ($callee->{property} // '');
}
return '';
}
# _math_round: half rounds toward +Infinity (JS Math.round: 2.5â3, -2.5â-2),
# matching the existing round helper rather than half-away-from-zero.
sub _math_round ($n) {
return POSIX::floor($n + 0.5);
}
sub _call_builtin ($name, $args) {
# An omitted argument is JS `undefined`.
my $arg = sub ($i) { $i < @$args ? $args->[$i] : $UNDEF };
if ($name eq 'Math.max') {
my $m = -(9**9**9); # JS Math.max() with no args is -Infinity
for my $a (@$args) {
my $n = _to_number($a);
return $n if $n != $n; # any NaN argument â NaN (JS / Go)
$m = $n if $n > $m;
}
return $m;
}
if ($name eq 'Math.min') {
my $m = 9**9**9; # JS Math.min() with no args is +Infinity
for my $a (@$args) {
my $n = _to_number($a);
return $n if $n != $n; # any NaN argument â NaN (JS / Go)
$m = $n if $n < $m;
}
return $m;
}
return abs(_to_number($arg->(0))) if $name eq 'Math.abs';
return POSIX::floor(_to_number($arg->(0))) if $name eq 'Math.floor';
return POSIX::ceil(_to_number($arg->(0))) if $name eq 'Math.ceil';
return _math_round(_to_number($arg->(0))) if $name eq 'Math.round';
# `String()` / `Number()` with no argument are "" / 0; `String(undefined)`
# is "undefined" and `Number(undefined)` NaN.
return @$args ? _to_string($args->[0]) : '' if $name eq 'String';
return @$args ? _to_number($args->[0]) : 0 if $name eq 'Number';
return _bool(_truthy($arg->(0))) if $name eq 'Boolean';
# Any other callee is outside the subset (refused upstream).
return undef;
}
# ---------------------------------------------------------------------------
# Member / index access
# ---------------------------------------------------------------------------
# _read_property: JS `obj.key`. A key the object does not have, and any read
# of a receiver with no such property (a nil, a number), is `undefined`.
sub _read_property ($obj, $key) {
return $UNDEF if _is_nullish($obj);
if (ref $obj eq 'HASH') {
return exists $obj->{$key} ? $obj->{$key} : $UNDEF;
}
if (ref $obj eq 'ARRAY') {
return $key eq 'length' ? scalar(@$obj) : $UNDEF;
}
return $UNDEF if ref $obj;
# `.length` is a string property only â a numeric scalar (123) has no
# `.length` in the subset (JS `(123).length` is undefined), so guard on
# _is_string rather than coercing the number to a string. Matches the
# Go evaluator (numbers fall through to nil there).
return _codepoint_length($obj) if $key eq 'length' && _is_string($obj);
return $UNDEF;
}
# _read_index: JS `obj[index]`, and the template helper `BarefootJS::get`
# (which delegates here, so a template read and a callback read cannot
# disagree on a key). The key goes through ToPropertyKey (`_to_string`:
# `undef` is "null", a JSON boolean "true" / "false", `-0` is "0", `1.0` is
# "1"). An array, and a string, are read only through a canonical array
# index: "1" reads element 1, while "01", "1e0", "-0", "1.1" and "-1" are
# ordinary property names and read `undef`. A string reads one UTF-16 code
# unit. A hash reads its own key (spec/js-primitive-semantics.md,
# "ToPropertyKey and index read"). A key the receiver does not have, and any
# read of a receiver with no properties, is `undefined` (`UNDEF`).
sub _read_index ($obj, $index) {
return $UNDEF if _is_nullish($obj);
my $key = _to_string($index);
if (ref $obj eq 'HASH') {
return exists $obj->{$key} ? $obj->{$key} : $UNDEF;
}
return $UNDEF unless $key =~ /\A(?:0|[1-9][0-9]*)\z/;
if (ref $obj eq 'ARRAY') {
return $key < @$obj ? $obj->[$key] : $UNDEF;
}
return $UNDEF if ref $obj || !_is_string($obj);
return _utf16_unit_at($obj, $key);
}
# _utf16_unit_at: the UTF-16 code unit of string $s at index $i, as a
# one-character string, or `undefined` past the end. A unit that is one half of
# a surrogate pair reads as U+FFFD: a lone surrogate cannot be written out
# as UTF-8 (spec/js-primitive-semantics.md, "Out of scope"). A string
# without Perl's UTF8 flag holds UTF-8 bytes, so a decoded copy is iterated
# (as `_codepoint_length` does): otherwise `"\xc3\xa9x"` would read one byte
lib/BarefootJS/Evaluator.pm view on Meta::CPAN
}
return $UNDEF;
}
# ---------------------------------------------------------------------------
# Evaluator-driven higher-order folds (the generalization of bf_reduce /
# bf_sort onto the evaluator) â the runtime half both Perl backends share.
# ---------------------------------------------------------------------------
# fold($items, $body, $acc_name, $item_name, $init, $direction, $base_env)
#
# Fold an arrayref into a value via the evaluator. The reducer $body is a
# pure ParsedExpr node evaluated against `{$acc_name => acc, $item_name =>
# item}` plus the captured free vars in $base_env per element; $init seeds the
# accumulator and $direction is "left" (reduce) or "right" (reduceRight).
# Generalizes bf_reduce â any reducer body, not just the +/* arithmetic
# catalogue, and acc may appear anywhere. $base_env is optional; the
# acc/item keys shadow any same-named base key. Mirrors Go's FoldEval.
sub fold ($items, $body, $acc_name, $item_name, $init, $direction = 'left', $base_env = undef) {
my @arr = ref $items eq 'ARRAY' ? @$items : ();
@arr = reverse @arr if ($direction // '') eq 'right';
# Seed the env from the captured free vars once; acc / item are
# overwritten each iteration (constant base keys carry through).
my %env = $base_env ? %$base_env : ();
my $acc = $init;
for my $item (@arr) {
$env{$acc_name} = $acc;
$env{$item_name} = $item;
$acc = evaluate($body, \%env);
}
return $acc;
}
# sort_by($items, $cmp, $param_a, $param_b, $base_env)
#
# Return a new arrayref ordered by a ParsedExpr comparator $cmp evaluated
# against `{$param_a => a, $param_b => b}` plus the captured free vars in
# $base_env to a number (negative / zero / positive, like a JS comparator).
# Generalizes bf_sort â any comparator body. $base_env is optional. Stable
# and non-mutating. Mirrors Go's SortEval.
# JS moves every `undefined` element to the end without handing it to the
# comparator.
sub sort_by ($items, $cmp, $param_a, $param_b, $base_env = undef) {
# Non-array receiver â empty arrayref, matching the nil-tolerant
# BarefootJS->sort helper convention (and avoiding an undef-deref footgun
# for callers that use the result as an arrayref). Value-compatible with
# the Go SortEval, whose nil slice iterates as empty too.
return [] unless ref $items eq 'ARRAY';
my %env = $base_env ? %$base_env : ();
# Decorate each element with its original index and tie-break on it when
# the comparator returns 0, so stability is explicit and independent of
# the `sort` pragma / build (portable to the declared minimum Perl, and
# matching Go's sort.SliceStable).
my @defined = grep { !_is_undef($_) } @$items;
my @tail = grep { _is_undef($_) } @$items;
my @decorated = map { [ $_, $defined[$_] ] } 0 .. $#defined;
my @sorted = sort {
$env{$param_a} = $a->[1];
$env{$param_b} = $b->[1];
my $c = _to_number(evaluate($cmp, \%env));
# Explicit sign test rather than `<=> 0`: a NaN comparator result
# warns / is undefined under `<=>`, whereas `< 0` / `> 0` are both
# false for NaN, yielding 0 (no reordering) â matching JS (NaN
# comparator â keep order) and the Go SortEval sign test. The
# original-index tie-break then preserves input order for equal keys.
($c < 0 ? -1 : $c > 0 ? 1 : 0) || ($a->[0] <=> $b->[0])
} @decorated;
return [ (map { $_->[1] } @sorted), @tail ];
}
# JSON entry points for the adapters: decode the callback body once, then fold /
# sort. Mirror the Go `bf_reduce_eval` / `bf_sort_eval` template funcs, which the
# adapters emit with a serialized-ParsedExpr body argument.
sub fold_json ($items, $body_json, $acc_name, $item_name, $init, $direction = 'left', $base_env = undef) {
require JSON::PP;
return fold($items, JSON::PP->new->decode($body_json), $acc_name, $item_name, $init, $direction, $base_env);
}
sub sort_by_json ($items, $cmp_json, $param_a, $param_b, $base_env = undef) {
require JSON::PP;
return sort_by($items, JSON::PP->new->decode($cmp_json), $param_a, $param_b, $base_env);
}
# ---------------------------------------------------------------------------
# Higher-order predicates (#2018, P2) â the generalization of bf_filter /
# bf_find / bf_find_index / bf_every / bf_some onto the evaluator. The
# predicate $pred is a pure ParsedExpr evaluated against `{$param => item}`
# plus the captured free vars in $base_env per element, lifting the
# field-equality / truthiness restriction to any pure predicate body. Each
# mirrors the corresponding Go helper (FilterEval / EveryEval / SomeEval /
# FindEval / FindIndexEval). $base_env is optional.
# ---------------------------------------------------------------------------
# filter â new arrayref of the elements the predicate keeps. Non-array receiver
# â empty arrayref (the BarefootJS->filter nil-tolerant convention).
sub filter ($items, $pred, $param, $base_env = undef) {
return [] unless ref $items eq 'ARRAY';
my %env = $base_env ? %$base_env : ();
my @out;
for my $item (@$items) {
$env{$param} = $item;
push @out, $item if _truthy(evaluate($pred, \%env));
}
return \@out;
}
# every â 1 iff the predicate holds for every element (vacuously 1 for an empty
# receiver, like JS).
sub every ($items, $pred, $param, $base_env = undef) {
my @arr = ref $items eq 'ARRAY' ? @$items : ();
my %env = $base_env ? %$base_env : ();
for my $item (@arr) {
$env{$param} = $item;
return 0 unless _truthy(evaluate($pred, \%env));
}
return 1;
}
# some â 1 iff the predicate holds for any element (0 for an empty receiver).
sub some ($items, $pred, $param, $base_env = undef) {
my @arr = ref $items eq 'ARRAY' ? @$items : ();
my %env = $base_env ? %$base_env : ();
for my $item (@arr) {
( run in 1.734 second using v1.01-cache-2.11-cpan-60884a8df76 )