forked from shlomif/Inline-Ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ruby.pm
529 lines (461 loc) · 13.5 KB
/
Ruby.pm
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package Inline::Ruby;
use strict;
use warnings;
use Carp;
require Inline;
require DynaLoader;
require Exporter;
use vars qw(@ISA $VERSION @EXPORT_OK);
$VERSION = '0.07';
@ISA = qw(Inline DynaLoader Exporter);
@EXPORT_OK = qw(rb_eval
rb_call_function
rb_iter
rb_call_class_method
rb_new_object
rb_call_instance_method
rb_bind_class
rb_bind_func
);
# Prevent Inline's import from complaining
sub import {
Inline::Ruby->export_to_level(1, @_);
}
sub dl_load_flags { 0x01 }
Inline::Ruby->bootstrap($VERSION);
use constant _GET_NAMESPACE => <<EOF;
Proc.new {
ns = { 'classes' => {}, 'modules' => {}, 'functions' => {} }
ObjectSpace.each_object(Class) do |x|
ns['classes'][x.name] = 1
end
ObjectSpace.each_object(Module) do |x|
ns['modules'][x.name] = 1
end
Object.private_instance_methods.each do |x|
ns['functions'][x] = 1
end
ns
}.call
EOF
#==============================================================================
# Register Ruby.pm as a valid Inline language
#==============================================================================
sub register {
return {
language => 'Ruby',
aliases => ['rb', 'ruby', 'RUBY'],
type => 'interpreted',
suffix => 'rbdat',
};
}
#==============================================================================
# Validate the Ruby config options
#==============================================================================
sub validate {
my $o = shift;
$o->{ILSM} ||= {};
$o->{ILSM}{FILTERS} ||= [];
$o->{ILSM}{AUTO_INCLUDE} ||= {};
$o->{ILSM}{built} ||= 0;
$o->{ILSM}{loaded} ||= 0;
$o->{ILSM}{bindto} = [qw(classes modules functions)];
$o->{ILSM}{ITER} ||= 'iter';
while (@_) {
my ($key, $value) = (shift, shift);
if ($key eq 'REGEX' or $key eq 'REGEXP') {
$o->{ILSM}{regexp} = qr/$value/;
}
elsif ($key eq 'BIND_TYPE' or $key eq 'BIND_TYPES') {
$o->_add_list($o->{ILSM}, 'bindto', $value, []);
}
elsif ($key eq 'ITER') {
$o->{ILSM}{$key} = $value;
}
elsif ($key eq 'FILTERS') {
next if $value eq '1' or $value eq '0'; # ignore ENABLE, DISABLE
$value = [$value] unless ref($value) eq 'ARRAY';
my %filters;
for my $val (@$value) {
if (ref($val) eq 'CODE') {
$o->_add_list($o->{ILSM}, $key, $val, []);
}
else {
eval { require Inline::Filters };
croak "'FILTERS' option requires Inline::Filters to be installed."
if $@;
%filters = Inline::Filters::get_filters($o->{API}{language})
unless keys %filters;
if (defined $filters{$val}) {
my $filter = Inline::Filters->new($val,
$filters{$val});
$o->_add_list($o->{ILSM}, $key, $filter, []);
}
else {
croak "Invalid filter $val specified.";
}
}
}
}
else {
croak "$key is not a valid config option for Ruby";
}
next;
}
}
sub _usage_validate {
return "Invalid value for config option $_[0]";
}
sub _add_list {
my $o = shift;
my ($ref, $key, $value, $default) = @_;
$value = [$value] unless ref $value;
croak _usage_validate($key) unless ref($value) eq 'ARRAY';
foreach my $val (@$value) {
if (defined $val) {
push @{$ref->{$key}}, $val;
}
else {
$ref->{$key} = $default;
}
}
}
=begin Removed
sub _add_string {
my $o = shift;
my ($ref, $key, $value, $default) = @_;
$value = [$value] unless ref $value;
croak _usage_validate($key) unless ref($value) eq 'ARRAY';
foreach my $val (@$value) {
if (defined $val) {
$ref->{$key} .= " $val";
}
else {
$ref->{$key} = $default;
}
}
}
sub _add_text {
my $o = shift;
my ($ref, $key, $value, $default) = @_;
$value = [$value] unless ref $value;
croak _usage_validate($key) unless ref($value) eq 'ARRAY';
for my $val (@$value) {
if (defined $val) {
chomp($val);
$ref->{$key} .= $val . "\n";
}
else {
$ref->{$key} = $default;
}
}
}
=end Removed
=cut
#==========================================================================
# Print a short information section if PRINT_INFO is enabled.
#==========================================================================
sub info {
my $o = shift;
my $info = "";
$o->build unless $o->{ILSM}{built};
my @functions = @{$o->{ILSM}{namespace}{functions}||[]};
$info .= "The following Ruby functions have been bound to Perl:\n"
if @functions;
for my $function (sort @functions) {
$info .= "\tdef $function()\n";
}
my %classes = %{$o->{ILSM}{namespace}{classes}||{}};
$info .= "The following Ruby classes have been bound to Perl:\n";
my $i = ' ' x 4;
for my $class (sort keys %classes) {
$info .= "${i}class $class\n";
$i .= $i;
for my $method (sort @{$classes{$class}{imethods}}) {
next unless $method =~ /^\w+$/;
$info .= "${i}def $method(...)\n";
}
for my $method (sort @{$classes{$class}{methods}}) {
next unless $method =~ /^\w+$/;
$info .= "${i}def $class.$method(...)\n";
}
}
return $info;
}
sub _eval_support_code {
rb_eval(<<'END');
def inline_ruby_class_grokker(*classes)
if classes == []
ObjectSpace.each_object(Class) do |x|
yield ['classes', x.name]
end
ObjectSpace.each_object(Module) do |x|
yield ['modules', x.name]
end
Kernel.methods.each do |x|
yield ['functions', x]
end
else
classes.each do |k|
n = {}
begin
n['methods'] = eval "#{k}.methods"
n['imethods'] = eval "#{k}.instance_methods"
rescue Exception
p "Exception: " + $!
end
yield [k, n]
end
end
end
END
}
#==========================================================================
# Run the code, study the main namespace, and cache the results.
#==========================================================================
sub build {
my $o = shift;
return if $o->{ILSM}{built};
# Filter the code
$o->{ILSM}{code} = $o->filter(@{$o->{ILSM}{FILTERS}});
# Get the namespace before & after evaluating the code:
my $pre = rb_eval(_GET_NAMESPACE);
rb_eval($o->{ILSM}{code});
my $post = rb_eval(_GET_NAMESPACE);
# Select those things which sprang into existence after running the code:
my @skip_clas = qw(PerlException PerlProc);
my @skip_func = qw();
delete @{ $post->{classes} }{@skip_clas, keys(%{$pre->{classes}})};
delete @{ $post->{functions} }{@skip_func, keys(%{$pre->{functions}})};
delete @{ $post->{modules} }{
keys(%{$pre->{modules}}), keys(%{$post->{classes}})
};
# Filter the results according to the {bindto} and {REGEXP} selections:
for my $type (qw(classes modules functions)) {
if ($o->{ILSM}{bindto}) {
delete $post->{$type}
unless grep { $_ eq $type } @{$o->{ILSM}{bindto}};
}
if ($o->{ILSM}{regexp}) {
for my $k (keys %{$post->{$type}}) {
delete $post->{$type}{$k} unless $k =~ $o->{ILSM}{regexp};
}
}
}
# Get more details about the classes and modules.
# FIXME! Is the quoting correct?
my $classes_arg = join ', ', map { quotemeta $_ } keys %{$post->{classes}};
my $c = rb_eval(<<EOF);
Proc.new {
ns = {}
classes = [$classes_arg]
classes.each do |k|
ns[k] = {}
begin
ns[k]['methods'] = eval "#{k}.methods"
ns[k]['imethods'] = eval "#{k}.instance_methods"
rescue Exception
p "Exception: " + \$!
end
end
ns
}.call
EOF
my $modules_arg = join ', ', map { quotemeta $_ } keys %{$post->{modules}};
my $m = rb_eval(<<EOF);
Proc.new {
ns = {}
classes = [$modules_arg]
classes.each do |k|
ns[k] = {}
begin
ns[k]['methods'] = eval "#{k}.methods"
ns[k]['imethods'] = eval "#{k}.instance_methods"
rescue Exception
p "Exception: " + \$!
end
end
ns
}.call
EOF
# And the namespace is:
my %namespace = (
classes => { %$c, %$m },
functions => [keys %{$post->{functions} || {}}],
);
if ((! @{$namespace{functions}})
and (! %{$namespace{classes}}))
{
warn "No functions or classes found!";
}
# Cache the results
require Inline::denter;
my $namespace = Inline::denter->new->indent(
*namespace => \%namespace,
*filtered => $o->{ILSM}{code},
*itername => $o->{ILSM}{ITER},
);
$o->mkpath("$o->{API}{install_lib}/auto/$o->{API}{modpname}");
{
open my $rbdat_fh, '>', $o->{API}{location}
or croak "Inline::Ruby couldn't write parse information!";
print {$rbdat_fh} $namespace;
close($rbdat_fh);
}
$o->{ILSM}{namespace} = \%namespace;
$o->{ILSM}{built}++;
}
sub _slurp
{
my $filename = shift;
open my $in, '<', $filename
or croak "Cannot open '$filename' for slurping - $!";
local $/;
my $contents = <$in>;
close($in);
return $contents;
}
#==============================================================================
# Load the code, run it, and bind everything to Perl
#==============================================================================
sub load {
my $o = shift;
return if $o->{ILSM}{loaded};
my $rbdat = _slurp($o->{API}{location});
require Inline::denter;
my %rbdat = Inline::denter->new->undent($rbdat);
$o->{ILSM}{namespace} = $rbdat{namespace};
$o->{ILSM}{code} = $rbdat{filtered};
$o->{ILSM}{ITER} = $rbdat{itername};
$o->{ILSM}{loaded}++;
# Run it
rb_eval($o->{ILSM}{code});
# Bind it all
for my $func (@{ $o->{ILSM}{namespace}{functions} || [] })
{
rb_bind_func("$o->{API}{pkg}::$func", $func);
}
for my $class (keys %{ $o->{ILSM}{namespace}{classes} || {} })
{
rb_bind_class("$o->{API}{pkg}::$class", $class, $o->{ILSM}{ITER},
%{$o->{ILSM}{namespace}{classes}{$class}});
}
# Bind the global function 'iter':
eval <<END;
sub $o->{API}{pkg}::$o->{ILSM}{ITER} {
unshift \@_, undef;
return &Inline::Ruby::rb_iter;
}
END
croak $@ if $@;
}
#==============================================================================
# Wrap a Ruby function with a Perl sub which calls it.
#==============================================================================
sub rb_bind_func {
my $perlfunc = shift; # The fully-qualified Perl sub name to create
my $function = shift; # The fully-qualified Ruby sub name to wrap
my $bind = <<END;
sub $perlfunc {
unshift \@_, "$function";
return &Inline::Ruby::rb_call_function;
}
END
eval $bind;
croak $@ if $@;
}
#==============================================================================
# Wrap a Ruby class in a Perl package. We wrap every method we know about,
# and we inherit from Inline::Ruby::Object so the Perverse Ruby Programmer
# can still create dynamic methods on-the-fly using its AUTOLOAD.
#==============================================================================
my %bound_pkgs;
sub rb_bind_class {
my $pkg = shift; # The perl class to use
my $class = shift; # The ruby class to wrap
my $iter = shift; # The name to use for 'iter'
my %methods = @_;
$pkg =~ s/\Amain:://;
if (exists($bound_pkgs{$pkg}))
{
return;
}
$bound_pkgs{$pkg} = 1;
my $bind = <<END;
package ${pkg};
\@${pkg}::ISA = qw(Inline::Ruby::Object);
sub new { # ${class}::new
splice \@_, 1, 0, "$class";
return &Inline::Ruby::rb_new_object;
}
END
$bind .= <<END if $iter;
sub $iter {
return &Inline::Ruby::rb_iter;
}
END
my %bound_methods;
for my $method (@{$methods{methods}}) {
next unless $method =~ /^\w+$/;
next if $method eq 'new'; # handled specially
next if $bound_methods{$method}++;
$bind .= <<END;
sub $method { # ${class}::${method}
splice \@_, 1, 0, "$method";
return &Inline::Ruby::rb_call_class_method;
}
END
}
for my $method (@{$methods{imethods}}) {
next unless $method =~ /^\w+$/;
next if $bound_methods{$method}++;
$bind .= <<END;
sub $method { # ${class}::${method}
splice \@_, 1, 0, "$method";
return &Inline::Ruby::rb_call_instance_method;
}
END
}
eval $bind;
croak $@ if $@;
}
#==============================================================================
# Create a new instance of a Ruby object.
#==============================================================================
sub rb_new_object {
return &Inline::Ruby::Object::new;
}
#==============================================================================
# We provide Inline::Ruby::Object as a base class for Ruby objects. It
# knows how to create, destroy, and call methods on objects.
#==============================================================================
package Inline::Ruby::Object;
sub new {
my $pkg = shift;
splice @_, 1, 0, 'new';
return bless &Inline::Ruby::rb_call_class_method, ref($pkg) || $pkg;
}
sub AUTOLOAD {
no strict;
$AUTOLOAD =~ s|^.*::||;
splice @_, 1, 0, $AUTOLOAD;
return &Inline::Ruby::rb_call_instance_method;
}
#==============================================================================
# We provide Inline::Ruby::Exception as a class for Ruby exceptions. Creating
# an instance of it throws a Perl exception. You can call Ruby methods on the
# exception object to get more information about what went wrong.
#
# Don't create your own Inline::Ruby::Exception objects. This is intended to
# be created from XS.
#==============================================================================
package Inline::Ruby::Exception;
use overload '""' => \&to_str;
sub new {
my ($cls, $obj) = @_;
die bless $obj, ref($cls) || $cls;
}
sub to_str {
$_[0]->inspect . "\n";
}
1;