NAME

Language::Expr::Compiler::js - Compile Language::Expr expression to JavaScript

VERSION

This document describes version 0.29 of Language::Expr::Compiler::js (from Perl distribution Language-Expr), released on 2016-07-03.

SYNOPSIS

use Language::Expr::Compiler::js;
my $jsc = Language::Expr::Compiler::js->new;
print $jsc->compile('map({$_**2}, [1, 2, 3])'); # prints: [1, 2, 3].map(function(_){ Math.pow(_, 2) })

# map Expr function to JS function/method/property
$jsc->func_mapping->{ceil} = 'Math.ceil';
$jsc->func_mapping->{uc} = '.toUpperCase';
$jsc->func_mapping->{length} = ':length';
print $jsc->compile(q{uc("party like it's ") . ceil(1998.9)}); # prints: "party like it's ".toUpperCase() + Math.ceil(1998.9)

DESCRIPTION

Compiles Language::Expr expression to JavaScript code. Some notes:

  • JavaScript version

    This compiler emits JavaScript 1.8.1 code (it uses several Array methods like map() and filter() [supported since JavaScript 1.6], 'let' lexical variables [supported since JavaScript 1.7] and native JSON [supported since JavaScript 1.8.1]).

    To test emitted JavaScript code, we use Node.js.

  • JavaScript-ness

    The emitted JS code will follow JavaScript's weak typing and coercion rules, e.g. Expr '1+"2"' will simply be translated to JavaScript '1+"2"' and will result in "12".

  • Variables by default simply use JavaScript variables.

    E.g. $a becomes a, and so on. Be careful not to make variables which are invalid in JavaScript, e.g. $.. or ${foo/bar}.

    You can customize this behaviour by subclassing rule_var() or by providing a hook_var() (see documentation in Language::Expr::Compiler::Base).

  • Functions by default simply use Javascript functions.

    Except those mentioned in func_mapping (e.g. rand() becomes Math.rand() if func_mapping->{rand} is 'Math.rand'). You can also map to JavaScript method (using '.meth' syntax) and property (using ':prop' syntax).

    You can customize this behaviour by subclassing rule_func() or by providing a hook_func() (see documentation in Language::Expr::Compiler::Base).

METHODS

compile($expr) => $js_code

Convert Language::Expr expression into JavaScript code. Dies if there is syntax error in expression.

HOMEPAGE

Please visit the project's homepage at https://metacpan.org/release/Language-Expr.

SOURCE

Source repository is at https://github.com/sharyanto/perl-Language-Expr.

BUGS

Please report any bugs or feature requests on the bugtracker website https://rt.cpan.org/Public/Dist/Display.html?Name=Language-Expr

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.

AUTHOR

perlancar <perlancar@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.