1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
|
package JavaScript::QuickJS;
use strict;
use warnings;
=encoding utf-8
=head1 NAME
JavaScript::QuickJS - Run JavaScript via L<QuickJS|https://bellard.org/quickjs> in Perl
=head1 SYNOPSIS
Quick and dirty …
my $val = JavaScript::QuickJS->new()->eval( q<
let foo = "bar";
[ "The", "last", "value", "is", "returned." ];
> );
… or load ES6 modules:
my $js = JavaScript::QuickJS->new()->helpers();
$js->eval_module( q/
import * as coolStuff from 'cool/stuff';
for (const [key, value] of Object.entries(coolStuff)) {
console.log(key, value);
}
/ );
=head1 DESCRIPTION
This library embeds Fabrice Bellard’s L<QuickJS|https://bellard.org/quickjs>
engine into a Perl XS module. You can thus run JavaScript
(L<ES2020|https://tc39.github.io/ecma262/> specification) directly in your
Perl programs.
This distribution includes all needed C code; unlike with most XS modules
that interface with C libraries, you don’t need QuickJS pre-installed on
your system.
=cut
# ----------------------------------------------------------------------
use XSLoader;
our $VERSION = '0.21';
XSLoader::load( __PACKAGE__, $VERSION );
# ----------------------------------------------------------------------
=head1 METHODS
=head2 $obj = I<CLASS>->new( %CONFIG_OPTS )
Instantiates I<CLASS>. %CONFIG_OPTS have the same effect as in
C<configure()> below.
=cut
sub new {
my ($class, %opts) = @_;
my $self = $class->_new();
return %opts ? $self->configure(%opts) : $self;
}
=head2 $obj = I<OBJ>->configure( %OPTS )
Tunes the QuickJS interpreter. Returns I<OBJ>.
%OPTS are any of:
=over
=item * C<max_stack_size>
=item * C<memory_limit>
=item * C<gc_threshold>
=back
For more information on these, see QuickJS itself.
=cut
sub configure {
my ($self, %opts) = @_;
my ($stack, $memlimit, $gc_threshold) = delete @opts{'max_stack_size', 'memory_limit', 'gc_threshold'};
if (my @extra = sort keys %opts) {
Carp::croak("Unknown: @extra");
}
return $self->_configure($stack, $memlimit, $gc_threshold);
}
#----------------------------------------------------------------------
=head2 $obj = I<OBJ>->set_globals( NAME1 => VALUE1, .. )
Sets 1 or more globals in I<OBJ>. See below for details on type conversions
from Perl to JavaScript.
Returns I<OBJ>.
=head2 $obj = I<OBJ>->helpers()
Defines QuickJS’s “helpers”, e.g., C<console.log>.
Returns I<OBJ>.
=head2 $obj = I<OBJ>->std()
Enables QuickJS’s C<std> module and creates a global of the same name
that’s usable from both script and module modes.
This resembles C<qjs>’s C<--std> flag except that it I<only> enables
C<std>, not C<os>.
Returns I<OBJ>.
=head2 $obj = I<OBJ>->os()
Like C<std()> but enables QuickJS’s C<os> module instead of C<std>.
=head2 $VALUE = I<OBJ>->eval( $JS_CODE )
Like running C<qjs -e '...'>. Returns $JS_CODE’s last value;
see below for details on type conversions from JavaScript to Perl.
Untrapped exceptions in JavaScript will be rethrown as Perl exceptions.
$JS_CODE is a I<character> string.
=head2 $promise = I<OBJ>->eval_module( $JS_CODE )
Runs $JS_CODE as a module, which enables ES6 module syntax.
Note that no values can be returned directly in this mode of execution.
Returns a promise that resolves once the module is loaded.
=head2 $obj = I<OBJ>->await()
Blocks until all of I<OBJ>’s pending work (if any) is complete.
For example, if you C<eval()> some code that creates a promise, call
this to wait for that promise to complete.
Returns I<OBJ>.
=head2 $obj = I<OBJ>->set_module_base( $PATH )
Sets a base path (a byte string) for ES6 module imports.
Returns I<OBJ>.
=head2 $obj = I<OBJ>->unset_module_base()
Restores QuickJS’s default directory for ES6 module imports
(as of this writing, it’s the process’s current directory).
Returns I<OBJ>.
=cut
# ----------------------------------------------------------------------
=head1 TYPE CONVERSION: JAVASCRIPT → PERL
This module converts returned values from JavaScript thus:
=over
=item * JS string primitives become I<character> strings in Perl.
=item * JS number & boolean primitives become corresponding Perl values.
=item * JS null & undefined become Perl undef.
=item * JS objects …
=over
=item * Arrays become Perl array references.
=item * “Plain” objects become Perl hash references.
=item * Function, RegExp, and Date objects become Perl
L<JavaScript::QuickJS::Function>, L<JavaScript::QuickJS::RegExp>,
and L<JavaScript::QuickJS::Date> objects, respectively.
=item * Behaviour is B<UNDEFINED> for other object types.
=back
=back
=head1 TYPE CONVERSION: PERL → JAVASCRIPT
Generally speaking, it’s the inverse of JS → Perl:
=over
=item * Perl strings, numbers, & booleans become corresponding JavaScript
primitives.
B<IMPORTANT:> Perl versions before 5.36 don’t reliably distinguish “numeric
strings” from “numbers”. If your perl predates 5.36, typecast accordingly
to prevent your Perl “number” from becoming a JavaScript string. (Even in
5.36 and later it’s still a good idea.)
=item * Perl undef becomes JS null.
=item * Unblessed array & hash references become JavaScript arrays and
“plain” objects.
=item * L<Types::Serialiser> booleans become JavaScript booleans.
=item * Perl code references become JavaScript functions.
=item * Perl L<JavaScript::QuickJS::Function>, L<JavaScript::QuickJS::RegExp>,
and L<JavaScript::QuickJS::Date> objects become their original
JavaScript objects.
=item * Anything else triggers an exception.
=back
=head1 MEMORY HANDLING NOTES
If any instance of a class of this distribution is DESTROY()ed at Perl’s
global destruction, we assume that this is a memory leak, and a warning is
thrown. To prevent this, avoid circular references, and clean up all global
instances.
Callbacks make that tricky. When you give a JavaScript function to Perl,
that Perl object holds a reference to the QuickJS context. Only once that
object is C<DESTROY()>ed do we release that QuickJS context reference.
Consider the following:
my $return;
$js->set_globals( __return => sub { $return = shift; () } );
$js->eval('__return( a => a )');
This sets $return to be a L<JavaScript::QuickJS::Function> instance. That
object holds a reference to $js. $js also stores C<__return()>,
which is a Perl code reference that closes around $return. Thus, we have
a reference cycle: $return refers to $js, and $js refers to $return. Those
two values will thus leak, and you’ll see a warning about it at Perl’s
global destruction time.
To break the reference cycle, just do:
undef $return;
… once you’re done with that variable.
You I<might> have thought you could instead do:
$js->set_globals( __return => undef )
… but that doesn’t work because $js holds a reference to all Perl code
references it B<ever> receives. This is because QuickJS, unlike Perl,
doesn’t expose object destructors (C<DESTROY()> in Perl), so there’s no
good way to release that reference to the code reference.
=head1 CHARACTER ENCODING NOTES
QuickJS (like all JS engines) assumes its strings are text. Since Perl
can’t distinguish text from bytes, though, it’s possible to convert
Perl byte strings to JavaScript strings. It often yields a reasonable
result, but not always.
One place where this falls over, though, is ES6 modules. QuickJS, when
it loads an ES6 module, decodes that module’s string literals to characters.
Thus, if you pass in byte strings from Perl, QuickJS will treat your
Perl byte strings’ code points as character code points, and when you
combine those code points with those from your ES6 module you may
get mangled output.
Another place that may create trouble is if your argument to C<eval()>
or C<eval_module()> (above) contains JSON. Perl’s popular JSON encoders
output byte strings by default, but as noted above, C<eval()> and
C<eval_module()> need I<character> strings. So either configure your
JSON encoder to output characters, or decode JSON bytes to characters
before calling C<eval()>/C<eval_module()>.
For best results, I<always> interact with QuickJS via I<character>
strings, and double-check that you’re doing it that way consistently.
=head1 NUMERIC PRECISION
Note the following if you expect to deal with “large” numbers:
=over
=item * JavaScript’s numeric-precision limits apply. (cf.
L<Number.MAX_SAFE_INTEGER|https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER>.)
=item * Perl’s stringification of numbers may be I<less> precise than
JavaScript’s storage of those numbers, or even than Perl’s own storage.
For example, in Perl 5.34 C<print 1000000000000001.0> prints C<1e+15>.
To counteract this loss of precision, add 0 to Perl’s numeric scalars
(e.g., C<print 0 + 1000000000000001.0>); this will encourage Perl to store
numbers as integers when possible, which fixes this precision problem.
=item * Long-double and quad-math perls may lose precision when converting
numbers to/from JavaScript. To see if this affects your perl—which, if
you’re unsure, it probably doesn’t—run C<perl -V>, and see if that perl’s
compile-time options mention long doubles or quad math.
=back
=head1 OS SUPPORT
QuickJS supports Linux, macOS, and Windows natively, so these work without
issue.
FreeBSD, OpenBSD, & Cygwin work after a few patches that we apply when
building this library. (Hopefully these will eventually merge into QuickJS.)
=head1 LIBATOMIC
QuickJS uses C11 atomics. Most platforms implement that functionality in
hardware, but others (e.g., arm32) don’t. To fill that void, we need to link
to libatomic.
This library’s build logic detects whether libatomic is necessary and will
only link to it if needed. If, for some reason, you need manual control over
that linking, set C<JS_QUICKJS_LINK_LIBATOMIC> in the environment to 1 or a
falsy value.
If you don’t know what any of that means, you can probably ignore it.
=head1 SEE ALSO
Other JavaScript modules on CPAN include:
=over
=item * L<JavaScript::Duktape::XS> and L<JavaScript::Duktape> make the
L<Duktape|https://duktape.org> library available to Perl. They’re similar to
this library, but Duktape itself (as of this writing) lacks support for
several JavaScript constructs that QuickJS supports. (It’s also slower.)
=item * L<JavaScript::V8> and L<JavaScript::V8::XS> expose Google’s
L<V8|https://v8.dev> library to Perl. Neither seems to support current
V8 versions.
=item * L<JE> is a pure-Perl (!) JavaScript engine.
=item * L<JavaScript> and L<JavaScript::Lite> expose Mozilla’s
L<SpiderMonkey|https://spidermonkey.dev/> engine to Perl.
=back
=head1 LICENSE & COPYRIGHT
This library is copyright 2023 Gasper Software Consulting.
This library is licensed under the same terms as Perl itself.
See L<perlartistic>.
QuickJS is copyright Fabrice Bellard and Charlie Gordon. It is released
under the L<MIT license|https://opensource.org/licenses/MIT>.
=cut
#----------------------------------------------------------------------
package JavaScript::QuickJS::JSObject;
package JavaScript::QuickJS::RegExp;
our @ISA;
BEGIN { @ISA = 'JavaScript::QuickJS::JSObject' };
package JavaScript::QuickJS::Function;
our @ISA;
BEGIN { @ISA = 'JavaScript::QuickJS::JSObject' };
1;
|