BarefootJS

 view release on metacpan or  search on metacpan

t/evaluator.t  view on Meta::CPAN

sub nstr { return { kind => 'literal', value => $_[0], literalType => 'string' } }

sub ncall_math {
    my ($fn, $arg) = @_;
    return { kind => 'call', callee => nmem(nid('Math'), $fn), args => [$arg] };
}

sub nincludes {
    my ($object, $needle) = @_;
    return { kind => 'array-method', method => 'includes', object => $object, args => [$needle] };
}

# A plain false for the `computed` flag; the evaluator only checks truthiness.
sub JSON_false { return 0 }

# fold lifts bf_reduce's op restriction and acc-canonical form: a reducer body
# that mixes acc with a product of two fields is impossible in the +/*
# self/field catalogue but trivial for the evaluator.
subtest 'fold: arbitrary reducer body (acc + item.price * item.qty)' => sub {
    my $body = nbin('+',
        nid('acc'),
        nbin('*', nmem(nid('item'), 'price'), nmem(nid('item'), 'qty')),
    );
    my $items = [ { price => 5, qty => 3 }, { price => 2, qty => 4 } ];
    is(BarefootJS::Evaluator::fold($items, $body, 'acc', 'item', 0, 'left'),
        23, '0 + 5*3 + 2*4');
};

# reduceRight is observable for string concatenation; the same body folds both
# directions.
subtest 'fold: direction is observable for string concat' => sub {
    my $body  = nbin('+', nid('acc'), nid('item'));
    my $items = [ 'a', 'b', 'c' ];
    is(BarefootJS::Evaluator::fold($items, $body, 'acc', 'item', '', 'left'),  'abc', 'left');
    is(BarefootJS::Evaluator::fold($items, $body, 'acc', 'item', '', 'right'), 'cba', 'right');
};

# sort_by lifts bf_sort's comparator pattern restriction: a comparator that
# calls Math.abs on each operand's field is outside the subtraction /
# localeCompare / relational-ternary catalogue, but is just another pure
# expression to the evaluator.
subtest 'sort_by: arbitrary comparator body (abs-of-field difference)' => sub {
    my $cmp = nbin('-',
        ncall_math('abs', nmem(nid('a'), 'v')),
        ncall_math('abs', nmem(nid('b'), 'v')),
    );
    my $items  = [ { v => -5 }, { v => 3 }, { v => -1 } ];
    my $sorted = BarefootJS::Evaluator::sort_by($items, $cmp, 'a', 'b');
    is_deeply([ map { $_->{v} } @$sorted ], [ -1, 3, -5 ], 'ascending by |v|');
};

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

    # sort by distance from a captured `pivot`: |a-pivot| - |b-pivot|.
    my $cmp = nbin('-',
        ncall_math('abs', nbin('-', nid('a'), nid('pivot'))),
        ncall_math('abs', nbin('-', nid('b'), nid('pivot'))),
    );
    my $sorted = BarefootJS::Evaluator::sort_by([1, 8, 4], $cmp, 'a', 'b', { pivot => 5 });
    is_deeply($sorted, [4, 8, 1], 'ascending by distance from captured pivot');
};

# Boolean-valued operators return JS booleans (JSON::PP::Boolean), not 1/0 —
# matching the Go evaluator, so they stringify "true"/"false" and concatenate
# as JS does.
subtest 'boolean-valued ops return JS booleans, not 1/0' => sub {
    my $lt = BarefootJS::Evaluator::evaluate(nbin('<', nid('a'), nid('b')), { a => 1, b => 2 });
    ok(JSON::PP::is_bool($lt), 'a < b is a JS boolean');
    is(BarefootJS::Evaluator::_to_string($lt), 'true', 'String(a < b) is "true", not "1"');

    my $cat = BarefootJS::Evaluator::evaluate(
        nbin('+', nstr('x'), nbin('<', nid('a'), nid('b'))), { a => 1, b => 2 });
    is($cat, 'xtrue', "'x' + (a < b) is 'xtrue', not 'x1'");

    my $eq = BarefootJS::Evaluator::evaluate(nbin('===', nid('a'), nid('b')), { a => 1, b => 1 });
    ok(JSON::PP::is_bool($eq), '1 === 1 is a JS boolean');

    my $not = BarefootJS::Evaluator::evaluate({ kind => 'unary', op => '!', argument => nstr('') }, {});
    is(BarefootJS::Evaluator::_to_string($not), 'true', 'String(!"") is "true"');

    my $b = BarefootJS::Evaluator::evaluate(
        { kind => 'call', callee => nid('Boolean'), args => [nstr('')] }, {});
    ok(JSON::PP::is_bool($b), 'Boolean("") is a JS boolean');
    is(BarefootJS::Evaluator::_to_string($b), 'false', 'String(Boolean("")) is "false", not "0"');

    # `.length` is a string/array property only; a numeric scalar has none.
    my $len = BarefootJS::Evaluator::evaluate(nmem(nid('n'), 'length'), { n => 123 });
    ok(BarefootJS::Undefined::is_undefined($len), '(123).length is undefined, not 3');

    # #2196: `.length` counts codepoints even when the input string does NOT
    # carry Perl's internal UTF8 flag — the real-world shape a decoded-JSON
    # or raw-request scalar can arrive in. Build "café" (4 codepoints),
    # force the UTF8 flag on with `utf8::upgrade` (a Latin-1-range literal
    # like "\x{00E9}" isn't reliably flagged on its own), then
    # `utf8::encode` it back off — leaving the same 5 UTF-8 BYTES behind,
    # exactly the input shape that used to make Perl's bare `length()`
    # return 5 instead of 4.
    my $cafe = "caf\x{00E9}";
    utf8::upgrade($cafe);
    ok(utf8::is_utf8($cafe), 'sanity: "café" is UTF8-flagged after utf8::upgrade');
    utf8::encode($cafe);
    ok(!utf8::is_utf8($cafe), 'sanity: utf8::encode dropped the UTF8 flag');
    is(length($cafe), 5, 'sanity: the unflagged scalar is 5 raw UTF-8 bytes');

t/evaluator.t  view on Meta::CPAN

    );

    # .filter(...).length > 0 — the doc/#2038 motivating composed shape.
    my $len_gt = {
        kind => 'binary', op => '>',
        left => nmem($filter_call, 'length'),
        right => { kind => 'literal', value => 0, literalType => 'number' },
    };
    ok(BarefootJS::Evaluator::evaluate($len_gt, {
        item => { tags => [ { active => JSON::PP::true }, { active => JSON::PP::false } ] },
    }), '.filter(...).length > 0 composes: at least one active');
    ok(!BarefootJS::Evaluator::evaluate($len_gt, {
        item => { tags => [ { active => JSON::PP::false }, { active => JSON::PP::false } ] },
    }), '.filter(...).length > 0 composes: none active is falsy');
};

# #2094: `.join(sep?)` — a sibling `array-method` alongside `.includes`.
subtest 'array-method join (#2094)' => sub {
    my $tags = nmem(nid('item'), 'tags');
    my $join_default = { kind => 'array-method', method => 'join', object => $tags, args => [] };
    is(BarefootJS::Evaluator::evaluate($join_default, { item => { tags => [ 'a', 'b' ] } }),
        'a,b', 'no separator defaults to a comma');

    my $join_custom = {
        kind => 'array-method', method => 'join', object => $tags,
        args => [ nstr('-') ],
    };
    is(BarefootJS::Evaluator::evaluate($join_custom, { item => { tags => [ 'a', 'b', 'c' ] } }),
        'a-b-c', 'custom separator');

    is(BarefootJS::Evaluator::evaluate($join_custom, { item => { tags => [] } }),
        '', 'empty array joins to the empty string');

    is(BarefootJS::Evaluator::evaluate($join_default, { item => { tags => [ 'a', undef, 'b' ] } }),
        'a,,b', 'a null/undef element joins as empty, not the string "null"');
};

subtest 'equality between an arithmetic result and a literal (#3445)' => sub {
    # The literal stays at the perl's NV precision while `0.1 + 0` is
    # rounded to a double; on a wide-NV perl they must still compare equal,
    # as they do in JS.
    my $lit = { kind => 'literal', value => 0.1, literalType => 'number' };
    my $zero = { kind => 'literal', value => 0, literalType => 'number' };
    my $sum = nbin('+', $lit, $zero);
    ok(BarefootJS::Evaluator::evaluate(nbin('===', $sum, $lit), {}), '(0.1 + 0) === 0.1');
    ok(!BarefootJS::Evaluator::evaluate(nbin('!==', $sum, nid('x')), { x => 0.1 }), '(0.1 + 0) !== x is false for x = 0.1');
    ok(BarefootJS::Evaluator::evaluate(nincludes(nid('xs'), $sum), { xs => [0.1] }), '[0.1].includes(0.1 + 0)');
};

subtest 'division by a signed zero (#3454)' => sub {
    # 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(
        nbin('/', $num->(1), nbin('%', $num->(-4), $num->(2))), {})),
        '-Infinity', 'evaluator: 1 / (-4 % 2)');
};

subtest 'number notation at the 1e-6 / 1e21 boundaries (#3380)' => sub {
    # JS prints decimal within [1e-6, 1e21) and an unpadded lower-case
    # exponent outside it; Perl's own `%.15g` pads the exponent and drops
    # digits past 15. Arithmetic goes through the evaluator, which computes
    # in doubles even on a perl whose NV is wider (#3445).
    my $calc = \&BarefootJS::Evaluator::_binary;
    my @cases = (
        [ $calc->('/', 1234567890, 1e15), '0.00000123456789' ],
        [ $calc->('/', 1234567890, 1e16), '1.23456789e-7' ],
        [ $calc->('*', 1234567890, 1e12), '1.23456789e+21' ],
        [ 1e-6,                           '0.000001' ],
        [ 1e-7,                           '1e-7' ],
        [ -1.5e-7,                        '-1.5e-7' ],
        [ 1e20,                           '100000000000000000000' ],
        [ 1e21,                           '1e+21' ],
        [ 12345678901234567890.0,         '12345678901234567000' ],
        [ $calc->('+', 0.1, 0.2),         '0.30000000000000004' ],
        [ 5e-324,                         '5e-324' ],
    );
    for my $c (@cases) {
        is(BarefootJS::Evaluator::_format_number($c->[0]), $c->[1], "formats $c->[1]");
    }
};

done_testing;



( run in 1.061 second using v1.01-cache-2.11-cpan-60884a8df76 )