Skip to content

Commit d7cf85b

Browse files
committed
Add a REPL program (with tab completion) as an example
1 parent 465af2e commit d7cf85b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

examples/v8repl

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/perl
2+
use strict;
3+
use Data::Dump qw(pp);
4+
use JavaScript::V8;
5+
use Term::ANSIColor qw(colored);
6+
use Term::ReadLine; # Much better if Term::ReadLine::Gnu is installed
7+
8+
my $js = JavaScript::V8::Context->new;
9+
$js->name_global("global");
10+
$js->bind(print => sub { print "@_\n" });
11+
12+
my $rl = Term::ReadLine->new($0);
13+
14+
if($rl->isa("Term::ReadLine::Gnu")) {
15+
my $attribs = $rl->Attribs;
16+
my @list;
17+
$attribs->{completion_entry_function} = sub {
18+
my($complete_prefix, $count) = @_;
19+
20+
if($count == 0) {
21+
(my $object = "global.$complete_prefix") =~ s/\.([^.]*)$//;
22+
my $object_prefix = $1;
23+
my $prefix = "";
24+
if($complete_prefix =~ s/\.([^.]+)$/./) {
25+
$prefix = $complete_prefix;
26+
}
27+
@list = sort map $prefix . $_,
28+
grep /^\Q$object_prefix\E/, keys %{$js->eval($object)};
29+
}
30+
31+
$list[$count];
32+
};
33+
}
34+
35+
while (1) {
36+
my $line = $rl->readline('> ');
37+
exit unless defined $line;
38+
my $ret = $js->eval($line);
39+
if($@) {
40+
print STDERR colored(['red'], $@);
41+
} else {
42+
pp $ret;
43+
}
44+
}

0 commit comments

Comments
 (0)