summaryrefslogtreecommitdiff
path: root/jpl/JPL/AutoLoader.pm
blob: 94d98563fd3ab18f579c9f892871422df182987b (plain)
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
package JPL::AutoLoader;

use strict;

use vars qw(@ISA @EXPORT $AUTOLOAD);

use Exporter;
@ISA = "Exporter";
@EXPORT = ("AUTOLOAD", "getmeth");

my %callmethod = (
    V => 'Void',
    Z => 'Boolean',
    B => 'Byte',
    C => 'Char',
    S => 'Short',
    I => 'Int',
    J => 'Long',
    F => 'Float',
    D => 'Double',
);

# A lookup table to convert the data types that Java
# developers are used to seeing into the JNI-mangled
# versions.
#
# bjepson 13 August 1997
#
my %type_table = (
    'void'    => 'V',
    'boolean' => 'Z',
    'byte'    => 'B',
    'char'    => 'C',
    'short'   => 'S',
    'int'     => 'I',
    'long'    => 'J',
    'float'   => 'F',
    'double'  => 'D'
);

# A cache for method ids.
#
# bjepson 13 August 1997
#
my %MID_CACHE;

# A cache for methods.
#
# bjepson 13 August 1997
#
my %METHOD_CACHE;

use JNI;

# XXX We're assuming for the moment that method ids are persistent...

sub AUTOLOAD {

    print "AUTOLOAD $AUTOLOAD(@_)\n" if $JPL::DEBUG;
    my ($classname, $methodsig) = $AUTOLOAD =~ /^(.*)::(.*)/;
    print "class = $classname, method = $methodsig\n" if $JPL::DEBUG;

    if ($methodsig eq "DESTROY") {
        print "sub $AUTOLOAD {}\n" if $JPL::DEBUG;
        eval "sub $AUTOLOAD {}";
        return;
    }

    (my $jclassname = $classname) =~ s/^JPL:://;
    $jclassname =~ s{::}{/}g;
    my $class = JNI::FindClass($jclassname)
        or die "Can't find Java class $jclassname\n";

    # This method lookup allows the user to pass in
    # references to two array that contain the input and
    # output data types of the method.
    #
    # bjepson 13 August 1997
    #
    my ($methodname, $sig, $retsig, $slow_way);
    if (ref $_[1] eq 'ARRAY' && ref $_[2] eq 'ARRAY') {

	$slow_way = 1;

        # First we strip out the input and output args.
	#
        my ($in,$out) = splice(@_, 1, 2);

        # let's mangle up the input argument types.
        #
        my @in  = jni_mangle($in);

        # if they didn't hand us any output values types, make
        # them void by default.
        #
        unless (@{ $out }) {
            $out = ['void'];
        }

        # mangle the output types
        #
        my @out = jni_mangle($out);

        $methodname = $methodsig;
        $retsig     = join("", @out);
        $sig        = "(" . join("", @in) . ")" . $retsig;

    } else {

        ($methodname, $sig) = split /__/, $methodsig, 2;
        $sig ||= "__V";                # default is void return

        # Now demangle the signature.

        $sig =~ s/_3/[/g;
        $sig =~ s/_2/;/g;
        my $tmp;
        $sig =~ s{
            (s|L[^;]*;)
        }{
	    $1 eq 's'
		? "Ljava/lang/String;"
		: (($tmp = $1) =~ tr[_][/], $tmp)
        }egx;
        if ($sig =~ s/(.*)__(.*)/($1)$2/) {
            $retsig = $2;
        }
        else {                        # void return is assumed
            $sig = "($sig)V";
            $retsig = "V";
        }
        $sig =~ s/_1/_/g;
    }
    print "sig = $sig\n" if $JPL::DEBUG;

    # Now look up the method's ID somehow or other.
    #
    $methodname = "<init>" if $methodname eq 'new';
    my $mid;

    # Added a method id cache to compensate for avoiding
    # Perl's method cache...
    #
    if ($MID_CACHE{qq[$classname:$methodname:$sig]}) {

        $mid = $MID_CACHE{qq[$classname:$methodname:$sig]};
        print "got method " . ($mid + 0) . " from cache.\n" if $JPL::DEBUG;

    } elsif (ref $_[0] or $methodname eq '<init>') {

        # Look up an instance method or a constructor
        #
        $mid = JNI::GetMethodID($class, $methodname, $sig);

    } else {

        # Look up a static method
        #
        $mid = JNI::GetStaticMethodID($class, $methodname, $sig);

    }

    # Add this method to the cache.
    #
    # bjepson 13 August 1997
    #
    $MID_CACHE{qq[$classname:$methodname:$sig]} = $mid if $slow_way;

    if ($mid == 0) {

        JNI::ExceptionClear();
        # Could do some guessing here on return type...
        die "Can't get method id for $AUTOLOAD($sig)\n";

    }

    print "mid = ", $mid + 0, ", $mid\n" if $JPL::DEBUG;
    my $rettype = $callmethod{$retsig} || "Object";
    print "*** rettype = $rettype\n" if $JPL::DEBUG;

    my $blesspack;
    no strict 'refs';
    if ($rettype eq "Object") {
        $blesspack = $retsig;
        $blesspack =~ s/^L//;
        $blesspack =~ s/;$//;
        $blesspack =~ s#/#::#g;
        print "*** Some sort of wizardry...\n" if $JPL::DEBUG;
        print %{$blesspack . "::"}, "\n" if $JPL::DEBUG;
        print defined %{$blesspack . "::"}, "\n" if $JPL::DEBUG;
        if (not defined %{$blesspack . "::"}) {
            #if ($blesspack eq "java::lang::String") {
            if ($blesspack =~ /java::/) {
                eval <<"END" . <<'ENDQ';
package $blesspack;
END
use JPL::AutoLoader;
use overload
        '""' => sub { JNI::GetStringUTFChars($_[0]) },
        '0+' => sub { 0 + "$_[0]" },
        fallback => 1;
ENDQ
            }
            else {
                eval <<"END";
package $blesspack;
use JPL::AutoLoader;
END
            }
        }
    }

    # Finally, call the method.  Er, somehow...
    #
    my $METHOD;

    my $real_mid = $mid + 0; # weird overloading that I
                             # don't understand ?!
    if (ref ${$METHOD_CACHE{qq[$real_mid]}} eq 'CODE') {

        $METHOD = ${$METHOD_CACHE{qq[$real_mid]}};
        print qq[Pulled $classname, $methodname, $sig from cache.\n] if $JPL::DEBUG;

    } elsif ($methodname eq "<init>") {
        $METHOD = sub {
            my $self = shift;
	    my $class = JNI::FindClass($jclassname);
            bless $class->JNI::NewObjectA($mid, \@_), $classname;
        };
    }
    elsif (ref $_[0]) {
        if ($blesspack) {
            $METHOD = sub {
                my $self = shift;
                if (ref $self eq $classname) {
                    my $callmethod = "JNI::Call${rettype}MethodA";
                    bless $self->$callmethod($mid, \@_), $blesspack;
                }
                else {
                    my $callmethod = "JNI::CallNonvirtual${rettype}MethodA";
                    bless $self->$callmethod($class, $mid, \@_), $blesspack;
                }
            };
        }
        else {
            $METHOD = sub {
                my $self = shift;
                if (ref $self eq $classname) {
                    my $callmethod = "JNI::Call${rettype}MethodA";
                    $self->$callmethod($mid, \@_);
                }
                else {
                    my $callmethod = "JNI::CallNonvirtual${rettype}MethodA";
                    $self->$callmethod($class, $mid, \@_);
                }
            };
        }
    }
    else {
        my $callmethod = "JNI::CallStatic${rettype}MethodA";
        if ($blesspack) {
            $METHOD = sub {
                my $self = shift;
                bless $class->$callmethod($mid, \@_), $blesspack;
            };
        }
        else {
            $METHOD = sub {
                my $self = shift;
                $class->$callmethod($mid, \@_);
            };
        }
    }
    if ($slow_way) {
	$METHOD_CACHE{qq[$real_mid]} = \$METHOD;
	&$METHOD;
    }
    else {
	*$AUTOLOAD = $METHOD;
	goto &$AUTOLOAD;
    }
}

sub jni_mangle {

    my $arr = shift;
    my @ret;

    foreach my $arg (@{ $arr }) {

        my $ret;

        # Count the dangling []s.
        #
	$ret = '[' x $arg =~ s/\[\]//g;

        # Is it a primitive type?
        #
        if ($type_table{$arg}) {
            $ret .= $type_table{$arg};
        } else {
            # some sort of class
            #
            $arg =~ s#\.#/#g;
            $ret .= "L$arg;";
        }
        push @ret, $ret;

    }

    return @ret;

}

sub getmeth {
    my ($meth, $in, $out) = @_;
    my @in  = jni_mangle($in);

    # if they didn't hand us any output values types, make
    # them void by default.
    #
    unless ($out and @$out) {
	$out = ['void'];
    }

    # mangle the output types
    #
    my @out = jni_mangle($out);

    my $sig        = join("", '#', @in, '#', @out);
    $sig =~ s/_/_1/g;
    my $tmp;
    $sig =~ s{
	(L[^;]*;)
    }{
	($tmp = $1) =~ tr[/][_], $tmp
    }egx;
    $sig =~ s{Ljava/lang/String;}{s}g;
    $sig =~ s/;/_2/g;
    $sig =~ s/\[/_3/g;
    $sig =~ s/#/__/g;
    $meth . $sig;
}

{
    package java::lang::String;
    use overload
	'""' => sub { JNI::GetStringUTFChars($_[0]) },
	'0+' => sub { 0 + "$_[0]" },
	fallback => 1;
}
1;