BarefootJS

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

| --- | --- |
| prop not passed | key left out |
| `undefined` passed (`c={props.c}` with `c` unset) | `{ c => $BarefootJS::UNDEF }` |
| `null` | `{ c => undef }` |
| a value | `{ c => 'x' }` |

A destructure default applies to the first two only. JSON decoded with
`JSON::PP` / `Mojo::JSON` gives `undef` for `null` and leaves a missing key
out, which is what you want; nothing walks decoded data to convert it.

`UNDEF` is false in boolean context, prints as `''` and numifies to NaN, but
it is `defined` in Perl's sense, and `//` keeps it. Test a value with
`BarefootJS::Undefined::is_undefined`, `is_null` and `is_nullish` (`== null`)
instead, or `$bf->is_nullish($v)` in a template.

Migration: a host that passed `undef` to mean "unset" now gets JS `null`
semantics (`'btn ' + c` renders `btn null`, and a destructure default no
longer applies). Leave the key out to leave a prop unset.

## Reference implementation

lib/BarefootJS.pm  view on Meta::CPAN


# The default of a helper's optional argument: the call passed none. JS
# reads an omitted argument as `undefined`, so `_omitted` accepts `UNDEF`
# too; an explicit `undef` is JS `null`, which each helper coerces like any
# other value (`[1, 2].slice(0, null)` is `[]`).
my $OMITTED = \'omitted';
sub _omitted { return (ref $_[0] && refaddr($_[0]) == refaddr($OMITTED)) || _undef_p($_[0]) ? 1 : 0 }

# JS ToString / ToNumber for a helper argument (a needle, a separator, a
# count), which spell `null` / `undefined` as JS does (`"null"` / 0,
# `"undefined"` / NaN); `string` / `number` are the display helpers.
sub _js_string { BarefootJS::Evaluator::_to_string($_[0]) }
sub _js_number { BarefootJS::Evaluator::_to_number($_[0]) }

# NOTE: This runtime is template-engine-agnostic AND framework-agnostic by
# design, so it can ship as a standalone CPAN distribution. It depends only on
# core Perl (subroutine signatures + the hand-rolled minimal accessor base
# below — no Mojo::Base, no Class::Tiny). Every operation that depends on *how*
# a template is rendered — JSON marshalling, raw-string marking, JSX-children
# materialisation, and named-template rendering — is delegated to a pluggable
# `backend` (see BarefootJS::Backend::Mojo for the reference Mojolicious

lib/BarefootJS.pm  view on Meta::CPAN

# ---------------------------------------------------------------------------
# JS-compat callees (#1189) — invoked from generated Mojo templates as
# <%= bf->json($val) %>, <%= bf->floor($val) %>, etc. The MojoAdapter's
# `templatePrimitives` registry emits these helper calls in place of the
# corresponding JS callees (`JSON.stringify`, `Math.floor`, …) so the SSR
# template can render value-equivalent output without a JS engine.
#
# Failure policy mirrors the Go adapter (#1188): user-data marshalling
# (json) bubbles errors so Mojolicious aborts loudly on cycles /
# unsupported values rather than silently producing an empty payload.
# Numeric coercion follows JS semantics (NaN propagates as the special
# string 'NaN'; non-numeric input returns 'NaN' rather than 0). Strings
# always coerce to a string representation.
# ---------------------------------------------------------------------------

sub json ($self, $value) {
    # `JSON.stringify`: `null` (`undef`) is "null"; `undefined` (`UNDEF`)
    # gives no string at the top level -- the result is `UNDEF` itself,
    # which prints nothing and omits an attribute -- an object member
    # holding it is skipped, and an array element holding it is written as
    # `null`.
    #
    # A number is written as JS writes it (`_format_number`): shortest
    # round-trip digits, `-0` as `0`, an unpadded exponent (`-4e-8`,
    # `-4e+21`), and NaN / Infinity as `null`, at any depth (#3787). The
    # encoders print `%.15g` (`0.3` for `0.1 + 0.2`), pad the exponent
    # (`-4e-08`) and spell Infinity `-Inf` or `"-Inf"`. Arrays and hashes
    # are walked here with sorted keys, as the canonical encoders do;
    # strings and other leaves go through the backend's encoder (Mojo's
    # `to_json` returns a character string, suitable for embedding in HTML
    # output via Mojo::ByteStream / `<%==`).
    return $value if _undef_p($value);
    my $ref = ref $value;
    return '[' . CORE::join(',', map { _undef_p($_) ? 'null' : $self->json($_) } @$value) . ']' if $ref eq 'ARRAY';
    if ($ref eq 'HASH') {

lib/BarefootJS.pm  view on Meta::CPAN

}

# A decoded JSON boolean (`Mojo::JSON::true` / `false`, a `JSON::PP::Boolean`).
sub _is_json_bool ($value) {
    my $ref = ref($value);
    return $ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool';
}

sub number ($self, $value) {
    # JS `Number(v)` mirror. Numeric coerces via Perl's implicit
    # numeric context; non-numeric / undef yield real numeric NaN
    # (`'nan' + 0`) so downstream arithmetic propagates correctly
    # (`Math.floor(NaN) === NaN`). Returning the literal string
    # "NaN" would conflate the user-passing-the-string-"NaN" case
    # with the parse-failure case, and break NaN detection in
    # downstream helpers.
    return 0 + 'nan' if _nullish($value);
    return $value + 0 if looks_like_number($value);
    return 0 + 'nan';
}

# JS `+` / `-` / `*` / `/` over numbers (#3454). The adapters emit these
# instead of Perl's native operators so the result is the IEEE double JS
# computes: a 64-bit IV sum past 2**53 rounds as a double, a perl with a
# wider NV (-Duselongdouble / -Dusequadmath) rounds to the double JS has,
# and division by zero yields +/-Infinity or NaN instead of dying. Each
# operand goes through JS ToNumber (`_num`): `undef` (`null`) is 0, `UNDEF`
# (`undefined`) NaN, a string its JS numeric value.
sub _as_double { unpack('d', pack('d', $_[0])) }
sub _num { _as_double(_js_number($_[0])) }

sub add ($self, $l, $r) {
    return _as_double(_num($l) + _num($r));
}

sub subtract ($self, $l, $r) {
    return _as_double(_num($l) - _num($r));
}

lib/BarefootJS.pm  view on Meta::CPAN

sub multiply ($self, $l, $r) {
    return _as_double(_num($l) * _num($r));
}

sub divide ($self, $l, $r) {
    return BarefootJS::Evaluator::_divide(_num($l), _num($r));
}

# JS `%` (#3474): the truncated remainder, which takes the dividend's sign
# (`-7 % 2` is -1) and keeps a fraction. Perl's native `%` floors (`-7 % 2`
# is 1) and converts both operands to integers (`NaN % 2` is 0).
sub mod ($self, $l, $r) {
    return BarefootJS::Evaluator::_remainder(_num($l), _num($r));
}

# NaN is the only float for which `$x != $x` holds. Used as the
# portable sentinel check in floor/ceil/round. The `Math` helpers coerce
# through JS ToNumber (`null` is 0, `undefined` NaN), as `Math.floor(null)`
# is 0.
sub _is_nan { my $n = shift; return $n != $n }

# True for +/-Infinity. `9**9**9` is Perl's portable infinity literal; a
# finite number is always strictly less than +Inf in magnitude.
sub _is_inf { my $n = shift; return $n == 9**9**9 || $n == -9**9**9 }

sub floor ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);

lib/BarefootJS.pm  view on Meta::CPAN

sub round ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);
    # POSIX has no `round`. JS `Math.round` rounds half toward
    # +Infinity (so `Math.round(-1.5) === -1`, not -2). `floor(n
    # + 0.5)` reproduces that for both signs.
    return POSIX::floor($n + 0.5);
}

# `Math.min(a, b)` / `Math.max(a, b)` -- two-arg forms only (#2168
# math-methods). JS returns NaN if either operand is NaN.
sub min ($self, $a, $b) {
    my $x = _js_number($a);
    my $y = _js_number($b);
    return $x if _is_nan($x);
    return $y if _is_nan($y);
    return $x < $y ? $x : $y;
}

sub max ($self, $a, $b) {
    my $x = _js_number($a);

lib/BarefootJS.pm  view on Meta::CPAN

# ---------------------------------------------------------------------------
#
# `Array.prototype.includes(x)` and `String.prototype.includes(sub)`
# share a method name in JS; the JSX parser can't tell the two
# receiver shapes apart without TS type inference, so both lower to
# the same IR node (`array-method` / method `includes`). This helper
# dispatches at the Perl level via `ref()`:
#   - ARRAY ref:  scan elements with `BarefootJS::Evaluator::_same_value_zero`,
#                 matching `Array.prototype.includes`'s SameValueZero
#                 semantics (no cross-type coercion, e.g. `[2].includes("2")`
#                 is false; NaN matches NaN) — the same algorithm the
#                 evaluator's serialized-callback path already uses for
#                 `.includes`, so both positions agree. This used to be a
#                 stringy `eq` scan, which coerced numbers to strings
#                 (`[2].includes("2")` was true) and diverged from JS.
#   - scalar:     `index($recv, $sub) != -1`, the needle JS ToString'd
#                 (`null` searches for "null", `undefined` for
#                 "undefined").
# Anything else (HASH ref, code ref) returns false — matches the
# JS semantic where `.includes` is only defined on Array /
# TypedArray / String.

lib/BarefootJS.pm  view on Meta::CPAN

# result is a Perl boolean, the same value the native operators yield.
sub strict_eq ($self, $l, $r) {
    return BarefootJS::Evaluator::_strict_eq($l, $r) ? !!1 : !!0;
}

# JS primitive helpers (spec/js-primitive-semantics.md, "Operation table"):
# ToBoolean, ToNumber, ToString, the relational operators, binary `+` and
# unary `-`. Each delegates to the callback evaluator's primitive of the same
# operation, so a template helper call and a callback body share one
# implementation. A boolean result is a Perl boolean, as `strict_eq`'s is.
# Unlike `number` and `string` (display helpers: `undef` / `UNDEF` -> NaN /
# ''), an `undef` operand reads as JS null here (0 / 'null') and `UNDEF` as JS
# undefined (NaN / 'undefined').
sub truthy ($self, $v) {
    return BarefootJS::Evaluator::_truthy($v) ? !!1 : !!0;
}

# Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapters
# spell `l || r` as `(keep_truthy(l) || [r])->[0]` and `l && r` as
# `(keep_falsy(l) || [r])->[0]`. `keep_truthy` is the one-element arrayref
# `[$v]` when `$v` is JS-truthy and undef otherwise (`keep_falsy` the
# reverse), so Perl's `||` stops at `$v`'s box exactly when JS returns `$v`
# itself and builds `[r]` only otherwise (the short circuit); `->[0]` unboxes

lib/BarefootJS.pm  view on Meta::CPAN

        # `undefined` only `undefined`.
        if (_nullish($item) || _nullish($elem)) {
            return $i if (!defined $item && !defined $elem) || (_undef_p($item) && _undef_p($elem));
            next;
        }
        return $i if $item eq $elem;
    }
    return -1;
}

# JS `ToIntegerOrInfinity` for a string position or index (#3613): NaN →
# 0, truncation toward zero, and ±Infinity clamped to ±2**53 so the
# caller's range check treats it as out of range (a bare `int()` keeps
# NaN, which then indexes element 0 with a warning).
sub _to_integer_or_infinity ($self, $value) {
    my $n = _js_number($value);
    return 0 if _is_nan($n);
    return 2**53 if $n >= 2**53;
    return -(2**53) if $n <= -(2**53);
    return int($n);
}

# `$s` as JS sees it: a list of UTF-16 code units. JS string positions
# (`indexOf`, `at`, `startsWith`'s position, …) count these, so an astral

lib/BarefootJS.pm  view on Meta::CPAN

        else {
            push @out, $el;
        }
    }
    return \@out;
}

# `Array.prototype.flat(depth)` with a DYNAMIC depth (#2094) — the depth is
# itself an arbitrary runtime value (e.g. a prop), not a compile-time literal,
# so it must be coerced with JS's `ToIntegerOrInfinity` before delegating to
# `flat` above: truncate toward zero; negative -> 0; NaN / non-numeric -> 0;
# +Infinity or a huge finite value -> flatten fully.
#
# Deliberately a SEPARATE entry point from `flat`, not a smarter version of
# it: the literal-depth path's `-1` argument is a compile-time SENTINEL baked
# into the template source, meaning "the source literally said `Infinity`". A
# genuinely dynamic depth that happens to evaluate to `-1` at render time
# means the OPPOSITE in real JS (`[1,[2]].flat(-1)` never recurses — same as
# `.flat(0)`). Since both paths would otherwise hand the same literal-looking
# argument to one shared function, that function couldn't tell which case
# it's in — so the two stay separate. Mirrors Go's `FlatDynamicDepth` /

lib/BarefootJS.pm  view on Meta::CPAN

    return $self->flat($recv, _coerce_flat_depth($depth));
}

# _coerce_flat_depth: JS `ToIntegerOrInfinity` for a dynamic `.flat(depth)`
# argument, collapsed to `flat`'s int contract (`-1` == flatten fully).
#
# Perl's scalar type system blurs string/number duality, so `looks_like_number`
# (already the codebase's ToNumber-style coercion check, see BarefootJS::
# Evaluator's `_to_number`) is reused here rather than inventing a new
# convention. `looks_like_number` on this Perl (5.38) already recognises the
# strings "Infinity" / "-Infinity" / "NaN" as numeric (verified empirically:
# `perl -MScalar::Util=looks_like_number -e 'print looks_like_number("Infinity")'`
# prints 1), and `$str + 0` on those strings yields the corresponding Perl
# non-finite double, so no extra string special-casing is needed here.
sub _coerce_flat_depth ($depth) {
    return 0 unless defined $depth;
    my $f;
    if (ref($depth) eq 'JSON::PP::Boolean') {
        $f = $depth ? 1 : 0;
    }
    elsif (!ref($depth) && looks_like_number($depth)) {
        $f = $depth + 0;
    }
    else {
        # undef handled above; anything else non-numeric (a plain string
        # that isn't a number, a HASH/ARRAY ref, ...) coerces via NaN.
        return 0;
    }
    return 0 if $f != $f;              # NaN
    return -1 if $f == 9**9**9;        # +Infinity -> flatten fully sentinel
    return 0  if $f == -(9**9**9);     # -Infinity -> 0
    my $trunc = int($f);               # Perl's int() truncates toward zero
    return 0  if $trunc < 0;
    return -1 if $trunc > 1_000_000;   # huge finite ~= flatten fully
    return $trunc;
}

# `Array.prototype.flatMap(fn)` value-returning field projection
# (#1448 Tier C) — map each element through a self / field projection,

lib/BarefootJS.pm  view on Meta::CPAN

# `Number.prototype.toFixed(digits)` (#1897) — fixed-decimal string with
# zero-padding. JS rounds the scaled integer half toward +Infinity (the
# spec's "pick the larger n" tie-break), so `(2.5).toFixed(0)` is "3";
# bare `sprintf("%.*f")` would round half-to-even ("2"), diverging. Scale
# by 10**digits, round with `floor(x + 0.5)` (the same tie-break the
# `round` helper uses), then format the exact multiple. A negative
# `digits` clamps to 0, mirroring how the adapters default an omitted
# argument.
sub to_fixed ($self, $value, $digits = $OMITTED) {
    my $n = $self->number($value);
    # JS toFixed returns the STRINGS "NaN" / "Infinity" / "-Infinity" for
    # non-finite inputs; the numeric values would stringify per-platform
    # ("nan"/"inf"/...) and diverge.
    return 'NaN' if _is_nan($n);
    return $n < 0 ? '-Infinity' : 'Infinity' if _is_inf($n);
    # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
    # makes `null` too.
    $digits = _omitted($digits) ? 0 : $self->_to_integer_or_infinity($digits);
    $digits = 0 if $digits < 0;
    my $factor  = 10 ** $digits;
    # Scaled as doubles, so `(1.005).toFixed(2)` sees JS's 100.49999… on a
    # perl whose NV is wider than a double (#3454).
    my $rounded = POSIX::floor(_as_double(_as_double($n) * $factor) + 0.5);
    return sprintf('%.*f', $digits, $rounded / $factor);

lib/BarefootJS.pm  view on Meta::CPAN

    else {
        # `quotemeta` forces literal-string matching (JS string-separator
        # semantics); the `-1` keeps trailing empty fields (JS keeps them,
        # Perl's bare `split` drops them).
        my $q = quotemeta("$sep");
        @parts = split /$q/, $s, -1;
    }

    # Optional `limit` caps the number of pieces (JS `split(sep, limit)`):
    # an omitted or `undefined` one is unbounded, any other one ToUint32'd
    # (`null` and NaN are 0 → empty; a negative limit wraps to a large one,
    # effectively unbounded).
    unless (_omitted($limit)) {
        my $n = _to_uint32($limit);
        @parts = @parts[0 .. $n - 1] if $n < scalar @parts;
    }

    return [@parts];
}

# `String.prototype.startsWith(prefix, position?)` (#1448 Tier B) —

lib/BarefootJS.pm  view on Meta::CPAN

sub pad_start ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    return $self->_pad($s, $target, $pad, 1);
}

sub pad_end ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    return $self->_pad($s, $target, $pad, 0);
}

# JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
sub _to_uint32 ($value) {
    my $n = _js_number($value);
    return 0 if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
    my $t = $n < 0 ? POSIX::ceil($n) : POSIX::floor($n);
    $t = POSIX::fmod($t, 4294967296);
    $t += 4294967296 if $t < 0;
    return $t;
}

# A row field's value: JS `item.key`, `undefined` when the row has no such

lib/BarefootJS.pm  view on Meta::CPAN


    my @sorted = sort $cmp @keyed;
    return [ (map { $_->[1] } @sorted), @tail ];
}

# Compare two projected keys, ascending orientation (-1 / 0 / 1); the
# caller negates for 'desc'. 'auto' compares numerically when both
# keys look like numbers, else lexically (matches Go's `bf_sort`).
# A nil key (`null` / `undefined`) reads as '' lexically and `null` as 0
# numerically, so the order stays total without warnings; a numeric
# `a.f - b.f` over an `undefined` key is NaN, which the sort reads as
# "equal".
sub _compare_sort_key ($av, $bv, $compare_type) {
    my $str = sub ($v) { _nullish($v) ? '' : $v };
    if ($compare_type eq 'string') {
        return $str->($av) cmp $str->($bv);
    }
    if ($compare_type eq 'auto') {
        if (!_undef_p($av) && !_undef_p($bv) && looks_like_number($av // '') && looks_like_number($bv // '')) {
            return ($av // 0) <=> ($bv // 0);
        }

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

    return $content;
}

# The browser snippet: a small IIFE — EventSource subscriber + scrollY
# preservation across reloads. Idempotent across duplicate mounts (the
# window.__bfDevReload guard). Returns a plain HTML string; callers mark it raw
# for their template engine.
sub snippet ($class, $endpoint) {
    my $ep = _js_str($endpoint);
    my $sk = _js_str($SCROLL_STORAGE_KEY);
    return qq{<script>(function(){if(window.__bfDevReload)return;window.__bfDevReload=1;try{var s=sessionStorage.getItem($sk);if(s){sessionStorage.removeItem($sk);var y=parseInt(s,10);if(!isNaN(y)){var restore=function(){window.scrollTo(0,y)};if(docu...
}

# A ready-made PSGI app for the SSE endpoint. Streams `event: reload` whenever
# <dist>/.dev/build-id changes, with `: hb` heartbeats in between.
#
# Implemented with the PSGI streaming interface and a blocking poll loop, so it
# holds one worker per open connection for the connection's lifetime — run it
# under a prefork PSGI server (Starman / Starlet) in dev, which is the natural
# choice for an app that also streams (e.g. an AI-chat SSE route). DevReload is
# automatically a no-op unless you mount it, and you should only mount it in

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

    }
    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);

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

    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;

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


# _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);

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

    }
    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() }

# ---------------------------------------------------------------------------

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

    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

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

}

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) {

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

    # 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 '+';

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

    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
# ---------------------------------------------------------------------------

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

    # 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.

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

# nullish receiver, the `undefined` identifier (`bf->undefined` in a
# template), an omitted declared prop. No decoded data is walked to convert
# anything.
#
# It is a blessed scalar reference with overloads, so Perl's own operators
# see it as JS sees `undefined` where they can:
#
# - `bool` is false: a native `if` / `unless` / `?:` / `!` reads it as falsy.
# - `""` is `''`: printed in a text or attribute position it renders nothing,
#   as JS renders `undefined` there.
# - `0+` is NaN: native arithmetic over it is NaN, as JS ToNumber.
# - `%{}` / `@{}` give a fresh empty hash / array, so a stray `->{k}` read or
#   an `@{...}` loop over it reads nothing instead of dying.
# - any method call (Kolon's `$x.k`, `$x.size()`) returns the singleton.
#
# It is NOT `undef`: Perl's `defined` is true for it and `//` keeps it. So
# every runtime and emitter site that means JS "nullish" tests through
# `is_nullish` below (or `$bf->is_nullish` in a template), never `defined` /
# `//`. A strict `=== null` is `is_null`, `=== undefined` is `is_undefined`.
#
# Identity is the class, not the address: a host's deep copy of a props

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


    my $u = $BarefootJS::UNDEF;               # JS undefined
    BarefootJS::Undefined::is_undefined($u);  # 1
    BarefootJS::Undefined::is_null(undef);    # 1 (Perl undef is JS null)
    BarefootJS::Undefined::is_nullish($u);    # 1

=head1 DESCRIPTION

Perl's C<undef> is JS C<null>. JS C<undefined> is the singleton
C<$BarefootJS::UNDEF>, which is false in boolean context, prints as C<''>,
numifies to NaN, and is C<defined> in Perl's sense. Test it with
C<is_undefined>, C<is_null> and C<is_nullish>, never with C<defined> or C<//>.

=cut

t/eval_vectors.t  view on Meta::CPAN

# _match: boolean form of the spec's value-compat comparison against a
# JSON-decoded expect — non-finite sentinel hashes, booleans by truthiness,
# numbers numerically, arrays/hashes recursively, strings by eq.
sub _match {
    my ($got, $expect) = @_;
    return VectorUndefined::runtime_undefined($got) if VectorUndefined::is_sentinel($expect);
    return !defined $got if !defined $expect;
    if (ref $expect eq 'HASH' && exists $expect->{'$num'}) {
        my $kind = $expect->{'$num'};
        return 0 unless defined $got && looks_like_number($got);
        return $got != $got ? 1 : 0 if $kind eq 'NaN';
        my $inf = 9**9**9;
        return $got == ($kind eq 'Infinity' ? $inf : -$inf) ? 1 : 0;
    }
    if (JSON::PP::is_bool($expect)) {
        # The result must itself be a JS boolean (JSON::PP::Boolean), not a
        # truthy/falsy 1/0 — otherwise a boolean-valued expression returning
        # the number 1 instead of `true` would pass and mask the divergence.
        return 0 unless JSON::PP::is_bool($got);
        return (!!$got eq !!$expect) ? 1 : 0;
    }

t/evaluator.t  view on Meta::CPAN


# Descending is just a reversed comparator body — no separate direction knob.
subtest 'sort_by: descending via a reversed comparator' => sub {
    my $cmp = nbin('-', nmem(nid('b'), 'x'), nmem(nid('a'), 'x'));
    my $items  = [ { x => 10 }, { x => 30 }, { x => 20 } ];
    my $sorted = BarefootJS::Evaluator::sort_by($items, $cmp, 'a', 'b');
    is_deeply([ map { $_->{x} } @$sorted ], [ 30, 20, 10 ], 'descending by x');
};

# Non-finite coercion stays JS-faithful (and matches the Go evaluator):
# division by zero is ±Infinity / NaN rather than a Perl die, and those
# values stringify as "Infinity" / "-Infinity" / "NaN" (not Perl's "Inf").
subtest 'non-finite: division by zero and JS stringification' => sub {
    my $div = sub {
        my ($a, $b) = @_;
        BarefootJS::Evaluator::evaluate(
            nbin('/', { kind => 'identifier', name => 'a' }, { kind => 'identifier', name => 'b' }),
            { a => $a, b => $b },
        );
    };
    my $inf = 9**9**9;
    is($div->(1, 0),  $inf,  '1/0 is +Infinity, not a die');
    is($div->(-1, 0), -$inf, '-1/0 is -Infinity');
    my $nan = $div->(0, 0);
    ok($nan != $nan, '0/0 is NaN');

    is(BarefootJS::Evaluator::_to_string($inf),    'Infinity',  'String(Infinity)');
    is(BarefootJS::Evaluator::_to_string(-$inf),   '-Infinity', 'String(-Infinity)');
    is(BarefootJS::Evaluator::_to_string($inf - $inf), 'NaN',   'String(NaN)');
};

# Captured free vars flow through $base_env (mirrors the Go FoldEval/SortEval
# baseEnv test) — a reducer / comparator body can reference an outer const.
subtest 'captured free vars via base_env' => sub {
    # reduce: acc + item * factor, with `factor` captured.
    my $body = nbin('+', nid('acc'), nbin('*', nid('item'), nid('factor')));
    my $sum = BarefootJS::Evaluator::fold([1, 2, 3], $body, 'acc', 'item', 0, 'left', { factor => 10 });
    is($sum, 60, '0 + 1*10 + 2*10 + 3*10 with captured factor');

t/evaluator.t  view on Meta::CPAN

    # A -0 from arithmetic underflow (`-1e-300 * 1e-300`) flips the sign of
    # the infinity, as in JS. The template runtime's `divide` shares the
    # decision with the evaluator.
    require BarefootJS;
    my $bf = bless {}, 'BarefootJS';
    my $neg_zero = $bf->multiply(-1e-300, 1e-300);
    is($bf->string($bf->divide(1, $neg_zero)),  '-Infinity', 'runtime: 1 / -0');
    is($bf->string($bf->divide(-1, $neg_zero)), 'Infinity',  'runtime: -1 / -0');
    is($bf->string($bf->divide(1, 0)),          'Infinity',  'runtime: 1 / 0');
    is($bf->string($bf->divide(-1, 0)),         '-Infinity', 'runtime: -1 / 0');
    is($bf->string($bf->divide(0, $neg_zero)),  'NaN',       'runtime: 0 / -0');
    my $num = sub { { kind => 'literal', value => $_[0], literalType => 'number' } };
    my $under = nbin('*', $num->(-1e-300), $num->(1e-300));
    is(BarefootJS::Evaluator::_format_number(BarefootJS::Evaluator::evaluate(nbin('/', $num->(1), $under), {})),
        '-Infinity', 'evaluator: 1 / (-1e-300 * 1e-300)');
};

subtest 'remainder takes the dividend sign (#3474)' => sub {
    # JS `%` truncates: the result takes the dividend's sign and keeps a
    # fraction, where Perl's native `%` floors and works on integers. The
    # template runtime's `mod` shares the decision with the evaluator.
    require BarefootJS;
    my $bf = bless {}, 'BarefootJS';
    is($bf->string($bf->mod(-7, 2)),   '-1',  'runtime: -7 % 2');
    is($bf->string($bf->mod(7, -2)),   '1',   'runtime: 7 % -2');
    is($bf->string($bf->mod(-7, -2)),  '-1',  'runtime: -7 % -2');
    is($bf->string($bf->mod(7.5, 2)),  '1.5', 'runtime: 7.5 % 2');
    is($bf->string($bf->mod(7, 0)),    'NaN', 'runtime: 7 % 0');
    is($bf->string($bf->mod($bf->number(undef), 2)), 'NaN', 'runtime: NaN % 2');
    is($bf->string($bf->mod(9**9**9, 2)), 'NaN', 'runtime: Infinity % 2');
    is($bf->string($bf->mod(undef, 2)), '0',  'runtime: a nil operand reads as 0');
    my $num = sub { { kind => 'literal', value => $_[0], literalType => 'number' } };
    is(BarefootJS::Evaluator::_format_number(BarefootJS::Evaluator::evaluate(nbin('%', $num->(-7), $num->(2)), {})),
        '-1', 'evaluator: -7 % 2');
    # A zero remainder of a negative dividend is -0: it prints "0", and the
    # sign shows through a later division.
    is($bf->string($bf->mod(-4, 2)), '0', 'runtime: -4 % 2 prints 0');
    is($bf->string($bf->divide(1, $bf->mod(-4, 2))), '-Infinity', 'runtime: 1 / (-4 % 2)');
    is($bf->string($bf->divide(1, $bf->mod(4, 2))),  'Infinity',  'runtime: 1 / (4 % 2)');
    is(BarefootJS::Evaluator::_format_number(BarefootJS::Evaluator::evaluate(

t/helper_vectors.t  view on Meta::CPAN

# _match: boolean form of the spec's value-compat comparison against a
# JSON-decoded expect — sentinel hashes, booleans by truthiness,
# numbers numerically, arrays/hashes recursively.
sub _match {
    my ($got, $expect) = @_;
    return VectorUndefined::runtime_undefined($got) if VectorUndefined::is_sentinel($expect);
    return !defined $got if !defined $expect;
    if (ref $expect eq 'HASH' && exists $expect->{'$num'}) {
        my $kind = $expect->{'$num'};
        return 0 unless defined $got && looks_like_number($got);
        return $got != $got ? 1 : 0 if $kind eq 'NaN';
        my $inf = 9**9**9;
        return $got == ($kind eq 'Infinity' ? $inf : -$inf) ? 1 : 0;
    }
    if (JSON::PP::is_bool($expect)) {
        return (!!$got eq !!$expect) ? 1 : 0;
    }
    if (ref $expect eq 'ARRAY') {
        return 0 unless ref $got eq 'ARRAY' && @$got == @$expect;
        _match($got->[$_], $expect->[$_]) or return 0 for 0 .. $#$expect;
        return 1;

t/primitive_vectors.t  view on Meta::CPAN

    # numbers or booleans with Perl's numeric `==` (#3824 step 8).
    strict_eq => sub {
        my ($a, $b) = @_;
        my $both_strings = BarefootJS::Evaluator::_is_string($a) && BarefootJS::Evaluator::_is_string($b);
        ($both_strings ? $a eq $b : $a == $b) ? !!1 : !!0;
    },
);

my $INF = 9**9**9;
my %SENTINEL = (
    'NaN'       => sub { $INF - $INF },
    'Infinity'  => sub { $INF },
    '-Infinity' => sub { -$INF },
    '-0'        => sub { -1 / $INF },
);

# Arguments keep JSON::PP booleans: the evaluator primitives the helpers
# delegate to read them as JS booleans. `$num` sentinels become doubles.
sub decode_arg {
    my ($v) = @_;
    return VectorUndefined::arg() if VectorUndefined::is_sentinel($v);

t/template_primitives.t  view on Meta::CPAN

    is $bf->string('hi'),  'hi', 'string passthrough';
    # Documented divergence from JS String(null) === "null".
    is $bf->string(undef), '',   'undef → "" (intentional divergence)';
    is $bf->string(JSON::PP::true),  'true',  'JSON true → "true" (#3440)';
    is $bf->string(JSON::PP::false), 'false', 'JSON false → "false" (#3440)';
    is $bf->bool_str('false'), 'false', 'bool_str keeps a stringified false (#3440)';
    is $bf->bool_str('true'),  'true',  'bool_str keeps a stringified true';
    is $bf->bool_str(0),       'false', 'bool_str of a Perl false';
};

# Real numeric NaN is the only float for which `$x != $x` holds.
# Tests check for it directly rather than string-comparing against
# "NaN", which stringifies platform-dependently.
sub is_nan { my $n = shift; return $n != $n }

subtest 'number — JS Number(v) mirror; NaN on parse failure' => sub {
    is $bf->number('3.14'), 3.14, 'numeric string';
    is $bf->number(42),     42,   'integer passthrough';
    ok is_nan($bf->number('not a num')), 'non-numeric → NaN';
    ok is_nan($bf->number(undef)),       'undef → NaN';
};

subtest 'floor / ceil / round — Math.* mirrors; propagate NaN' => sub {
    is $bf->floor(3.7),    3, '3.7 → 3';
    is $bf->floor(-3.2),  -4, '-3.2 → -4';
    ok is_nan($bf->floor('not')), 'floor: NaN propagates';

    is $bf->ceil(3.1),     4, '3.1 → 4';
    is $bf->ceil(-3.7),   -3, '-3.7 → -3';
    ok is_nan($bf->ceil('not')), 'ceil: NaN propagates';

    is $bf->round(3.5),    4, '3.5 → 4';
    is $bf->round(3.4),    3, '3.4 → 3';
    # JS `Math.round` ties go toward +Infinity, NOT away from zero —
    # so -1.5 rounds to -1 (not -2). Pin both halves of the negative
    # tie-break so a future POSIX::floor swap doesn't silently
    # regress the JS-compat contract.
    is $bf->round(-1.5),  -1, '-1.5 → -1 (JS half-toward-+Inf, not half-away-from-zero)';
    is $bf->round(-1.6),  -2, '-1.6 → -2';
    ok is_nan($bf->round('not')), 'round: NaN propagates';
};

# `Math.min(a, b)` / `Math.max(a, b)` (two-arg forms only) and
# `Math.abs()` (#2168 math-methods). JS returns NaN if EITHER min/max
# operand is NaN.
subtest 'min / max / abs — Math.* mirrors; propagate NaN' => sub {
    is $bf->min(3, 7),    3, 'min(3, 7) → 3';
    is $bf->min(7, 3),    3, 'min(7, 3) → 3 (order-independent)';
    is $bf->min(-2, -5), -5, 'min(-2, -5) → -5';
    ok is_nan($bf->min('not', 5)), 'min: NaN in first arg propagates';
    ok is_nan($bf->min(5, 'not')), 'min: NaN in second arg propagates';

    is $bf->max(3, 7),    7, 'max(3, 7) → 7';
    is $bf->max(7, 3),    7, 'max(7, 3) → 7 (order-independent)';
    is $bf->max(-2, -5), -2, 'max(-2, -5) → -2';
    ok is_nan($bf->max('not', 5)), 'max: NaN in first arg propagates';
    ok is_nan($bf->max(5, 'not')), 'max: NaN in second arg propagates';

    # The helpers answer a double, as JS does; on a perl built with
    # -Duselongdouble a bare `7.6` is the wider NV, so compare both as
    # doubles (#3445, #3872).
    my $double = \&BarefootJS::Evaluator::_double;
    is $double->($bf->abs(-7.6)), $double->(7.6), 'abs(-7.6) → 7.6';
    is $double->($bf->abs(7.6)),  $double->(7.6), 'abs(7.6) → 7.6 (no-op)';
    is $bf->abs(0),    0,   'abs(0) → 0';
    ok is_nan($bf->abs('not')), 'abs: NaN propagates';
};

# `Array.prototype.includes(x)` + `String.prototype.includes(sub)` lower
# to the same `$bf->includes($recv, $elem)` shape — see #1448 Tier A.
# The Perl helper dispatches on `ref()`: ARRAY ref scans elements with
# `BarefootJS::Evaluator::_same_value_zero` (SameValueZero — no cross-type
# coercion, NaN matches NaN), matching the evaluator's serialized-callback
# `.includes` path so both positions agree; scalar falls back to
# `index(..., ...) != -1`. Anything else (HASH ref, code ref) returns
# false to match the JS semantic that `.includes` is only defined on
# Array / TypedArray / String.
subtest 'includes — array + string + non-array/string dispatch' => sub {
    # Array receiver: SameValueZero element search (handles defined/undef
    # parity, and no numeric/string coercion — see the cross-type cases
    # below).
    ok  $bf->includes(['a', 'b', 'c'], 'b'), 'array contains element → 1';
    ok !$bf->includes(['a', 'b', 'c'], 'z'), 'array does not contain → 0';

t/template_primitives.t  view on Meta::CPAN

    ok $bf->strict_eq('p', 'p'), 'equal strings are equal';
    ok !$bf->strict_eq('', 'a'), 'empty string vs non-empty string';
    ok !$bf->strict_eq('001', '1'), 'numeric-looking strings compare by content';
    ok $bf->strict_eq(1, 1.0), 'numbers compare by value';
    ok $bf->strict_eq(0, -0.0), '0 === -0';
    ok $bf->strict_eq(1e3, 1000), 'exponent notation is the same number';
    ok !$bf->strict_eq(0.5, 1), 'different numbers are not equal';
    ok !$bf->strict_eq(1, '1'), 'number vs string of the same digits';
    ok !$bf->strict_eq('abc', 0), 'non-numeric string vs 0';
    my $nan = 0 + 'nan';
    ok !$bf->strict_eq($nan, $nan), 'NaN !== NaN';
    ok $bf->strict_eq(undef, undef), 'undef === undef';
    ok !$bf->strict_eq(undef, 0), 'undef vs 0';
    ok !$bf->strict_eq(undef, ''), 'undef vs empty string';
    ok $bf->strict_eq(JSON::PP::true(), JSON::PP::true()), 'true === true';
    ok !$bf->strict_eq(JSON::PP::true(), JSON::PP::false()), 'true !== false';
    ok !$bf->strict_eq(JSON::PP::true(), 1), 'true !== 1';
    my ($obj, $arr) = ({ id => 1 }, [1]);
    ok $bf->strict_eq($obj, $obj), 'the same hash ref is equal to itself';
    ok $bf->strict_eq($arr, $arr), 'the same array ref is equal to itself';
    ok !$bf->strict_eq({ id => 1 }, { id => 1 }), 'distinct hashes with equal contents are not equal';

t/template_primitives.t  view on Meta::CPAN

    ok BarefootJS::Undefined::is_undefined($bf->at('', 0)), 'at empty string';
    is $bf->at('a😀b', 1),    "\x{FFFD}", 'at half of a surrogate pair → U+FFFD';
    ok  $bf->starts_with('日本語', '本', 1), 'startsWith BMP position';
    ok  $bf->starts_with('a😀b', 'b', 3),   'startsWith position after astral';
    ok !$bf->starts_with('a😀b', 'b', 2),   'startsWith position inside pair';
    ok  $bf->ends_with('日本語', '本', 2),   'endsWith BMP endPosition';
    ok  $bf->ends_with('a😀b', '😀', 3),     'endsWith astral endPosition';
    ok !$bf->ends_with('a😀b', 'a', 2),     'endsWith endPosition inside pair';
};

# ToIntegerOrInfinity for the string index paths (#3613): NaN is 0,
# ±Infinity is out of range, fractions truncate toward zero.
subtest 'string index methods read non-finite positions as ToIntegerOrInfinity' => sub {
    my $inf = 9**9**9;
    my $nan = $inf - $inf;
    is $bf->at('abc', $nan),   'a',   'at(NaN) is at(0)';
    ok BarefootJS::Undefined::is_undefined($bf->at('abc', $inf)), 'at(Infinity) is out of range';
    ok BarefootJS::Undefined::is_undefined($bf->at('abc', -$inf)), 'at(-Infinity) is out of range';
    is $bf->at('abc', 1.9),    'b',   'at(1.9) truncates';
    is $bf->at('abc', -1.5),   'c',   'at(-1.5) truncates toward zero';
    ok  $bf->starts_with('abc', 'a', $nan), 'startsWith NaN position is 0';
    ok  $bf->starts_with('abc', '', $inf),  'startsWith Infinity position clamps';
    ok !$bf->ends_with('abc', 'c', $nan),   'endsWith NaN endPosition is 0';
    ok  $bf->ends_with('abc', 'c', $inf),   'endsWith Infinity endPosition clamps';
};

# `Array.prototype.concat(other)` — merges two arrays in order
# into a new ARRAY ref (#1448 Tier A). Non-array operands collapse
# to empty (matches the Go `bf_concat` semantic); the result must
# compose with `.join(...)` etc., hence the ARRAY ref return type.
subtest 'concat — merges two arrays into a new array ref' => sub {
    is $bf->concat(['a','b'], ['c','d']),    ['a','b','c','d'],     'two non-empty arrays';
    is $bf->concat([],         ['a']),       ['a'],                 'empty + non-empty';

t/undefined.t  view on Meta::CPAN

    ok $bf->is_undefined($U) && $bf->is_null(undef) && $bf->is_nullish($U) && $bf->is_nullish(undef),
        'the template helpers';
    ok !$bf->is_null($U) && !$bf->is_undefined(undef) && !$bf->is_nullish(0), 'and their negatives';
};

subtest "Perl's own view of the value" => sub {
    ok !$U, 'false in boolean context';
    ok defined $U, 'but defined: `defined` and `//` must not test it';
    is(($U // 'd'), $U, '`//` keeps it');
    is "[$U]", '[]', 'prints as the empty string';
    ok $nan->($U + 0), 'numifies to NaN';
    is scalar(@{$U}), 0, 'an array dereference reads nothing';
    ok !defined $U->{k}, 'a hash dereference reads nothing';
    ok $is_u->($U->size), 'a method call (Kolon member syntax) reads undefined';
};

subtest 'a template prints undefined as empty' => sub {
    is $bf->string($U), '', 'display string';
    is $bf->string(undef), '', 'display string of null';
    ok $nan->($bf->number($U)), 'display number';
    ok $is_u->($bf->json($U)), 'json of a top-level undefined is undefined (no string)';

t/undefined.t  view on Meta::CPAN


subtest 'coercions tell the nils apart' => sub {
    is $bf->to_string($U), 'undefined', 'ToString(undefined)';
    is $bf->to_string(undef), 'null', 'ToString(null)';
    is $bf->plus($U, 'x'), 'undefinedx', 'undefined + "x"';
    ok $nan->($bf->plus($U, 1)), 'undefined + 1';
    ok $nan->($bf->to_number($U)), 'ToNumber(undefined)';
    is $bf->to_number(undef), 0, 'ToNumber(null)';
    is $bf->subtract(undef, 1), -1, 'null - 1';
    ok $nan->($bf->multiply($U, 2)), 'undefined * 2';
    ok $nan->($bf->subtract('abc', 1)), '"abc" - 1 is NaN (JS ToNumber)';
    ok $nan->($bf->mod($U, 2)), 'undefined % 2';
    ok $bf->strict_eq($U, $U), 'undefined === undefined';
    ok !$bf->strict_eq($U, undef), 'undefined !== null';
    ok !$bf->lt($U, 1), 'undefined < 1 is false';
    ok $bf->le(undef, 0), 'null <= 0 is true';
    ok $nan->($bf->floor($U)), 'Math.floor(undefined)';
    is $bf->floor(undef), 0, 'Math.floor(null)';
    ok !$bf->truthy($U), 'ToBoolean(undefined)';
};

t/undefined.t  view on Meta::CPAN

    my $coalesce = { kind => 'logical', op => '??', left => $missing, right => { kind => 'literal', value => 'd' } };
    is $ev->($coalesce, { o => {} }), 'd', '?? over undefined';
    is $ev->($coalesce, { o => { x => undef } }), 'd', '?? over null';
    is $ev->($coalesce, { o => { x => 0 } }), 0, '?? keeps 0';
};

subtest 'String() and Number() with no argument' => sub {
    my $call = sub { BarefootJS::Evaluator::_call_builtin($_[0], $_[1]) };
    is $call->('Number', []), 0, 'Number() is 0';
    is $call->('String', []), '', 'String() is ""';
    ok $nan->($call->('Number', [$U])), 'Number(undefined) is NaN';
    is $call->('String', [$U]), 'undefined', 'String(undefined)';
};

done_testing;



( run in 4.340 seconds using v1.01-cache-2.11-cpan-60884a8df76 )