BarefootJS

 view release on metacpan or  search on metacpan

lib/BarefootJS/Evaluator.pm  view on Meta::CPAN

package BarefootJS::Evaluator;
our $VERSION = "0.14.0";
use strict;
use warnings;
use utf8;
use feature 'signatures';
no warnings 'experimental::signatures';

use B ();
use POSIX ();
use JSON::PP ();
use Scalar::Util qw(looks_like_number);

# Lightweight evaluator for the pure `ParsedExpr` subset, scoped to
# higher-order callback bodies (reduce / sort / map / filter / find
# `(…) => expr`) — issue #2018. Templates cannot carry a lambda in
# expression position, which is why the adapters historically special-cased
# these callbacks into fixed shapes (bf_sort's comparator catalogue,
# bf_reduce's +/* fold). Instead, the callback BODY rides as a pure
# `ParsedExpr` subtree (the structured IR the compiler already produces) and
# is evaluated here against an environment (`{acc, item, …captured free
# vars}`).
#
# ONE shared implementation for both Perl backends (Mojo + Xslate), living
# alongside SearchParams.pm in the engine-agnostic core (no CPAN deps beyond
# core B / POSIX / Scalar::Util). The accepted subset and its semantics are
# documented in spec/compiler.md ("ParsedExpr Evaluator Semantics") and pinned
# isomorphically by the cross-language golden vectors
# (packages/adapter-tests/helper-vectors/eval-vectors.json), shared with the Go
# evaluator (bf.go) — same input → same output.
#
# The coercion below is JS-faithful (ToNumber / ToString / ToBoolean, strict
# equality) and deliberately distinct from the divergent bf->string / number
# helpers in BarefootJS.pm, so the contract is unambiguous and the two
# template adapters stay byte-equal with each other and with Go.

# evaluate($node, $env)
#
# Evaluate a decoded ParsedExpr node (a hashref keyed by `kind`) against the
# environment hashref ($env), returning a Perl value (number, string,
# JSON::PP::Boolean, undef for null, arrayref, hashref). The matching JSON
# entry point is eval_json() below.
sub evaluate ($node, $env) {
    return undef unless ref $node eq 'HASH';
    my $kind = $node->{kind} // '';

    if ($kind eq 'literal') {
        return $node->{value};
    }
    if ($kind eq 'identifier') {
        return $env->{ $node->{name} };
    }
    if ($kind eq 'binary') {
        return _binary($node->{op},
            evaluate($node->{left}, $env), evaluate($node->{right}, $env));
    }
    if ($kind eq 'unary') {
        return _unary($node->{op}, evaluate($node->{argument}, $env));
    }
    if ($kind eq 'logical') {
        my $op   = $node->{op};
        my $left = evaluate($node->{left}, $env);
        if ($op eq '&&') {
            return _truthy($left) ? evaluate($node->{right}, $env) : $left;
        }
        if ($op eq '||') {
            return _truthy($left) ? $left : evaluate($node->{right}, $env);
        }
        # `??`
        return defined $left ? $left : evaluate($node->{right}, $env);
    }
    if ($kind eq 'conditional') {
        return _truthy(evaluate($node->{test}, $env))
            ? evaluate($node->{consequent}, $env)
            : evaluate($node->{alternate}, $env);
    }
    if ($kind eq 'member') {
        return _read_property(evaluate($node->{object}, $env), $node->{property});
    }
    if ($kind eq 'index-access') {
        return _read_index(evaluate($node->{object}, $env), evaluate($node->{index}, $env));
    }
    if ($kind eq 'call') {
        # Nested `.map(cb)` / `.filter(cb)` (#2094) — e.g. a `.flatMap(p =>
        # p.tags.map(t => '#'+t))` projection body that itself contains a
        # `.map`/`.filter` call. Checked BEFORE builtin-name resolution
        # (the callee is a `member` node, never a bare/dotted builtin
        # identifier, so the two can't collide). Mirrors Go's
        # evalArrayCallbackCall / evalArrayCallback.
        my ($method, $object_node, $arrow_node) = _array_callback_call($node);
        if (defined $method) {
            return _array_callback($method, $object_node, $arrow_node, $env);
        }
        my $name = _builtin_name($node->{callee});
        return undef unless defined $name && $name ne '';
        my @args = map { evaluate($_, $env) } @{ $node->{args} // [] };
        return _call_builtin($name, \@args);
    }
    if ($kind eq 'template-literal') {

lib/BarefootJS/Evaluator.pm  view on Meta::CPAN

            return _bool(0);
        }
        if (_is_string($obj)) {
            return _bool(index($obj, _to_string($needle)) != -1);
        }
        # Any other receiver is not a JS `.includes` target — degrade to
        # false rather than throwing, mirroring the reference.
        return _bool(0);
    }
    if ($kind eq 'array-method' && ($node->{method} // '') eq 'join'
        && @{ $node->{args} // [] } <= 1)
    {
        # `.join(sep?)` (#2094), a sibling of `.includes` above in the
        # `array-method` node kind — needed for a composed case like
        # `.flatMap(p => p.tags.map(...).join(' ')).join(', ')`. JS
        # semantics: default separator is `,`; a `null`/`undefined`
        # element joins as `''` (NOT the string "null"). Mirrors the Go
        # evaluator's evalJoin.
        my $obj  = evaluate($node->{object}, $env);
        my $args = $node->{args} // [];
        my $sep  = @$args == 1 ? _to_string(evaluate($args->[0], $env)) : ',';
        return _join_array($obj, $sep);
    }

    # arrow-fn / higher-order / unsupported array-method: a callback body
    # containing these is refused upstream (BF101); never reached here.
    return undef;
}

# ---------------------------------------------------------------------------
# Nested `.map` / `.filter` callback recognition (#2094) — the evaluator
# widening that lets a callback body (already evaluated here for reduce /
# sort / filter / find / …) itself contain a `.map(cb)` or `.filter(cb)`
# call, e.g. the #1938 blog-showcase `.flatMap(p => p.tags.map(t => '#'+t))`
# projection. Everything else nested (`.some`/`.find`/`.every`/`.sort`/
# `.reduce`/`.flat`/`.flatMap`, standalone arrows) stays refused upstream —
# only `.map`/`.filter` are recognized here, mirroring Go's
# evalArrayCallbackCall / evalArrayCallback exactly.
# ---------------------------------------------------------------------------

# _array_callback_call($node): if $node (a `call` node) is a `.map(arrow)` /
# `.filter(arrow)` call — i.e. its callee is an uncomputed `member` node
# 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`/`undefined` (Perl `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 { defined $_ ? _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;
}

sub _nan {
    my $inf = 9**9**9;
    return $inf - $inf;
}

# ---------------------------------------------------------------------------
# JS coercion primitives (ToNumber / ToString / ToBoolean).
# ---------------------------------------------------------------------------

sub _to_number ($v) {
    return 0 if !defined $v;
    if (ref $v eq 'JSON::PP::Boolean') { return $v ? 1 : 0 }
    return _nan() if ref $v;
    if (_is_string($v)) {
        my $t = $v;
        $t =~ s/\A\s+//;
        $t =~ s/\s+\z//;
        return 0 if $t eq '';
        return looks_like_number($t) ? ($t + 0) : _nan();
    }
    return $v + 0;
}

sub _to_string ($v) {
    return 'null' if !defined $v;
    if (ref $v eq 'JSON::PP::Boolean') { return $v ? 'true' : 'false' }
    # JS spells the non-finite doubles "Infinity" / "-Infinity" / "NaN";
    # Perl stringifies them "Inf" / "-Inf" / "NaN", so the non-finite cases
    # are pinned here to stay JS-faithful (and match the Go evaluator's
    # evalToString). Finite numbers and strings fall through to plain
    # interpolation.
    if (_is_number($v)) {
        my $n = $v + 0;
        return 'NaN'       if $n != $n;
        return 'Infinity'  if $n == 9**9**9;
        return '-Infinity' if $n == -(9**9**9);
    }
    return "$v";
}

sub _truthy ($v) {
    return 0 if !defined $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"

lib/BarefootJS/Evaluator.pm  view on Meta::CPAN

            return $ln > 0 ? 9**9**9 : -(9**9**9);
        }
        return $ln / $rn;
    }
    if ($op eq '%') {
        my $rn = _to_number($r);
        return _nan() if $rn == 0;
        return POSIX::fmod(_to_number($l), $rn);
    }
    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;
}

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 = $l lt $r ? -1 : $l gt $r ? 1 : 0;
    }
    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);
}

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) {
        my ($lf, $rf) = ($l + 0, $r + 0);
        return 0 if $lf != $lf || $rf != $rf;    # NaN
        return $lf == $rf ? 1 : 0;
    }
    return 0 if $ln != $rn;    # one numeric, one not
    if (!defined $l) { return !defined $r ? 1 : 0 }
    return 0 if !defined $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;
    }
    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 '!';
    return -_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) {
    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;

lib/BarefootJS/Evaluator.pm  view on Meta::CPAN

# (findLast).
sub find ($items, $pred, $param, $forward = 1, $base_env = undef) {
    my @arr = ref $items eq 'ARRAY' ? @$items : ();
    @arr = reverse @arr unless $forward;
    my %env = $base_env ? %$base_env : ();
    for my $item (@arr) {
        $env{$param} = $item;
        return $item if _truthy(evaluate($pred, \%env));
    }
    return undef;
}

# find_index — index of the first matching element, or -1. $forward false →
# findLastIndex (the index is into the original array either way).
sub find_index ($items, $pred, $param, $forward = 1, $base_env = undef) {
    my @arr = ref $items eq 'ARRAY' ? @$items : ();
    my %env = $base_env ? %$base_env : ();
    my @idx = $forward ? ( 0 .. $#arr ) : reverse( 0 .. $#arr );
    for my $i (@idx) {
        $env{$param} = $arr[$i];
        return $i if _truthy(evaluate($pred, \%env));
    }
    return -1;
}

# flat_map — project each element through $proj (a pure ParsedExpr) and flatten
# the results one level. A projection yielding an arrayref contributes its
# elements; any other value contributes itself (JS `.flatMap` keeps a non-array
# return as a single element). Generalizes bf->flat_map / flat_map_tuple to any
# pure projection. Mirrors Go's FlatMapEval. $base_env is optional.
sub flat_map ($items, $proj, $param, $base_env = undef) {
    my @arr = ref $items eq 'ARRAY' ? @$items : ();
    my %env = $base_env ? %$base_env : ();
    my @out;
    for my $item (@arr) {
        $env{$param} = $item;
        my $v = evaluate($proj, \%env);
        if (ref $v eq 'ARRAY') { push @out, @$v }
        else                   { push @out, $v }
    }
    return \@out;
}

# map_items — project each element through $proj (a pure ParsedExpr), keeping
# each result as one element (no flatten): JS value-producing `.map(cb)`
# (#2073). Named map_items (not `map`) so the Perl builtin stays unshadowed.
# Mirrors Go's MapEval. $base_env is optional.
sub map_items ($items, $proj, $param, $base_env = undef) {
    my @arr = ref $items eq 'ARRAY' ? @$items : ();
    my %env = $base_env ? %$base_env : ();
    my @out;
    for my $item (@arr) {
        $env{$param} = $item;
        push @out, evaluate($proj, \%env);
    }
    return \@out;
}

# ---------------------------------------------------------------------------
# JSON-string seams — the adapters emit `bf->filter_eval($recv, '<json>', …)`;
# the predicate body arrives as a JSON string here, decoded then handed to the
# helper above (mirroring fold_json / sort_by_json).
# ---------------------------------------------------------------------------

sub filter_json ($items, $pred_json, $param, $base_env = undef) {
    require JSON::PP;
    return filter($items, JSON::PP->new->decode($pred_json), $param, $base_env);
}

sub every_json ($items, $pred_json, $param, $base_env = undef) {
    require JSON::PP;
    return every($items, JSON::PP->new->decode($pred_json), $param, $base_env);
}

sub some_json ($items, $pred_json, $param, $base_env = undef) {
    require JSON::PP;
    return some($items, JSON::PP->new->decode($pred_json), $param, $base_env);
}

sub find_json ($items, $pred_json, $param, $forward = 1, $base_env = undef) {
    require JSON::PP;
    return find($items, JSON::PP->new->decode($pred_json), $param, $forward, $base_env);
}

sub find_index_json ($items, $pred_json, $param, $forward = 1, $base_env = undef) {
    require JSON::PP;
    return find_index($items, JSON::PP->new->decode($pred_json), $param, $forward, $base_env);
}

sub flat_map_json ($items, $proj_json, $param, $base_env = undef) {
    require JSON::PP;
    return flat_map($items, JSON::PP->new->decode($proj_json), $param, $base_env);
}

sub map_json ($items, $proj_json, $param, $base_env = undef) {
    require JSON::PP;
    return map_items($items, JSON::PP->new->decode($proj_json), $param, $base_env);
}

1;



( run in 0.668 second using v1.01-cache-2.11-cpan-600a1bdf6e4 )