Perlito5/Java/Emitter.pm untested

filter: Statementstmt 0.0% 0 / 1038 Branchbran 0.0% 0 / 534 Conditioncond 0.0% 0 / 428 MC/DCmcdc 0.0% 0 / 261 Subroutinesub 0.0% 0 / 72 Podpod 0.0% 0 / 70 totaltotal 0.0% 0 / 2403 CC 268 SCAR 56.5
CC
268
Cov
0%
emit_java
992.0
emit_java_global
650.0
emit_java
506.0
CRAP 284.1
1 use v5;
2 use strict;
3  
4 package Perlito5::Java::LexicalBlock;
5 {
6 sub new { my $class = shift; bless {@_}, $class }
7 sub block { $_[0]->{block} }
8 # top_level - true if this is the main block in a subroutine;
9  
10 sub has_decl {
11 my $self = $_[0];
12 my $type = $_[1];
13 for my $decl ( @{$self->{block}} ) {
14 return 1
15 if grep { $_->{decl} eq $type } $decl->emit_java_get_decl();
16 }
17 return 0;
18 }
19  
20 sub emit_return {
21 my ($has_local, $local_label, $value) = @_;
22 $has_local
23 ? 'return PerlOp.cleanup_local(' . $local_label . ', ' . $value . ')'
24 : 'return ' . $value;
25 }
26  
27 sub looks_like_dead_code {
28 my ($decl) = @_;
29  
30 if ( (ref($decl) eq 'Perlito5::AST::Apply') && $decl->{code} eq 'circumfix:<( )>' ) {
31 # dead code ()
32 return 1 if !@{$decl->{arguments}};
33 # dead code (my $x, undef)
34 return 1 if !grep { !looks_like_dead_code($_) } @{$decl->{arguments}};
35 }
36 if ( (ref($decl) eq 'Perlito5::AST::Apply') && ($decl->{code} eq 'my' || $decl->{code} eq 'our') ) {
37 # dead code my ($x)
38 return 1;
39 }
40 if ( (ref($decl) eq 'Perlito5::AST::Decl') && ($decl->{decl} eq 'my' || $decl->{decl} eq 'our') ) {
41 # dead code my $x
42 return 1;
43 }
44 if ( ( (ref($decl) eq 'Perlito5::AST::Int') )
45 || ( (ref($decl) eq 'Perlito5::AST::Num') )
46 || ( (ref($decl) eq 'Perlito5::AST::Buf') )
47 || ( (ref($decl) eq 'Perlito5::AST::Var') && $decl->{sigil} ne '&' )
48 || ( (ref($decl) eq 'Perlito5::AST::Apply') && $decl->{code} eq 'undef' && !@{$decl->{arguments}} )
49 )
50 {
51 # dead code 123
52 # dead code undef
53 return 1;
54 }
55 return 0;
56 }
57  
58 sub emit_body_statement {
59 my ($decl, $level, $wantarray ) = @_;
60 my @str;
61  
62 if ( ref($decl) eq 'Perlito5::AST::Apply' && $decl->{code} eq 'package' ) {
63 $Perlito5::PKG_NAME = $decl->{namespace};
64 }
65  
66 # if ( ref($decl) eq 'Perlito5::AST::Apply' && $decl->{code} eq 'infix:<=>' ) {
67 # # my $x = ... (untyped scalar)
68 # my $arg0 = $decl->{arguments}[0];
69 # if ( ref($arg0) eq 'Perlito5::AST::Decl' && $arg0->{decl} eq 'my' && $arg0->{type} eq '' ) {
70 # my $var = $arg0->{var};
71 # if (!$var->is_begin_scratchpad()) {
72 # if ($var->{sigil} eq '$') {
73 # my $arg = $decl->{arguments}[1];
74 # return "PlLvalue " . $var->emit_java($level) . " = new PlLvalue(" . $arg->emit_java($level, "scalar") . ");";
75 # }
76 # }
77 # }
78 # }
79  
80 my @var_decl = $decl->emit_java_get_decl();
81 for my $arg (@var_decl) {
82 push @str, $arg->emit_java_init($level, $wantarray);
83 }
84  
85 if ( looks_like_dead_code( $decl ) ) {
86 # this looks like dead code
87 }
88 elsif (
89 (ref($decl) eq 'Perlito5::AST::Apply')
90 && ( $decl->{code} eq "list:<,>"
91 || $decl->{code} eq "infix:<=>>"
92 || $decl->{code} eq "circumfix:<( )>"
93 )
94 )
95 {
96 # workaround for "Error: not a statement"
97 # These expressions cannot be used in statement position in Java:
98 # x, y
99 # x => y
100 if ($decl->{code} eq "infix:<=>>") {
101 $decl->{arguments}[0] = Perlito5::AST::Lookup->autoquote($decl->{arguments}[0]);
102 }
103 push @str, emit_body_statement($_)
104 for @{$decl->{arguments}};
105 }
106 elsif ( (ref($decl) eq 'Perlito5::AST::CompUnit')
107 || (ref($decl) eq 'Perlito5::AST::For' )
108 || (ref($decl) eq 'Perlito5::AST::While' )
109 || (ref($decl) eq 'Perlito5::AST::If' )
110 || (ref($decl) eq 'Perlito5::AST::Block' )
111 )
112 {
113 push @str, $decl->emit_java( $level, 'statement' );
114 }
115 else {
116 push @str, $decl->emit_java( $level, 'statement' ) . ';';
117 }
118 return @str;
119 }
120  
121 sub emit_last_statement {
122 my ($self, $last_statement, $level, $wantarray, $has_local, $local_label ) = @_;
123 my @str;
124  
125 my @var_decl = $last_statement->emit_java_get_decl();
126 for my $arg (@var_decl) {
127 push @str, $arg->emit_java_init($level, $wantarray);
128 }
129  
130 my @stmt = Perlito5::Macro::insert_return($last_statement);
131 $last_statement = pop @stmt;
132  
133 for (@stmt) {
134 push @str, $_->emit_java($level, 'statement') . ';';
135 }
136  
137 if ( (ref($last_statement) eq 'Perlito5::AST::Apply' ) && $last_statement->{code} eq 'return' ) {
138 if ( $self->{top_level} || $last_statement->{_return_from_block} || $Perlito5::JAVA_CAN_RETURN ) {
139 if (!@{$last_statement->{arguments}}) {
140 push @str, emit_return($has_local, $local_label, 'PerlOp.context(want)') . ';';
141 }
142 else {
143 push @str, emit_return($has_local, $local_label,
144 Perlito5::Java::to_runtime_context([$last_statement->{arguments}[0]], $level+1, 'runtime')
145 ) . ';';
146 }
147 }
148 else {
149 if (!@{$last_statement->{arguments}}) {
150 $Perlito5::THROW_RETURN = 1;
151 push @str, 'throw new PlReturnException(PerlOp.context(return_context));';
152 }
153 else {
154 $Perlito5::THROW_RETURN = 1;
155 push @str, 'throw new PlReturnException('
156 . Perlito5::Java::to_runtime_context([$last_statement->{arguments}[0]], $level+1, 'return')
157 . ');';
158 }
159 }
160 }
161 else {
162 my $s = $last_statement->emit_java($level, 'runtime');
163 $s .= ';'
164 unless (ref($last_statement) eq 'Perlito5::AST::If')
165 || (ref($last_statement) eq 'Perlito5::AST::While')
166 || (ref($last_statement) eq 'Perlito5::AST::Block');
167 push @str, $s;
168 }
169 return @str;
170 }
171  
172 sub emit_java {
173 my ($self, $level, $wantarray) = @_;
174 local $Perlito5::PKG_NAME = $Perlito5::PKG_NAME;
175 my $block_label = Perlito5::Java::get_java_loop_label( $self->{block_label} );
176 $Perlito5::THROW = 1 if $block_label;
177  
178 my @block;
179 my $block_last = $#{$self->{block}};
180 STMT:
181 for my $i ( 0 .. $block_last ) {
182 my $stmt = $self->{block}[$i];
183 if (defined($stmt)) {
184 push @block, $stmt;
185  
186 # TODO - test for "if" with "return" in both sides
187  
188 if ( (ref($stmt) eq 'Perlito5::AST::Apply' ) && $stmt->{code} eq 'return' ) {
189 last STMT;
190 }
191 }
192 }
193 if ($self->{top_level} && !@block) {
194 push @block, Perlito5::AST::Apply->new( code => 'return', arguments => [] );
195 }
196 my @str;
197 my @pre;
198 my $has_local = $self->has_decl("local");
199 my $has_regex = 0;
200 if (grep {$_->emit_java_has_regex()} @block) {
201 # regex variables like '$1' are implicitly 'local'
202 $has_local = 1;
203 $has_regex = 1;
204 }
205 my $local_label = Perlito5::Java::get_label();
206 local $Perlito5::JAVA_HAS_LOCAL = $has_local;
207 local $Perlito5::JAVA_LOCAL_LABEL = $local_label;
208 $Perlito5::JAVA_CAN_RETURN = 0 if $has_local;
209 if ( $has_local ) {
210 push @pre, 'int ' . $local_label . ' = PerlOp.local_length();';
211 if ($has_regex) {
212 push @pre, 'PerlOp.push_local_regex_result();'
213 }
214 }
215  
216 my $last_statement;
217 if ($wantarray ne 'void' && $wantarray ne 'statement') {
218 $last_statement = pop @block;
219 }
220 for my $decl ( @block ) {
221 push @str, emit_body_statement( $decl, $level, 'statement' );
222 }
223 if ($last_statement) {
224 push @str, emit_last_statement( $self, $last_statement, $level, $wantarray, $has_local, $local_label );
225 }
226  
227 # print STDERR Perlito5::Dumper::Dumper( $self );
228 # print STDERR Perlito5::Dumper::Dumper( \@str );
229  
230 if ($self->{eval_block}) {
231 # eval { ... }
232 return ( @pre,
233 "try {",
234 \@str,
235 "}",
236 "catch(PlReturnException e) {",
237 [ emit_return($has_local, $local_label, 'e.ret') . ";" ],
238 "}",
239 "catch(PlNextException e) {",
240 [ "throw e;" ],
241 "}",
242 "catch(PlLastException e) {",
243 [ "throw e;" ],
244 "}",
245 "catch(PlRedoException e) {",
246 [ "throw e;" ],
247 "}",
248 "catch(PlDieException e) {",
249 [ 'PlV.Scalar_EVAL_ERROR.set(e.ret);',
250 "return PlCx.UNDEF;",
251 ],
252 "}",
253 "catch(Exception e) {",
254 [ 'PlV.Scalar_EVAL_ERROR.set(new PlStringLazyError(e));',
255 "return PlCx.UNDEF;",
256 ],
257 "}",
258 );
259 }
260  
261 if ($self->{top_level}) {
262 # sub { ... }
263 if ($Perlito5::THROW_RETURN) {
264 return ( @pre,
265 "try {",
266 [ @str ],
267 '}',
268 'catch(PlReturnException e) {',
269 [ emit_return($has_local, $local_label, 'e.ret') . ";" ],
270 '}',
271 );
272 }
273 else {
274 return ( @pre, @str );
275 }
276 }
277  
278 if ($self->{not_a_loop}) {
279 # if (1) { ... } simple lexical block
280 if ($has_local && !$last_statement) {
281 if (@block && $block[-1]->isa( 'Perlito5::AST::Apply' ) && $block[-1]->{code} eq 'return' ) {
282 }
283 else {
284 push @str, 'PerlOp.cleanup_local(' . $local_label . ', PlCx.UNDEF);';
285 }
286 }
287 return ( @pre, @str );
288 }
289  
290 if ( $Perlito5::THROW || ($self->{continue} && @{$self->{continue}{stmts}} > 0) ) {
291 # { ... } block with next/last/redo/continue
292  
293 my $redo_label = Perlito5::Java::get_label();
294 my $test_label = 'e.label_id != 0';
295 $test_label = "e.label_id != $block_label && e.label_id != 0"
296 if $block_label;
297  
298 my @continue;
299 if ($self->{continue}) {
300  
301 # TODO - set up next/last/redo inside continue block
302  
303 local $Perlito5::JAVA_CAN_RETURN = 0;
304 push @continue,
305 "if (!$redo_label) {",
306 [ "try {",
307 [ Perlito5::Java::LexicalBlock->new(
308 block => $self->{continue}{stmts},
309 not_a_loop => 1,
310 )->emit_java($level + 2, $wantarray)
311 ],
312 '}',
313 'catch(PlNextException e) {',
314 [ "if ($test_label) {",
315 [ "throw e;" ],
316 "}"
317 ],
318 '}',
319 'catch(PlRedoException e) {',
320 [ "if ($test_label) {",
321 [ "throw e;" ],
322 "}",
323 "$redo_label = true;",
324 ],
325 '}',
326 ],
327 "}";
328 }
329  
330 push @pre,
331 "boolean $redo_label;",
332 "do {",
333 [
334 "$redo_label = false;",
335 "try {",
336 [ @str ],
337 '}',
338 'catch(PlNextException e) {',
339 [ "if ($test_label) {",
340 [ "throw e;" ],
341 "}"
342 ],
343 '}',
344 'catch(PlRedoException e) {',
345 [ "if ($test_label) {",
346 [ "throw e;" ],
347 "}",
348 "$redo_label = true;",
349 ],
350 '}',
351 @continue,
352 ],
353 "} while ($redo_label);";
354 @str = ();
355 }
356 elsif ($has_local && !$last_statement) {
357 # block with "local"
358 push @str, 'PerlOp.cleanup_local(' . $local_label . ', PlCx.UNDEF);';
359 }
360 return ( @pre, @str );
361 }
362 sub emit_java_has_regex { () }
363 }
364  
365 package Perlito5::AST::CompUnit;
366 {
367 sub emit_java {
368 my ($self, $level, $wantarray) = @_;
369 local $Perlito5::JAVA_CAN_RETURN = 0;
370 return Perlito5::Java::LexicalBlock->new(
371 block => $self->{body},
372 not_a_loop => 1,
373 )->emit_java( $level + 1, $wantarray );
374 }
375 sub process_java_import_statement {
376 my ($namespace, $annotation_ast) = @_;
377  
378 # Perl:
379 # package Put { import => 'java.Put' };
380 #
381 # AST:
382 # bless({
383 # 'stmts' => [
384 # bless({
385 # 'arguments' => [],
386 # 'code' => 'package',
387 # 'namespace' => 'Put',
388 # }, 'Perlito5::AST::Apply'),
389 # bless({
390 # 'arguments' => [
391 # bless({
392 # 'arguments' => [],
393 # 'bareword' => 1,
394 # 'code' => 'import',
395 # 'namespace' => '',
396 # }, 'Perlito5::AST::Apply'),
397 # bless({
398 # 'buf' => 'java.Put',
399 # }, 'Perlito5::AST::Buf'),
400 # ],
401 # 'code' => 'infix:<=>>',
402 # 'namespace' => '',
403 # }, 'Perlito5::AST::Apply'),
404 # ],
405 # }, 'Perlito5::AST::Block'),
406  
407 my $str = '';
408  
409 my $Java_class = Perlito5::Java::get_java_class_info();
410 my $class = $namespace;
411 # warn "Java class: $class\n";
412 # TODO - add more information about the class
413  
414 # we need the parameter list as Perl data, so we need to evaluate the AST
415 # - wrap the "list AST into a "hashref" AST
416 my $args_ast = $annotation_ast;
417  
418 # - eval the Perl code and store the arguments to use later
419 my $ast =
420 Perlito5::AST::Block->new(
421 stmts => [$args_ast],
422 );
423 # warn Perlito5::Dumper::Dumper( $ast );
424 my @data = Perlito5::eval_ast($ast);
425 # warn Perlito5::Dumper::Dumper( \@data );
426  
427 $Java_class->{$class} = Perlito5::eval_ast($ast)
428 or die "error in arguments to generate Java class: $@";
429  
430  
431 if ($Java_class->{$class}->{java_path}) {
432 # package header { java_path => 'org.perlito.udfs' }
433 # ==> $Java_class->{header}->{java_path} = 'org.perlito.udfs';
434 $str .= "package $Java_class->{$class}->{java_path};\n";
435 }
436 elsif ($Java_class->{$class}->{import}) {
437 Perlito5::Java::set_java_class_defaults(
438 $class, $Java_class->{$class}->{import},
439 );
440 }
441 elsif ($Java_class->{$class}->{extends}) {
442 # (obsolete)
443 #
444 # extends => 'JavaObject', # Perl package name (a class imported from Java)
445 # methods => [ ... ]
446  
447 my $extended = $Java_class->{ $Java_class->{$class}->{extends} };
448 if ($extended) {
449 $Java_class->{$class}->{extends_java_type} = $extended->{java_type};
450  
451 }
452 else {
453 die "cannot extend class '" . $Java_class->{$class}->{extends} . "' because it was not declared";
454 }
455  
456 my $perl_to_java = $class;
457 $perl_to_java =~ s/:://g;
458 Perlito5::Java::set_java_class_defaults(
459 $class, $perl_to_java,
460 );
461  
462 # warn Perlito5::Dumper::Dumper $Java_class->{$class};
463 # warn "'extends' not implemented";
464 }
465 elsif ($Java_class->{$class}->{implements}) {
466 # (obsolete)
467 #
468 # implements => 'JavaObject', # Perl package name (a class imported from Java)
469 # methods => [ ... ]
470  
471 my $implemented = $Java_class->{ $Java_class->{$class}->{implements} };
472 if ($implemented) {
473 $Java_class->{$class}->{implements_java_type} = $implemented->{java_type};
474  
475 }
476 else {
477 die "cannot implement class '" . $Java_class->{$class}->{implements} . "' because it was not declared";
478 }
479  
480 my $perl_to_java = $class;
481 $perl_to_java =~ s/:://g;
482 Perlito5::Java::set_java_class_defaults(
483 $class, $perl_to_java,
484 );
485  
486 # warn Perlito5::Dumper::Dumper $Java_class->{$class};
487 # warn "'implements' not implemented";
488 }
489 else {
490 die "missing 'import' argument to generate Java class";
491 }
492  
493 return $str;
494 }
495 sub emit_java_program {
496 my ($comp_units, %options) = @_;
497 $Perlito5::PKG_NAME = 'main';
498 $Perlito5::THROW = 0;
499 $Perlito5::THROW_RETURN = 0;
500 my $level = 0;
501 my $wantarray = 'statement';
502 my $str;
503 $str .= Perlito5::Compiler::do_not_edit("//");
504  
505 # look for special 'Java' packages
506 for my $ann ( @Perlito::ANNOTATION ) {
507 $str .= process_java_import_statement(@$ann);
508 }
509  
510 my @main;
511  
512 if ($options{'expand_use'}) {
513 for my $k (keys %INC) {
514 # serialize %INC
515 push @main, Perlito5::AST::Apply->new(
516 code => 'infix:<=>',
517 arguments => [
518 Perlito5::AST::Lookup->new(
519 obj => Perlito5::AST::Var->new(
520 '_decl' => "global",
521 '_namespace' => "main",
522 '_real_sigil' => "%",
523 'name' => "INC",
524 'namespace' => '',
525 'sigil' => "\$",
526 ),
527 index_exp => Perlito5::AST::Buf->new( buf => $k ),
528 ),
529 Perlito5::AST::Buf->new( buf => $INC{$k} ),
530 ],
531 )->emit_java($level + 1, 'void') . ';';
532 }
533 }
534  
535 for my $comp_unit ( @$comp_units ) {
536 my @str = $comp_unit->emit_java($level + 1, $wantarray);
537 # $str[-1] .= ";\n" if @str && !ref($str[-1]);
538 push @main, @str;
539 }
540 if ($options{'expand_use'}) {
541 my $Java_class = Perlito5::Java::get_java_class_info();
542 $str .= join("",
543 Perlito5::Java::Runtime->emit_java(
544 java_classes => $Java_class,
545 java_constants => [], # \@Perlito5::Java::Java_constants,
546 )
547 );
548 }
549  
550 my $main_class = "Main";
551 $main_class = "LibPerl" if $Perlito5::BOOTSTRAP_JAVA_EVAL;
552  
553 $str .= Perlito5::Java::emit_wrap_java(-1,
554 "class $main_class {",
555 [ @Perlito5::Java::Java_constants,
556 "public static void main(String[] args) {",
557 [
558 ( $Perlito5::JAVA_EVAL ? "org.perlito.Perlito5.LibPerl.main( new String[]{} );" : ()),
559  
560 "PlV.init(args);",
561 "int want = PlCx.VOID;",
562 "int return_context = PlCx.VOID;",
563 "PlArray List__ = new PlArray();",
564 "Exception ee = null;",
565 "try {",
566 [ @Perlito5::Java::Java_init,
567 @main,
568 ],
569 "}",
570 "catch(PlReturnException e) {",
571 # TODO - fix blocks and re-enable this error message
572 # [ 'ee = new PlDieException(new PlString("Can\'t return outside a subroutine"));' ],
573 "}",
574 "catch(PlNextException e) {",
575 [ 'ee = new PlDieException(new PlString("Can\'t \\"next\\" outside a loop block"));' ],
576 "}",
577 "catch(PlLastException e) {",
578 [ 'ee = new PlDieException(new PlString("Can\'t \\"last\\" outside a loop block"));' ],
579 "}",
580 "catch(PlRedoException e) {",
581 [ 'ee = new PlDieException(new PlString("Can\'t \\"redo\\" outside a loop block"));' ],
582 "}",
583 "catch(Exception e) {",
584 [ 'ee = e;' ],
585 "}",
586 # emit error messages
587 'if (ee != null) {',
588 [ # 'PlCORE.warn(PlCx.VOID, new PlArray(new PlString(ee.getMessage())));'
589 'ee.printStackTrace(System.err);',
590 ],
591 '}',
592 # execute END blocks
593 'PlV.teardown();',
594 # return error code
595 'if (ee != null) {',
596 [ 'System.exit(1);' ],
597 '}',
598 ],
599 "}",
600 ],
601 [ "public static void init() {",
602 [
603 "main(new String[]{});"
604 ],
605 "}",
606 ],
607 [ "public static PlObject[] apply(String functionName, String... args) {",
608 [
609 "PlArray list = new PlArray(args);",
610 "PlObject result = new PlString(functionName).apply(PlCx.LIST, list);",
611 "PlArray res = result instanceof PlArray ? (PlArray) result : new PlArray(result);",
612 "PlObject[] out = new PlObject[res.to_int()];",
613 "int i = 0;",
614 "for (PlObject s : res) {",
615 [ "out[i++] = s;",
616 ],
617 "}",
618 "return out;",
619 ],
620 "}",
621 ],
622 [ "public static PlObject[] apply(String functionName, PlObject... args) {",
623 [
624 "PlArray list = new PlArray(args);",
625 "PlObject result = new PlString(functionName).apply(PlCx.LIST, list);",
626 "PlArray res = result instanceof PlArray ? (PlArray) result : new PlArray(result);",
627 "PlObject[] out = new PlObject[res.to_int()];",
628 "int i = 0;",
629 "for (PlObject s : res) {",
630 [ "out[i++] = s;",
631 ],
632 "}",
633 "return out;",
634 ],
635 "}",
636 ],
637 [ "public static PlObject[] apply(String functionName) {",
638 [
639 "PlArray list = new PlArray();",
640 "PlObject result = new PlString(functionName).apply(PlCx.LIST, list);",
641 "PlArray res = result instanceof PlArray ? (PlArray) result : new PlArray(result);",
642 "PlObject[] out = new PlObject[res.to_int()];",
643 "int i = 0;",
644 "for (PlObject s : res) {",
645 [ "out[i++] = s;",
646 ],
647 "}",
648 "return out;",
649 ],
650 "}",
651 ],
652 "}",
653 ) . "\n";
654  
655 return $str;
656 }
657 sub emit_java_get_decl { () }
658 sub emit_java_has_regex { () }
659 }
660  
661 package Perlito5::AST::Int;
662 {
663 sub emit_java {
664 my ($self, $level, $wantarray) = @_;
665 my $v = $self->{int};
666 if ( length($v) > 19 || $v > 2**62 ) {
667 # max value is 2**63 - 1
668 if ( length($v) > 19 || $v >= 9223372036854775806.0 ) {
669 return "new PlDouble(" . $v . ".0d)";
670 }
671 return "new PlInt(" . $v . "L)";
672 }
673 if ( $v >= -2 && $v < 0) {
674 return "PlCx.MIN" . abs($v);
675 }
676 if ( $v >= 0 && $v <= 9) {
677 return "PlCx.INT" . abs($v);
678 }
679 my $s = "new PlInt(" . $v . "L)";
680  
681 return Perlito5::Java::get_constant( "PlInt", $s );
682 }
683 sub emit_java_set {
684 die "Can't modify constant item in scalar assignment";
685 }
686 sub emit_java_get_decl { () }
687 sub emit_java_has_regex { () }
688 }
689  
690 package Perlito5::AST::Num;
691 {
692 my $inf = 1000 ** 1000 ** 1000;
693  
694 sub emit_java {
695 my ($self, $level, $wantarray) = @_;
696 my $s;
697 if ($self->{num} == $inf) {
698 $s = "new PlDouble(Double.POSITIVE_INFINITY)";
699 }
700 else {
701 $s = "new PlDouble(" . $self->{num} . "d)";
702 }
703 return Perlito5::Java::get_constant( "PlDouble", $s );
704 }
705 sub emit_java_set {
706 die "Can't modify constant item in scalar assignment";
707 }
708 sub emit_java_get_decl { () }
709 sub emit_java_has_regex { () }
710 }
711  
712 package Perlito5::AST::Buf;
713 {
714 sub emit_java {
715 my ($self, $level, $wantarray) = @_;
716 my $s = "PlStringConstant.getConstant(" . Perlito5::Java::escape_string( $self->{buf} ) . ")";
717  
718 return Perlito5::Java::get_constant( "PlStringConstant", $s );
719 }
720 sub emit_java_set {
721 die "Can't modify constant item in scalar assignment";
722 }
723 sub emit_java_get_decl { () }
724 sub emit_java_has_regex { () }
725 }
726  
727 package Perlito5::AST::Block;
728 {
729 sub emit_java {
730 my ($self, $level, $wantarray) = @_;
731 local $Perlito5::THROW = 0;
732 local $Perlito5::JAVA_CAN_RETURN = 0;
733 my $body = Perlito5::Java::LexicalBlock->new(
734 block => $self->{stmts},
735 block_label => $self->{label},
736 continue => $self->{continue},
737 );
738 my @str = $body->emit_java($level + 1, $wantarray);
739 if ($Perlito5::THROW) {
740 @str = Perlito5::Java::emit_wrap_last_exception_java( $self, \@str, $wantarray );
741 }
742 return Perlito5::Java::emit_wrap_java($level, @str);
743 }
744 sub emit_java_get_decl { () }
745 sub emit_java_has_regex { () }
746 }
747  
748 package Perlito5::AST::Index;
749 {
750 sub emit_java {
751 my ($self, $level, $wantarray, $autovivification_type) = @_;
752 # autovivification_type: array, hash
753 my $method = $autovivification_type || 'aget';
754 $method = 'aget_scalarref' if $autovivification_type eq 'scalar';
755 $method = 'aget_arrayref' if $autovivification_type eq 'array';
756 $method = 'aget_hashref' if $autovivification_type eq 'hash';
757 $method = 'aget_lvalue' if $autovivification_type eq 'lvalue';
758 $method = 'aget_lvalue_local' if $autovivification_type eq 'local';
759 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
760 && $self->{obj}->{code} eq 'prefix:<@>'
761 )
762 || ( $self->{obj}->isa('Perlito5::AST::Var')
763 && $self->{obj}->{sigil} eq '@'
764 )
765 || ( $self->{obj}->isa('Perlito5::AST::Apply')
766 && $self->{obj}->{code} eq 'circumfix:<( )>'
767 )
768 )
769 {
770 # @a[10, 20]
771 # (4,5,6)[0,2]
772 return $self->{obj}->emit_java($level, 'list', 'lvalue') . '.aget_list_of_aliases('
773 . Perlito5::Java::to_context($wantarray) . ', '
774 . Perlito5::Java::to_list([$self->{index_exp}], $level)
775 . ')'
776 }
777 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
778 && $self->{obj}->{code} eq 'prefix:<%>'
779 )
780 || ( $self->{obj}->isa('Perlito5::AST::Var')
781 && $self->{obj}->{sigil} eq '%'
782 )
783 )
784 {
785 # Perl5.20 hash slice
786 # %a[10, 20]
787 # %$a[0, 2] ==> %{$a}[0,2]
788  
789 # "fix" the sigil type
790 my $obj = $self->{obj}->clone();
791 $obj->{sigil} = '@'
792 if $obj->{sigil} eq '%';
793 $obj->{code} = 'prefix:<@>'
794 if $obj->{code} eq 'prefix:<%>';
795  
796 return $obj->emit_java($level) . '.aget_hash_list_of_aliases('
797 . Perlito5::Java::to_context($wantarray) . ', '
798 . Perlito5::Java::to_list([$self->{index_exp}], $level)
799 . ')';
800 }
801 if ( $self->{obj}->isa('Perlito5::AST::Apply')
802 && $self->{obj}->{code} eq 'prefix:<$>'
803 )
804 {
805 # $$a[0] ==> $a->[0]
806 return Perlito5::AST::Call->new(
807 'method' => 'postcircumfix:<[ ]>',
808 'invocant' => $self->{obj}->{arguments}[0],
809 'arguments' => $self->{index_exp},
810 )->emit_java($level, $wantarray, $autovivification_type);
811 }
812 my $s = Perlito5::Java::to_native_int( $self->{index_exp}, $level + 1 );
813 return $self->emit_java_container($level) . '.' . $method . '(' . $s . ')';
814 }
815 sub emit_java_set {
816 my ($self, $arguments, $level, $wantarray, $localize) = @_;
817 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
818 && $self->{obj}->{code} eq 'prefix:<@>'
819 )
820 || ( $self->{obj}->isa('Perlito5::AST::Var')
821 && $self->{obj}->{sigil} eq '@'
822 )
823 )
824 {
825 # @a[10, 20]
826 # @$a[0, 2] ==> @{$a}[0,2]
827 return '((PlArray)' . $self->emit_java($level, 'list'). ').list_set('
828 . Perlito5::Java::to_context($wantarray) . ', '
829 . Perlito5::Java::to_list([$arguments], $level)
830 . ')'
831 }
832 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
833 && $self->{obj}->{code} eq 'prefix:<%>'
834 )
835 || ( $self->{obj}->isa('Perlito5::AST::Var')
836 && $self->{obj}->{sigil} eq '%'
837 )
838 )
839 {
840 # Perl5.20 hash slice
841 # %a[10, 20]
842 # %$a[0, 2] ==> %{$a}[0,2]
843 # TODO - move this message to parser
844 die "Can't modify index/value array slice in list assignment";
845 }
846 if ($localize) {
847 return $self->emit_java_container($level) . '.aget_lvalue_local('
848 . Perlito5::Java::autoquote($self->{index_exp}, $level) . ').set('
849 . Perlito5::Java::to_scalar([$arguments], $level+1)
850 . ')';
851 }
852 my $s = Perlito5::Java::to_native_int( $self->{index_exp}, $level + 1 );
853  
854 if ( $self->{obj}->isa('Perlito5::AST::Apply')
855 && $self->{obj}->{code} eq 'prefix:<$>'
856 )
857 {
858 # ${"Exporter::Cache"}[2]
859 # $$a[0] ==> $a->[0]
860 my $obj = Perlito5::Java::emit_java_autovivify( $self->{obj}->{arguments}[0], $level+1, 'array' );
861 return $obj . '.aset('
862 . $s . ', '
863 . Perlito5::Java::to_scalar([$arguments], $level+1)
864 . ')';
865 }
866  
867 # my $obj = Perlito5::Java::emit_java_autovivify( $self, $level+1, 'array' );
868 # return $obj . '.aset('
869 return $self->emit_java_container($level) . '.aset('
870 . $s . ', '
871 . Perlito5::Java::to_scalar([$arguments], $level+1)
872 . ')';
873 }
874 sub emit_java_container {
875 my $self = shift;
876 my $level = shift;
877 if ( $self->{obj}->isa('Perlito5::AST::Apply')
878 && $self->{obj}->{code} eq 'prefix:<$>'
879 )
880 {
881 # ${"Exporter::Cache"}[2]
882 # $$a[0] ==> $a->[0]
883 my $v = Perlito5::AST::Apply->new( %{$self->{obj}}, code => 'prefix:<@>' );
884 return $v->emit_java($level);
885 }
886 if ( $self->{obj}->isa('Perlito5::AST::Apply')
887 && $self->{obj}->{code} eq 'circumfix:<( )>'
888 )
889 {
890 # the expression inside () returns a list
891 return Perlito5::Java::to_list([$self->{obj}], $level);
892 }
893 if ( $self->{obj}->isa('Perlito5::AST::Var')
894 && $self->{obj}->{sigil} eq '$'
895 )
896 {
897 my $obj = $self->{obj}->clone();
898 $obj->{sigil} = '@';
899 return $obj->emit_java($level);
900 }
901 else {
902 return Perlito5::Java::emit_java_autovivify( $self->{obj}, $level, 'array' );
903 }
904 }
905 sub emit_java_get_decl { () }
906 sub emit_java_has_regex { () }
907 }
908  
909 package Perlito5::AST::Lookup;
910 {
911 sub emit_java {
912 my ($self, $level, $wantarray, $autovivification_type) = @_;
913 # autovivification_type: array, hash
914 my $method = $autovivification_type || 'hget';
915 $method = 'hget_scalarref' if $autovivification_type eq 'scalar';
916 $method = 'hget_arrayref' if $autovivification_type eq 'array';
917 $method = 'hget_hashref' if $autovivification_type eq 'hash';
918 $method = 'hget_lvalue' if $autovivification_type eq 'lvalue';
919 $method = 'hget_lvalue_local' if $autovivification_type eq 'local';
920 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
921 && $self->{obj}->{code} eq 'prefix:<$>'
922 )
923 || ( $self->{obj}->isa('Perlito5::AST::Var')
924 && $self->{obj}->{sigil} eq '$'
925 )
926 )
927 {
928 if ( $self->{index_exp}->isa('Perlito5::AST::Apply')
929 && $self->{index_exp}->{code} eq 'list:<,>'
930 )
931 {
932 # Perl "multidimensional array emulation"
933 # $a{ 'x', 'y' }
934 # $$a{ 'x', 'y' } ==> ${$a}{ 'x', 'y' }
935 $self->{index_exp}{code} = 'join';
936 unshift @{ $self->{index_exp}{arguments} },
937 Perlito5::AST::Var->new(
938 '_decl' => "global",
939 '_namespace' => "main",
940 'name' => ";",
941 'namespace' => '',
942 'sigil' => "\$",
943 );
944 }
945 }
946 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
947 && $self->{obj}->{code} eq 'prefix:<@>'
948 )
949 || ( $self->{obj}->isa('Perlito5::AST::Var')
950 && $self->{obj}->{sigil} eq '@'
951 )
952 )
953 {
954 # @a{ 'x', 'y' }
955 # @$a{ 'x', 'y' } ==> @{$a}{ 'x', 'y' }
956 my $v;
957 if ( $self->{obj}->isa('Perlito5::AST::Var') ) {
958 $v = $self->{obj};
959 }
960 $v = Perlito5::AST::Apply->new( code => 'prefix:<%>', namespace => $self->{obj}->namespace, arguments => $self->{obj}->arguments )
961 if $self->{obj}->isa('Perlito5::AST::Apply');
962  
963 return '((PlHash)' . $v->emit_java($level, 'scalar') . ").hget_list_of_aliases("
964 . Perlito5::Java::to_context($wantarray) . ', '
965 . Perlito5::Java::to_list([$self->{index_exp}], $level)
966 . ')'
967 }
968 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
969 && $self->{obj}->{code} eq 'prefix:<%>'
970 )
971 || ( $self->{obj}->isa('Perlito5::AST::Var')
972 && $self->{obj}->{sigil} eq '%'
973 )
974 )
975 {
976 # Perl5.20 hash slice
977 # %a{ 'x', 'y' }
978 # %$a{ 'x', 'y' } ==> %{$a}{ 'x', 'y' }
979 my $v;
980 if ( $self->{obj}->isa('Perlito5::AST::Var') ) {
981 $v = $self->{obj};
982 }
983 $v = Perlito5::AST::Apply->new( code => 'prefix:<%>', namespace => $self->{obj}->namespace, arguments => $self->{obj}->arguments )
984 if $self->{obj}->isa('Perlito5::AST::Apply');
985  
986 return $v->emit_java($level) . '.hget_hash_list_of_aliases('
987 . Perlito5::Java::to_context($wantarray) . ', '
988 . Perlito5::Java::to_list([$self->{index_exp}], $level)
989 . ')'
990 }
991 if ( $self->{obj}->isa('Perlito5::AST::Apply')
992 && $self->{obj}->{code} eq 'prefix:<$>'
993 )
994 {
995 # $$a{aa} ==> $a->{aa}
996 return Perlito5::AST::Call->new(
997 'method' => 'postcircumfix:<{ }>',
998 'invocant' => $self->{obj}->{arguments}[0],
999 'arguments' => $self->{index_exp},
1000 )->emit_java($level, $wantarray, $autovivification_type);
1001 }
1002 my $index = Perlito5::AST::Lookup->autoquote($self->{index_exp});
1003  
1004 if ( $self->{obj}->isa('Perlito5::AST::Var')
1005 && $self->{obj}->{name} eq '+'
1006 && $self->{obj}->{_namespace} eq 'main'
1007 && $self->{obj}->{sigil} eq '$'
1008 )
1009 {
1010 # $+{aa} => named capture from regex
1011 return 'PerlOp.regex_named_capture('
1012 . Perlito5::Java::to_native_str($index, $level)
1013 . ')';
1014 }
1015  
1016 return $self->emit_java_container($level) . '.' . $method . '('
1017 . Perlito5::Java::to_native_str($index, $level)
1018 . ')';
1019 }
1020 sub emit_java_set {
1021 my ($self, $arguments, $level, $wantarray, $localize) = @_;
1022 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
1023 && $self->{obj}->{code} eq 'prefix:<$>'
1024 )
1025 || ( $self->{obj}->isa('Perlito5::AST::Var')
1026 && $self->{obj}->{sigil} eq '$'
1027 )
1028 )
1029 {
1030 if ( $self->{index_exp}->isa('Perlito5::AST::Apply')
1031 && $self->{index_exp}->{code} eq 'list:<,>'
1032 )
1033 {
1034 # Perl "multidimensional array emulation"
1035 # $a{ 'x', 'y' }
1036 # $$a{ 'x', 'y' } ==> ${$a}{ 'x', 'y' }
1037 $self->{index_exp}{code} = 'join';
1038 unshift @{ $self->{index_exp}{arguments} },
1039 Perlito5::AST::Var->new(
1040 '_decl' => "global",
1041 '_namespace' => "main",
1042 'name' => ";",
1043 'namespace' => '',
1044 'sigil' => "\$",
1045 );
1046 }
1047 }
1048 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
1049 && $self->{obj}->{code} eq 'prefix:<@>'
1050 )
1051 || ( $self->{obj}->isa('Perlito5::AST::Var')
1052 && $self->{obj}->{sigil} eq '@'
1053 )
1054 )
1055 {
1056 # @a{ 'x', 'y' }
1057 # @$a{ 'x', 'y' } ==> @{$a}{ 'x', 'y' }
1058 return '((PlArray)' . $self->emit_java($level, 'list'). ').list_set('
1059 . Perlito5::Java::to_context($wantarray) . ', '
1060 . Perlito5::Java::to_list([$arguments], $level)
1061 . ')'
1062 }
1063 if ( ( $self->{obj}->isa('Perlito5::AST::Apply')
1064 && $self->{obj}->{code} eq 'prefix:<%>'
1065 )
1066 || ( $self->{obj}->isa('Perlito5::AST::Var')
1067 && $self->{obj}->{sigil} eq '%'
1068 )
1069 )
1070 {
1071 # Perl5.20 hash slice
1072 # %a{ 'x', 'y' }
1073 # %$a{ 'x', 'y' } ==> %{$a}{ 'x', 'y' }
1074 # TODO - move this message to parser
1075 die "Can't modify index/value array slice in list assignment";
1076 }
1077 if ($localize) {
1078 return $self->emit_java_container($level) . '.hget_lvalue_local('
1079 . Perlito5::Java::autoquote($self->{index_exp}, $level) . ').set('
1080 . Perlito5::Java::to_scalar([$arguments], $level+1)
1081 . ')';
1082 }
1083  
1084 if ( $self->{obj}->isa('Perlito5::AST::Apply')
1085 && $self->{obj}->{code} eq 'prefix:<$>'
1086 )
1087 {
1088 # $$a{x} ==> $a->{x}
1089 my $obj = Perlito5::Java::emit_java_autovivify( $self->{obj}->{arguments}[0], $level+1, 'hash' );
1090 return $obj . '.hset('
1091 . Perlito5::Java::autoquote($self->{index_exp}, $level) . ', '
1092 . Perlito5::Java::to_scalar([$arguments], $level+1)
1093 . ')';
1094 }
1095  
1096 my $index = Perlito5::AST::Lookup->autoquote($self->{index_exp});
1097 return $self->emit_java_container($level) . '.hset('
1098 . Perlito5::Java::to_native_str($index, $level) . ', '
1099 . Perlito5::Java::to_scalar([$arguments], $level+1)
1100 . ')';
1101 }
1102 sub emit_java_container {
1103 my $self = shift;
1104 my $level = shift;
1105 if ( $self->{obj}->isa('Perlito5::AST::Apply')
1106 && $self->{obj}->{code} eq 'prefix:<$>'
1107 )
1108 {
1109 # ${"Exporter::Cache"}{x}
1110 # $$a{0} ==> $a->{0}
1111 my $v = Perlito5::AST::Apply->new( %{$self->{obj}}, code => 'prefix:<%>' );
1112 return $v->emit_java($level);
1113 }
1114 if ( $self->{obj}->isa('Perlito5::AST::Var')
1115 && $self->{obj}->{sigil} eq '$'
1116 )
1117 {
1118 # my $v = $self->{obj}; HERE
1119  
1120 #if ($self->{obj}{_real_sigil} ne '%') {
1121 # warn Perlito5::Dumper::Dumper($self->{obj});
1122 #}
1123  
1124 my $v = Perlito5::AST::Var->new( %{$self->{obj}}, sigil => '%' );
1125 return $v->emit_java($level)
1126 }
1127 else {
1128 return Perlito5::Java::emit_java_autovivify( $self->{obj}, $level, 'hash' );
1129 }
1130 }
1131 sub emit_java_get_decl { () }
1132 sub emit_java_has_regex { () }
1133 }
1134  
1135 package Perlito5::AST::Var;
1136 {
1137 my $inf = 1000 ** 1000 ** 1000;
1138  
1139 sub emit_java_global {
1140 my ($self, $level, $wantarray, $localize) = @_;
1141 my $local = $localize ? "_local" : "";
1142 my $str_name = $self->{name};
1143 my $sigil = $self->{_real_sigil} || $self->{sigil};
1144 my $namespace = $self->{namespace} || $self->{_namespace};
1145 if ($sigil eq '@' && $self->{name} eq '_' && $namespace eq 'main') {
1146 # XXX - optimization - @_ is a lexical
1147 my $s = 'List__';
1148 if ($self->{sigil} eq '$#') {
1149 return $s . '.end_of_array_index()';
1150 }
1151 if ( $wantarray eq 'scalar' ) {
1152 return $s . '.length_of_array()';
1153 }
1154 if ( $wantarray eq 'runtime' || $wantarray eq 'return' ) {
1155 return '(' . Perlito5::Java::to_context($wantarray) . ' == PlCx.LIST'
1156 . ' ? ' . $s
1157 . ' : ' . $s . '.length_of_array()'
1158 . ')';
1159 }
1160 return $s;
1161 }
1162  
1163 if ($sigil eq '$') {
1164 if ($self->{name} > 0
1165 && $self->{name} != $inf # $Inf in Math::Complex
1166 ) {
1167 # regex captures
1168 return 'PerlOp.regex_var(' . (0 + $self->{name}) . ')'
1169 }
1170 if ($namespace eq 'main') {
1171 my $java_name = $Perlito5::Java::special_scalar{$self->{name}};
1172 if ($java_name) {
1173 # $_ ==> PlV.Scalar_ARG
1174 return "PlV.$java_name" if !$local;
1175 return "PlV.sget${local}_${java_name}()";
1176 }
1177 }
1178 if ($self->{name} eq '&' || $self->{name} eq '`' || $self->{name} eq "'") {
1179 # regex match $&
1180 return 'PerlOp.regex_var(' . Perlito5::Java::escape_string($self->{name}) . ')'
1181 }
1182 if ($self->{name} eq '$') {
1183 # PID $$
1184 return 'PerlOp.getPID()'
1185 }
1186 }
1187 if ( $sigil eq '::' ) {
1188 return Perlito5::Java::escape_string( $namespace );
1189 # return Perlito5::AST::Buf->new( buf => $namespace )->emit_java($level, 'scalar');
1190 }
1191  
1192 my $full_name = $namespace . '::' . $str_name;
1193 my $index = Perlito5::Java::escape_string($full_name);
1194 if ( $sigil eq '$' ) {
1195 if (!$local) {
1196 # create a PlStringConstant
1197 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1198 return $scalar . '.scalarRef'
1199 }
1200 return "PlV.sget$local(" . $index . ')';
1201 }
1202 if ( $sigil eq '*' ) {
1203 return "PlV.fget$local(" . $index . ')';
1204 }
1205 if ( $sigil eq '&' ) {
1206 my $namespace = $self->{namespace} || $Perlito5::PKG_NAME;
1207 # create a PlStringConstant
1208 my $sub = Perlito5::AST::Buf->new( buf => $namespace . '::' . $str_name )->emit_java($level, 'scalar');
1209 return $sub . '.apply(' . Perlito5::Java::to_context($wantarray) . ', List__)';
1210 }
1211 if ($sigil eq '@') {
1212 my $s = "PlV.array_get$local(" . $index . ')';
1213 if (!$local) {
1214 # create a PlStringConstant
1215 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1216 $s = $scalar . '.arrayRef.o.array_deref_strict()';
1217 }
1218 if ($self->{sigil} eq '$#') {
1219 return $s . '.end_of_array_index()'
1220 }
1221 if ( $wantarray eq 'scalar' ) {
1222 return $s . '.length_of_array()';
1223 }
1224 return $s;
1225 }
1226 if ($sigil eq '%') {
1227 if (!defined($str_name)) {
1228 # %Module::
1229 return "PerlOp.getSymbolTable(" . $index . ')';
1230 }
1231 if (!$local) {
1232 # create a PlStringConstant
1233 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1234 return $scalar . '.hashRef.o.hash_deref_strict()';
1235 }
1236 return "PlV.hash_get$local(" . $index . ')';
1237 }
1238 die "don't know how to access variable ", $sigil, $self->name;
1239 }
1240  
1241 sub emit_java_global_set {
1242 my ($self, $arguments, $level, $wantarray, $localize) = @_;
1243 my $local = $localize ? "_local" : "";
1244 my $str_name = $self->{name};
1245 my $sigil = $self->{_real_sigil} || $self->{sigil};
1246 my $namespace = $self->{namespace} || $self->{_namespace};
1247 if ($sigil eq '@' && $self->{name} eq '_' && $namespace eq 'main') {
1248 # XXX - optimization - @_ is a lexical
1249 my $s = 'List__';
1250 if ($self->{sigil} eq '$#') {
1251 return $s . '.set_end_of_array_index(' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')';
1252 }
1253 if ( $wantarray eq 'scalar' ) {
1254 return $s . '.to_long()';
1255 }
1256 # TODO - return in the right context
1257 # TODO - local()-ize if needed
1258 return $s . ".set(" . Perlito5::Java::to_list([$arguments], $level+1) . ')';
1259 # if ( $wantarray eq 'runtime' ) {
1260 # return '(want'
1261 # . ' ? ' . $s
1262 # . ' : ' . $s . '.to_long()'
1263 # . ')';
1264 # }
1265 # return $s;
1266 }
1267  
1268 if ($sigil eq '$' && $self->{name} > 0
1269 && $self->{name} != $inf # $Inf in Math::Complex
1270 )
1271 {
1272 # regex captures
1273 return 'p5_regex_capture[' . ($self->{name} - 1) . ']'
1274 }
1275 if ( $sigil eq '::' ) {
1276 return Perlito5::Java::escape_string( $namespace );
1277 }
1278  
1279 my $full_name = $namespace . '::' . $str_name;
1280 my $index = Perlito5::Java::escape_string($full_name);
1281 if ( $sigil eq '$' ) {
1282 if ($namespace eq 'main') {
1283 my $java_name = $Perlito5::Java::special_scalar{$self->{name}};
1284 if ($java_name) {
1285 # $_ ==> PlV.Scalar_ARG
1286 return "PlV.${java_name}.set(" . Perlito5::Java::to_scalar([$arguments], $level+1) . ")" if !$local;
1287 return "PlV.sset${local}_${java_name}(" . Perlito5::Java::to_scalar([$arguments], $level+1) . ")";
1288 }
1289 }
1290 if (!$local) {
1291 # create a PlStringConstant
1292 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1293 return $scalar . '.scalarRef.set(' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')';
1294 }
1295 return "PlV.sset$local(" . $index . ', ' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')';
1296 }
1297 if ( $sigil eq '@' ) {
1298  
1299 if ($self->{sigil} eq '$#') {
1300 $self = $self->clone();
1301 $self->{sigil} = '@';
1302 return 'PlV.array_get(' . $index . ').set_end_of_array_index(' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')';
1303 }
1304 # TODO - return in the right context
1305 if (!$local) {
1306 # create a PlStringConstant
1307 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1308 return $scalar . '.arrayRef.o.array_deref_set(' . Perlito5::Java::to_list([$arguments], $level+1) . ')';
1309 }
1310 return "PlV.array_set$local(" . $index . ', ' . Perlito5::Java::to_list([$arguments], $level+1) . ')';
1311 }
1312 if ( $sigil eq '%' ) {
1313 if (!$local) {
1314 # create a PlStringConstant
1315 my $scalar = Perlito5::AST::Buf->new( buf => $full_name )->emit_java($level, 'scalar');
1316 return $scalar . '.hashRef.o.hash_deref_set(' . Perlito5::Java::to_list([$arguments], $level+1) . ')';
1317 }
1318 return "PlV.hash_set$local(" . $index . ', ' . Perlito5::Java::to_list([$arguments], $level+1) . ')';
1319 }
1320 if ( $sigil eq '*' ) {
1321 return "PlV.glob_set$local(" . $index . ', '
1322 . Perlito5::Java::to_scalar([$arguments], $level+1) . ', '
1323 . Perlito5::Java::escape_string($Perlito5::PKG_NAME)
1324 . ')';
1325 }
1326 if ( $sigil eq '&' ) {
1327 # return 'PlV.apply(' . $index . ', ' . Perlito5::Java::to_context($wantarray) . ', List__)';
1328 }
1329 die "don't know how to assign to variable ", $sigil, $self->name;
1330 }
1331  
1332 sub emit_java_global_set_alias {
1333 my ($self, $arguments, $level, $wantarray, $localize) = @_;
1334 die "can't localize emit_java_global_set_alias()" if $localize;
1335 my $str_name = $self->{name};
1336 my $sigil = $self->{_real_sigil} || $self->{sigil};
1337 my $namespace = $self->{namespace} || $self->{_namespace};
1338 if ($sigil eq '$' && $self->{name} > 0) {
1339 # TODO - for $1 (...) {} is valid perl
1340 die "not implemented emit_java_global_set_alias() for regex capture";
1341 }
1342 my $index = Perlito5::Java::escape_string($namespace . '::' . $str_name);
1343 $arguments = Perlito5::Java::to_scalar([$arguments], $level+1)
1344 if ref($arguments);
1345 if ( $sigil eq '$' ) {
1346 if ($namespace eq 'main') {
1347 my $java_name = $Perlito5::Java::special_scalar{$self->{name}};
1348 if ($java_name) {
1349 # $_ ==> PlV.Scalar_ARG
1350 return "PlV.sset_alias_${java_name}(" . $arguments . ")";
1351 }
1352 }
1353 return "PlV.sset_alias(" . $index . ', ' . $arguments . ")";
1354 }
1355 return "PlV.aset_alias(" . $index . ', ' . $arguments . ")" if $sigil eq '@';
1356 return "PlV.hset_alias(" . $index . ', ' . $arguments . ")" if $sigil eq '%';
1357 die "can't emit_java_global_set_alias() for sigil '$sigil'";
1358 }
1359  
1360 sub emit_java {
1361 my ($self, $level, $wantarray) = @_;
1362 $self = $self->to_begin_scratchpad();
1363 my $sigil = $self->{_real_sigil} || $self->{sigil};
1364 my $decl_type = $self->{_decl} || 'global';
1365 if ( $decl_type ne 'my' && $decl_type ne 'state' ) {
1366 return $self->emit_java_global($level, $wantarray);
1367 }
1368 my $str_name = $self->{name} . "_" . $self->{_id};
1369  
1370 $str_name = $Perlito5::Java::Java_var_name{$self->{_id}}
1371 if exists $Perlito5::Java::Java_var_name{$self->{_id}};
1372  
1373 if ($self->{sigil} eq '$#') {
1374 return $str_name . '.end_of_array_index()';
1375 }
1376 if ( $sigil eq '@' ) {
1377 if ( $wantarray eq 'scalar' ) {
1378 return $self->emit_java($level, 'list') . '.length_of_array()';
1379 }
1380 if ( $wantarray eq 'runtime' || $wantarray eq 'return' ) {
1381 return '(' . Perlito5::Java::to_context($wantarray) . ' == PlCx.LIST'
1382 . ' ? ' . $self->emit_java($level, 'list')
1383 . ' : ' . $self->emit_java($level, 'list') . '.length_of_array()'
1384 . ')';
1385 }
1386 }
1387 return $str_name;
1388 }
1389  
1390 sub emit_java_set {
1391 my ($self, $arguments, $level, $wantarray) = @_;
1392 $self = $self->to_begin_scratchpad();
1393 my $decl_type = $self->{_decl} || 'global';
1394 if ( $decl_type ne 'my' && $decl_type ne 'state' ) {
1395 return $self->emit_java_global_set($arguments, $level, $wantarray);
1396 }
1397 my $open = $wantarray eq 'void' || $wantarray eq 'statement' ? '' : '(';
1398 my $close = $wantarray eq 'void' || $wantarray eq 'statement' ? '' : ')';
1399 my $sigil = $self->{_real_sigil} || $self->{sigil};
1400 my $id = $self->{_id};
1401 if ( $sigil eq '$' && $id ) {
1402 my $Java_var = Perlito5::Java::get_java_var_info();
1403 my $type = $Java_var->{ $id }{type} || 'PlLvalue';
1404 if ($type ne 'PlLvalue') {
1405 # "set" a typed variable - there is no .set() method
1406  
1407 my $class_info = Perlito5::Java::get_java_class_info();
1408 if (exists $class_info->{$type}) {
1409  
1410 # cast the argument to java_type
1411 #
1412 # use Data::Dumper;
1413 # print STDERR Dumper Perlito5::Java::get_java_class_info()->{$type};
1414 #
1415 # $ perl perlito5.pl -Isrc5/lib -Cjava -e ' package XYZ { import => "a.b.C" } my XYZ $xx = $v ' > x.txt
1416 # $VAR1 = {
1417 # 'java_type' => 'a.b.C',
1418 # 'java_native_to_perl' => 'pC',
1419 # 'perl_package' => 'XYZ',
1420 # 'import' => 'a.b.C',
1421 # 'perl_to_java' => 'to_XYZ'
1422 # };
1423  
1424 # TODO - right side can be a native var or expression
1425  
1426 if (ref($arguments) eq "Perlito5::AST::Var") {
1427 my $arg_sigil = $arguments->{_real_sigil} || $arguments->{sigil};
1428 my $arg_id = $arguments->{_id};
1429 if ( $arg_sigil eq '$' ) {
1430 my $arg_type = 'PlLvalue';
1431 $arg_type = $Java_var->{ $arg_id }{type}
1432 if $arg_id && $Java_var->{ $arg_id }{type};
1433 if ($arg_type eq 'PlLvalue') {
1434 # left type is typed, right type is Perl
1435  
1436 # print STDERR Perlito5::Dumper::Dumper($class_info->{$type});
1437  
1438 # TODO - cast the result from toJava()
1439  
1440 if (exists $class_info->{$type}{perl_to_java}) {
1441 # $v.toString()
1442 return $self->emit_java($level)
1443 . ' = ' . Perlito5::Java::to_scalar([$arguments], $level+1)
1444 . '.' . $class_info->{$type}{perl_to_java} . '()';
1445 }
1446  
1447 if (exists $class_info->{$type}{java_type}) {
1448 # (MyClass)($v.toJava())
1449 # - this runs with @SuppressWarnings("unchecked")
1450 my $t = $class_info->{$type}{java_type};
1451 return $self->emit_java($level)
1452 . ' = ' . '(' . $t . ')('
1453 . Perlito5::Java::to_scalar([$arguments], $level+1) . '.toJava())';
1454 }
1455  
1456 }
1457 }
1458 }
1459 my $java_type = $class_info->{$type}{java_type};
1460 return $self->emit_java($level) . ' = ' . Perlito5::Java::to_native_args([$arguments], $level+1, $java_type);
1461 }
1462  
1463 return $self->emit_java($level) . ' = ' . Perlito5::Java::to_native_args([$arguments], $level+1);
1464 }
1465 return $self->emit_java($level) . '.set(' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')'
1466 }
1467 if ( $sigil eq '@' ) {
1468  
1469 if ($self->{sigil} eq '$#') {
1470 $self = $self->clone();
1471 $self->{sigil} = '@';
1472 return $open . $self->emit_java($level) . '.set_end_of_array_index(' . Perlito5::Java::to_scalar([$arguments], $level+1) . ')' . $close
1473 }
1474  
1475 return $self->emit_java($level) . '.set(' . Perlito5::Java::to_list([$arguments], $level+1) . ')'
1476 }
1477 if ( $sigil eq '%' ) {
1478 return $self->emit_java($level) . '.set('
1479 . Perlito5::Java::to_context($wantarray) . ', '
1480 . Perlito5::Java::to_list([$arguments], $level+1, 'hash')
1481 . ')';
1482 }
1483 if ( $sigil eq '*' ) {
1484 my $namespace = $self->{namespace} || $self->{_namespace};
1485 return 'p5typeglob_set('
1486 . Perlito5::Java::escape_string($namespace) . ', '
1487 . Perlito5::Java::escape_string($self->{name}) . ', '
1488 . Perlito5::Java::to_scalar([$arguments], $level+1)
1489 . ')'
1490 }
1491 die "don't know how to assign to variable ", $sigil, $self->name;
1492 }
1493  
1494 sub emit_java_get_decl { () }
1495 sub emit_java_has_regex { () }
1496 }
1497  
1498 package Perlito5::AST::Decl;
1499 {
1500 sub emit_java {
1501 my ($self, $level, $wantarray) = @_;
1502 my $var = $self->{var};
1503 $var = $var->to_begin_scratchpad() if ref($var) eq 'Perlito5::AST::Var';
1504 my $localize = '';
1505 if ($self->{decl} eq 'local') {
1506 $localize = 'local';
1507 if ( ref($var) eq 'Perlito5::AST::Var' ) {
1508 return $var->emit_java_global($level, $wantarray, $localize);
1509 }
1510 }
1511 $var->emit_java( $level, $wantarray, $localize );
1512 }
1513 sub emit_java_init {
1514 my ($self, $level, $wantarray) = @_;
1515 my $var = $self->{var};
1516 return () if ref($var) eq 'Perlito5::AST::Var' && $var->is_begin_scratchpad();
1517 my $Java_var = Perlito5::Java::get_java_var_info();
1518 my $type = $self->{type} || 'PlLvalue';
1519 my $id = $self->{var}{_id};
1520 if ( $id ) {
1521  
1522 return if $Java_var->{ $id }; # done
1523  
1524 $Java_var->{ $id } = { id => $id, type => $type };
1525 }
1526  
1527 if ($self->{decl} eq 'our') {
1528 return '';
1529 }
1530 if ($self->{decl} eq 'local') {
1531 return '';
1532 }
1533 if ($self->{decl} eq 'my' || $self->{decl} eq 'state') {
1534 if ($self->{var}->{sigil} eq '%') {
1535 return 'PlHash ' . $self->{var}->emit_java($level) . ' = new PlHash();';
1536 }
1537 elsif ($self->{var}->{sigil} eq '@') {
1538 return 'PlArray ' . $self->{var}->emit_java($level) . ' = new PlArray();';
1539 }
1540 else {
1541 my $Java_class = Perlito5::Java::get_java_class_info();
1542 my $java_type = $Java_class->{$type}{java_type} || 'PlLvalue';
1543 if( $java_type eq 'PlLvalue' ) {
1544 return "${java_type} " . $self->{var}->emit_java($level) . " = new ${java_type}();";
1545 } else {
1546 return "${java_type} " . $self->{var}->emit_java($level) . ";";
1547 }
1548 }
1549 }
1550 else {
1551 die "not implemented: Perlito5::AST::Decl '" . $self->{decl} . "'";
1552 }
1553 }
1554 sub emit_java_set {
1555 my ($self, $arguments, $level, $wantarray) = @_;
1556 my $var = $self->{var};
1557 $var = $var->to_begin_scratchpad() if ref($var) eq 'Perlito5::AST::Var';
1558 my $localize = '';
1559 if ($self->{decl} eq 'local') {
1560 $localize = 'local';
1561 if ( ref($var) eq 'Perlito5::AST::Var' ) {
1562 return $var->emit_java_global_set($arguments, $level, $wantarray, $localize);
1563 }
1564 }
1565 $var->emit_java_set($arguments, $level, $wantarray, $localize);
1566 }
1567 sub emit_java_get_decl {
1568 my $self = shift;
1569 my $var = $self->{var};
1570 return () if ref($var) eq 'Perlito5::AST::Var' && $var->is_begin_scratchpad();
1571 return ($self);
1572 }
1573 sub emit_java_has_regex { () }
1574 }
1575  
1576 package Perlito5::AST::Call;
1577 {
1578 sub emit_java {
1579 my ($self, $level, $wantarray, $autovivification_type) = @_;
1580 # autovivification_type: array, hash
1581 my $meth = $self->{method};
1582  
1583 if ( $meth eq 'postcircumfix:<[ ]>' ) {
1584 my $method = $autovivification_type || 'aget';
1585 $method = 'aget_scalarref' if $autovivification_type eq 'scalar';
1586 $method = 'aget_arrayref' if $autovivification_type eq 'array';
1587 $method = 'aget_hashref' if $autovivification_type eq 'hash';
1588 $method = 'aget_lvalue' if $autovivification_type eq 'lvalue';
1589 $method = 'aget_lvalue_local' if $autovivification_type eq 'local';
1590 return Perlito5::Java::emit_java_autovivify( $self->{invocant}, $level, 'array' )
1591 . '.' . $method . '('
1592 . Perlito5::Java::to_native_int( $self->{arguments}, $level + 1 )
1593 . ')';
1594 }
1595 if ( $meth eq 'postcircumfix:<{ }>' ) {
1596 my $method = $autovivification_type || 'hget';
1597 $method = 'hget_scalarref' if $autovivification_type eq 'scalar';
1598 $method = 'hget_arrayref' if $autovivification_type eq 'array';
1599 $method = 'hget_hashref' if $autovivification_type eq 'hash';
1600 $method = 'hget_lvalue' if $autovivification_type eq 'lvalue';
1601 $method = 'hget_lvalue_local' if $autovivification_type eq 'local';
1602  
1603 my $args = $self->{arguments};
1604 if ( (ref($args) eq 'Perlito5::AST::Apply')
1605 && $args->{code} eq 'list:<,>'
1606 )
1607 {
1608 # Perl "multidimensional array emulation"
1609 # $a{ 'x', 'y' }
1610 # $$a{ 'x', 'y' } ==> ${$a}{ 'x', 'y' }
1611 $args->{code} = 'join';
1612 unshift @{ $args->{arguments} },
1613 Perlito5::AST::Var->new(
1614 '_decl' => "global",
1615 '_namespace' => "main",
1616 'name' => ";",
1617 'namespace' => '',
1618 'sigil' => "\$",
1619 );
1620 }
1621  
1622 return Perlito5::Java::emit_java_autovivify( $self->{invocant}, $level, 'hash' )
1623 . '.' . $method . '('
1624 . Perlito5::Java::to_native_str(Perlito5::AST::Lookup->autoquote($self->{arguments}), $level + 1, 'list')
1625 . ')';
1626 }
1627 if ($meth eq 'postcircumfix:<( )>') {
1628 # $x->()
1629 my $invocant;
1630  
1631 if ( ref( $self->{invocant} ) eq 'Perlito5::AST::Var' && $self->{invocant}{sigil} eq '::' ) {
1632 if ( $self->{invocant}{namespace} eq '__SUB__' || $self->{invocant}{namespace} eq 'CORE::__SUB__' ) {
1633 # __SUB__->()
1634 $invocant = 'this.currentSub'; # "this" is the closure
1635 }
1636 else {
1637 # x->()
1638 my $fullname = $self->{invocant}{namespace};
1639 if ($fullname !~ /::/) {
1640 $fullname = $Perlito5::PKG_NAME . '::' . $fullname;
1641 }
1642 $invocant = Perlito5::AST::Buf->new( buf => $fullname )->emit_java($level, 'scalar');
1643 }
1644 }
1645 elsif ( ref( $self->{invocant} ) eq 'Perlito5::AST::Int' ) {
1646 # 4->()
1647 $invocant = Perlito5::AST::Buf->new( buf => $Perlito5::PKG_NAME . '::' . $self->{invocant}{int} )->emit_java($level, 'scalar');
1648 }
1649 else {
1650 # $x->()
1651 $invocant = $self->{invocant}->emit_java($level, 'scalar');
1652 }
1653  
1654 return $invocant . '.apply('
1655 . Perlito5::Java::to_context($wantarray) . ', '
1656 . Perlito5::Java::to_list($self->{arguments})
1657 . ')';
1658 }
1659 if (substr($meth, 0, 7) eq 'SUPER::') {
1660 # $x->SUPER::meth
1661 my $method = substr($meth, 7);
1662 if ($method) {
1663 $method = Perlito5::Java::escape_string($method);
1664 return 'PerlOp.callSuper('
1665 . $method . ', '
1666 . Perlito5::Java::pkg . ', '
1667 . Perlito5::Java::to_method_call_param_list($self->{invocant}, $self->{arguments}, $level + 1) . ', '
1668 . Perlito5::Java::to_context($wantarray)
1669 . ')'
1670 }
1671 }
1672  
1673 # class method call in native 'Java' packages
1674 #
1675 # package Sample { import => "misc.Java.Sample" };
1676 # Sample->new();
1677 # new Sample();
1678 #
1679 if ( ref($self->{invocant}) eq 'Perlito5::AST::Var' && $self->{invocant}->{sigil} eq '::' ) {
1680 my $Java_class = Perlito5::Java::get_java_class_info();
1681 if ( exists $Java_class->{$self->{invocant}->{namespace}} ) {
1682 my $info = $Java_class->{$self->{invocant}->{namespace}};
1683 if ($meth eq 'new') {
1684 return "new $info->{java_type}(" . Perlito5::Java::to_native_args($self->{arguments}) . ")";
1685 }
1686 if ($self->{_no_params}) {
1687 # Sample->NAME
1688 return "$info->{java_type}.${meth}";
1689 }
1690 else {
1691 return "$info->{java_type}.${meth}(" . Perlito5::Java::to_native_args($self->{arguments}) . ")";
1692 }
1693 }
1694 }
1695  
1696 my $invocant = $self->{invocant}->emit_java($level, 'scalar');
1697  
1698 # method call on a typed invocant
1699 # package Sample { import => "misc.Java.Sample" };
1700 # my Sample $s;
1701 # $s->meth();
1702 #
1703 if ( ref($self->{invocant}) eq 'Perlito5::AST::Var' && $self->{invocant}->{_id} ) {
1704 my $id = $self->{invocant}->{_id};
1705 my $Java_var = Perlito5::Java::get_java_var_info();
1706 my $type = $Java_var->{ $id }{type} || 'PlLvalue';
1707 if ($type ne 'PlLvalue') {
1708 if ($self->{_no_params}) {
1709 # $s->NAME
1710 return "$invocant.${meth}";
1711 }
1712 else {
1713 return "$invocant.${meth}(" . Perlito5::Java::to_native_args($self->{arguments}) . ")";
1714 }
1715 }
1716 }
1717  
1718 # method call on a "native" invocant
1719 # package Sample { import => "misc.Java.Sample" };
1720 # my Sample $s;
1721 # $s->meth()->meth();
1722 #
1723 if ( Perlito5::Java::is_native($self->{invocant}) ) {
1724 if ($self->{_no_params}) {
1725 # $s->NAME
1726 return "$invocant.${meth}";
1727 }
1728 else {
1729 return "$invocant.${meth}(" . Perlito5::Java::to_native_args($self->{arguments}) . ")";
1730 }
1731 }
1732  
1733 # "Perl" method call
1734  
1735 if ( ref($meth) ) {
1736 $meth = $meth->emit_java($level, 'scalar');
1737 }
1738 else {
1739 # create a PlStringConstant
1740 $meth = Perlito5::AST::Buf->new( buf => $meth )->emit_java($level, 'scalar');
1741 }
1742  
1743 return 'PerlOp.call('
1744 . $meth . ', '
1745 . Perlito5::Java::to_method_call_param_list($self->{invocant}, $self->{arguments}, $level + 1) . ', '
1746 . Perlito5::Java::to_context($wantarray)
1747 . ')'
1748 }
1749  
1750 sub emit_java_set {
1751 my ($self, $arguments, $level, $wantarray) = @_;
1752 if ( $self->{method} eq 'postcircumfix:<[ ]>' ) {
1753 return Perlito5::Java::emit_java_autovivify( $self->{invocant}, $level, 'array' )
1754 . '.aset('
1755 . Perlito5::Java::to_native_int($self->{arguments}, $level+1) . ', '
1756 . Perlito5::Java::to_scalar([$arguments], $level+1)
1757 . ')';
1758 }
1759 if ( $self->{method} eq 'postcircumfix:<{ }>' ) {
1760  
1761 my $args = $self->{arguments};
1762 if ( (ref($args) eq 'Perlito5::AST::Apply')
1763 && $args->{code} eq 'list:<,>'
1764 )
1765 {
1766 # Perl "multidimensional array emulation"
1767 # $a{ 'x', 'y' }
1768 # $$a{ 'x', 'y' } ==> ${$a}{ 'x', 'y' }
1769 $args->{code} = 'join';
1770 unshift @{ $args->{arguments} },
1771 Perlito5::AST::Var->new(
1772 '_decl' => "global",
1773 '_namespace' => "main",
1774 'name' => ";",
1775 'namespace' => '',
1776 'sigil' => "\$",
1777 );
1778 }
1779  
1780 return Perlito5::Java::emit_java_autovivify( $self->{invocant}, $level, 'hash' )
1781 . '.hset('
1782 . Perlito5::Java::to_native_str(Perlito5::AST::Lookup->autoquote($self->{arguments}), $level + 1, 'list') . ', '
1783 . Perlito5::Java::to_scalar([$arguments], $level+1)
1784 . ')';
1785 }
1786 die "don't know how to assign to method ", $self->{method};
1787 }
1788 sub emit_java_get_decl { () }
1789 sub emit_java_has_regex { () }
1790 }
1791  
1792 package Perlito5::AST::If;
1793 {
1794 sub emit_java {
1795 my ($self, $level, $wantarray) = @_;
1796 my $cond = $self->{cond};
1797  
1798 # extract declarations from 'cond'
1799 my @str;
1800 my $old_level = $level;
1801 # print Perlito5::Dumper::Dumper($self);
1802 # print Perlito5::Dumper::Dumper($self->{cond});
1803 if ($cond) {
1804 my @var_decl = $cond->emit_java_get_decl();
1805 for my $arg (@var_decl) {
1806 push @str, $arg->emit_java_init($level + 1, $wantarray);
1807 }
1808 }
1809 my $body =
1810 ref($self->{body}) ne 'Perlito5::AST::Block'
1811 ? $self->{body} # may be undef
1812 : (!@{ $self->{body}->stmts })
1813 ? undef
1814 : Perlito5::Java::LexicalBlock->new( block => $self->{body}->stmts, not_a_loop => 1 );
1815 my $otherwise =
1816 ref($self->{otherwise}) ne 'Perlito5::AST::Block'
1817 ? $self->{otherwise} # may be undef
1818 : (!@{ $self->{otherwise}->stmts })
1819 ? undef
1820 : Perlito5::Java::LexicalBlock->new( block => $self->{otherwise}->stmts, not_a_loop => 1 );
1821
1822 push @str, 'if (' . Perlito5::Java::to_native_bool($cond, $level + 1) . ') {';
1823 if ($body) {
1824 push @str, [ $body->emit_java( $level + 1, $wantarray ) ];
1825 }
1826 push @str, '}';
1827 if ($otherwise) {
1828 # TODO - this breaks if a variable is declared in the "elsif" condition
1829 # if ( @{ $otherwise->{block} } == 1
1830 # && ref($otherwise->{block}[0]) eq 'Perlito5::AST::If'
1831 # )
1832 # {
1833 # push @str, ( 'else', $otherwise->{block}[0]->emit_java( $level, $wantarray ) );
1834 # }
1835 # else {
1836 # push @str,
1837 # 'else {',
1838 # [ $otherwise->emit_java( $level + 1, $wantarray ) ],
1839 # '}';
1840 # }
1841 push @str,
1842 'else {',
1843 [ $otherwise->emit_java( $level + 1, $wantarray ) ],
1844 '}';
1845 }
1846 return Perlito5::Java::emit_wrap_java($level, @str);
1847 }
1848 sub emit_java_get_decl { () }
1849 sub emit_java_has_regex { () }
1850 }
1851  
1852  
1853 package Perlito5::AST::When;
1854 {
1855 sub emit_java {
1856 my ($self, $level, $wantarray) = @_;
1857 # TODO - special case when When is inside a Given block
1858 # TODO - special case when When is a statement modifier
1859 my $cond = $self->{cond};
1860 # extract declarations from 'cond'
1861 my @str;
1862 my $old_level = $level;
1863 # print Perlito5::Dumper::Dumper($self);
1864 # print Perlito5::Dumper::Dumper($self->{cond});
1865 if ($cond) {
1866 my @var_decl = $cond->emit_java_get_decl();
1867 for my $arg (@var_decl) {
1868 $level = $old_level + 1;
1869 push @str, $arg->emit_java_init($level, $wantarray);
1870 }
1871 }
1872 $cond = Perlito5::AST::Apply->new(
1873 'arguments' => [
1874 Perlito5::AST::Var::SCALAR_ARG(),
1875 $cond,
1876 ],
1877 'code' => 'infix:<~~>',
1878 'namespace' => '',
1879 );
1880 my $next = Perlito5::AST::Apply->new(
1881 'arguments' => [],
1882 'bareword' => 1,
1883 'code' => 'next',
1884 'namespace' => '',
1885 );
1886 my $body =
1887 ref($self->{body}) ne 'Perlito5::AST::Block'
1888 ? Perlito5::Java::LexicalBlock->new( block => [ $self->{body} ], not_a_loop => 1 )
1889 : (!@{ $self->{body}->stmts })
1890 ? undef
1891 : Perlito5::Java::LexicalBlock->new( block => $self->{body}->stmts, not_a_loop => 1 );
1892 push @{ $body->{block} }, $next;
1893  
1894 push @str, 'if (' . Perlito5::Java::to_native_bool($cond, $level + 1) . ') {';
1895 if ($body) {
1896 push @str, [ $body->emit_java( $level + 1, $wantarray ) ];
1897 }
1898 push @str, '}';
1899 return Perlito5::Java::emit_wrap_java($level, @str);
1900 }
1901 sub emit_java_get_decl { () }
1902 sub emit_java_has_regex { () }
1903 }
1904  
1905  
1906 package Perlito5::AST::While;
1907 {
1908 sub emit_java {
1909 my ($self, $level, $wantarray) = @_;
1910 my $cond = $self->{cond};
1911  
1912 # extract declarations from 'cond'
1913 my @str;
1914 my $old_level = $level;
1915 # print Perlito5::Dumper::Dumper($self);
1916 # print Perlito5::Dumper::Dumper($self->{cond});
1917 if ($cond) {
1918 my @var_decl = $cond->emit_java_get_decl();
1919 for my $arg (@var_decl) {
1920 $level = $old_level + 1;
1921 push @str, $arg->emit_java_init($level, $wantarray);
1922 }
1923 }
1924 my $expression = Perlito5::Java::to_native_bool($cond, $level + 1);
1925 if ($expression eq 'false') {
1926 # no-op
1927 return 'PerlOp.statement();';
1928 }
1929  
1930 if ( ref($self->{body}) eq 'Perlito5::AST::Apply' && $self->{body}{code} eq 'do' ) {
1931 # body is 'Perlito5::AST::Apply' in this construct:
1932 # do { ... } while ...;
1933 push @str,
1934 'do {',
1935 [ Perlito5::Java::LexicalBlock->new(
1936 block => $self->{body}{arguments}[0]{stmts},
1937 not_a_loop => 1,
1938 )->emit_java($level + 2, $wantarray)
1939 ],
1940 '}',
1941 'while (' . $expression . ');';
1942 }
1943 else {
1944 local $Perlito5::THROW = 0;
1945 my $body =
1946 ref($self->{body}) ne 'Perlito5::AST::Block'
1947 ? [ $self->{body} ]
1948 : $self->{body}{stmts};
1949 push @str, 'while (' . $expression . ') {',
1950 [ Perlito5::Java::LexicalBlock->new(
1951 block => $body,
1952 block_label => $self->{label},
1953 continue => $self->{continue},
1954 )->emit_java($level + 2, $wantarray)
1955 ],
1956 '}';
1957 if ($Perlito5::THROW) {
1958 @str = Perlito5::Java::emit_wrap_last_exception_java( $self, \@str, $wantarray );
1959 }
1960 }
1961  
1962 return Perlito5::Java::emit_wrap_java($level, @str);
1963 }
1964 sub emit_java_get_decl { () }
1965 sub emit_java_has_regex { () }
1966 }
1967  
1968 package Perlito5::AST::For;
1969 {
1970 sub emit_java {
1971 my ($self, $level, $wantarray) = @_;
1972 local $Perlito5::THROW = 0;
1973 my $body =
1974 ref($self->{body}) ne 'Perlito5::AST::Block'
1975 ? [ $self->{body} ]
1976 : $self->{body}{stmts};
1977  
1978 # extract declarations from 'cond'
1979 my @str;
1980 # my $old_level = $level;
1981 # print Perlito5::Dumper::Dumper($self);
1982 # print Perlito5::Dumper::Dumper($self->{cond});
1983 my $cond = ref( $self->{cond} ) eq 'ARRAY'
1984 ? $self->{cond}
1985 : [ $self->{cond} ];
1986 for my $expr ( @$cond ) {
1987 if ($expr) {
1988 my @var_decl = $expr->emit_java_get_decl();
1989 for my $arg (@var_decl) {
1990 # $level = $old_level + 1;
1991 push @str, $arg->emit_java_init($level, $wantarray);
1992 }
1993 }
1994 }
1995 # print Perlito5::Dumper::Dumper(\@str);
1996  
1997 if (ref($self->{cond}) eq 'ARRAY') {
1998 # C-style for
1999 # TODO - make continue-block a syntax error
2000 push @str,
2001 'for ( '
2002 . ( $self->{cond}[0] ? $self->{cond}[0]->emit_java($level + 1) . '; ' : '; ' )
2003 . ( $self->{cond}[1] ? Perlito5::Java::to_native_bool($self->{cond}[1], $level + 1) . '; ' : '; ' )
2004 . ( $self->{cond}[2] ? $self->{cond}[2]->emit_java($level + 1) . ' ' : '' )
2005 . ') {',
2006 [
2007 # $v->emit_java($level + 1) . ".set(item);",
2008 (Perlito5::Java::LexicalBlock->new( block => $body, block_label => $self->{label} ))->emit_java($level + 2, $wantarray),
2009 ],
2010 '}';
2011 }
2012 else {
2013 my $local_label = Perlito5::Java::get_label();
2014 my $cond = $self->{cond};
2015 my $loop_expression;
2016 my $loop_expression_is_integer = 0;
2017 if ( (ref($cond) eq 'Perlito5::AST::Apply' ) && $cond->{code} eq 'infix:<..>' ) {
2018 my ($arg1, $arg2) = @{ $cond->{arguments} };
2019  
2020 if ((ref($arg1) eq 'Perlito5::AST::Int') && (ref($arg2) eq 'Perlito5::AST::Int')) {
2021 $loop_expression_is_integer = 1;
2022 $loop_expression =
2023 'long ' . $local_label . ' = ' . $arg1->{int} . '; '
2024 . $local_label . ' <= ' . $arg2->{int} . '; '
2025 . $local_label . '++';
2026 }
2027 else {
2028 $loop_expression = 'PlObject ' . $local_label
2029 . ' : new PerlRange('
2030 . $arg1->emit_java($level + 1) . ', '
2031 . $arg2->emit_java($level + 1)
2032 . ')';
2033 }
2034 }
2035 elsif ( (ref($cond) eq 'Perlito5::AST::Apply' ) && $cond->{code} eq 'list:<,>' ) {
2036 # TODO - create an iterator over the iterators
2037 # TODO - optimization - use to_list() when the topic doesn't need to mutate
2038 #
2039 # Note: evaluate the iterator before localizing the iterator variable,
2040 # because the iterator expression may be using the variable
2041 #
2042 # example:
2043 #
2044 # for (@$_) {...}
2045 #
2046 my $expr_label = Perlito5::Java::get_label();
2047 push @str, 'PlObject ' . $expr_label . ' = ' . Perlito5::Java::to_param_list($cond->{arguments}, $level + 1) . ';';
2048 $loop_expression = 'PlObject ' . $local_label . ' : ' . $expr_label;
2049 }
2050 else {
2051 my $expr_label = Perlito5::Java::get_label();
2052 push @str, 'PlObject ' . $expr_label . ' = ' . $cond->emit_java($level + 1, 'list') . ';';
2053 $loop_expression = 'PlObject ' . $local_label . ' : ' . $expr_label;
2054 }
2055  
2056 my $decl = '';
2057 my $v = $self->{topic};
2058 if ($v->{decl}) {
2059 $decl = $v->{decl};
2060 $v = $v->{var};
2061 }
2062 else {
2063 $decl = $v->{_decl} || 'global';
2064 }
2065 my $namespace = $v->{namespace} || $v->{_namespace} || $Perlito5::PKG_NAME;
2066 my $s;
2067 if ($decl eq 'my' || $decl eq 'state' ) {
2068 # TODO - use PlObject for topic, because:
2069 # - less memory
2070 # - arguments are r/o when needed
2071 my $loop_init;
2072 if ($loop_expression_is_integer) {
2073 $loop_init = 'PlLvalue ' . $v->emit_java($level + 1) . ' = new PlLvalue(' . $local_label . ')';
2074 }
2075 else {
2076 $loop_init = 'PlLvalue ' . $v->emit_java($level + 1) . " = (PlLvalue)$local_label";
2077 }
2078 push @str,
2079 'for (' . $loop_expression . ') {',
2080 [ $loop_init . ";",
2081 Perlito5::Java::LexicalBlock->new(
2082 block => $body,
2083 block_label => $self->{label},
2084 continue => $self->{continue},
2085 )->emit_java($level + 2, $wantarray),
2086 ],
2087 '}';
2088 }
2089 else {
2090 # use global variable or $_
2091 # localize variable
2092 my $local_label2 = Perlito5::Java::get_label();
2093 my $loop_init;
2094 if ($loop_expression_is_integer) {
2095 $loop_init = $v->emit_java($level, 'scalar', 'lvalue') . '.set(' . $local_label . ')';
2096 }
2097 else {
2098 $loop_init = $v->emit_java_global_set_alias( "(PlLvalue)$local_label", $level + 1 );
2099 }
2100 push @str, 'int ' . $local_label2 . ' = PerlOp.local_length();';
2101 push @str, $v->emit_java_global($level + 1, 'scalar', 1) . ";";
2102 push @str,
2103 'for (' . $loop_expression . ') {',
2104 [ $loop_init . ";",
2105 Perlito5::Java::LexicalBlock->new(
2106 block => $body,
2107 block_label => $self->{label},
2108 continue => $self->{continue},
2109 )->emit_java($level + 2, $wantarray),
2110 ],
2111 '}';
2112 push @str, 'PerlOp.cleanup_local(' . $local_label2 . ', PlCx.UNDEF);';
2113 }
2114 }
2115 if ($Perlito5::THROW) {
2116 @str = Perlito5::Java::emit_wrap_last_exception_java( $self, \@str, $wantarray );
2117 }
2118 return Perlito5::Java::emit_wrap_java($level, @str);
2119 }
2120 sub emit_java_get_decl { () }
2121 sub emit_java_has_regex { () }
2122 }
2123  
2124 package Perlito5::AST::Sub;
2125 {
2126 sub emit_java {
2127 my ($self, $level, $wantarray) = @_;
2128 # Statevar transformation. See lib/Perlito5/Macro.pm
2129 if (my $node = $self->maybe_rewrite_statevars()) {
2130 return $node->emit_java($level, $wantarray);
2131 }
2132 local $Perlito5::THROW;
2133 local $Perlito5::THROW_RETURN if !$self->{_do_block};
2134 my $prototype = defined($self->{sig})
2135 ? 'new PlString(' . Perlito5::Java::escape_string($self->{sig}) . ')'
2136 : 'PlCx.UNDEF';
2137  
2138 my $attributes = $self->{attributes} || [];
2139 my $is_lvalue;
2140 for (@$attributes) {
2141 $is_lvalue = 1 if $_->[0] eq 'lvalue';
2142 }
2143 # warn "is_lvalue" if $is_lvalue;
2144  
2145 my $is_defined = 'true';
2146 if (!defined $self->{block}) {
2147 # this is a predeclaration
2148 $is_defined = 'false';
2149 }
2150  
2151 my $outer_sub;
2152 $outer_sub = 'this.currentSub' if $Perlito5::Java::is_inside_subroutine;
2153  
2154 my $sub_ref = Perlito5::Java::get_label();
2155 local $Perlito5::Java::is_inside_subroutine = 1;
2156 my $block = Perlito5::Java::LexicalBlock->new( block => $self->{block}{stmts}, not_a_loop => 1 );
2157  
2158 # get list of captured variables, including inner blocks
2159 my @captures_ast = (); # @Perlito5::CAPTURES;
2160  
2161 {
2162 my @captured;
2163 for my $stmt (@{$self->{block}{stmts}}) {
2164 push @captured, $stmt->get_captures();
2165 }
2166 my %dont_capture = map { $_->{dont} ? ( $_->{dont} => 1 ) : () } @captured;
2167 my %capture = map { $_->{dont} ? ()
2168 : $dont_capture{ $_->{_id} } ? ()
2169 : ($_->{_decl} eq 'local' || $_->{_decl} eq 'global' || $_->{_decl} eq '') ? ()
2170 : ( $_->{_id} => $_ )
2171 } @captured;
2172 # warn Perlito5::Dumper::Dumper(\@captured);
2173 # warn Perlito5::Dumper::Dumper(\%dont_capture);
2174 # warn Perlito5::Dumper::Dumper(\%capture);
2175  
2176 my %seen = map { $_->{_id} => 1 } @captures_ast;
2177  
2178 my @more = (
2179 grep { ! $seen{ $_->{_id} } }
2180 map { $capture{$_} }
2181 sort keys %capture );
2182 push @captures_ast, @more;
2183 }
2184  
2185 local @Perlito5::CAPTURES = @captures_ast;
2186  
2187 my @captures_java = map { $_->emit_java( $level, 'list' ) } @captures_ast;
2188  
2189 # set the new variable names inside the closure
2190 local %Perlito5::Java::Java_var_name;
2191 my $i = 0;
2192 for (@captures_ast) {
2193 my $capture_name = 'this.env[' . $i . ']';
2194 my $sigil = $_->{_real_sigil} || $_->{sigil};
2195 if ($sigil eq '$') {
2196 $capture_name = "((PlLvalue)$capture_name)";
2197 }
2198 elsif ($sigil eq '@') {
2199 $capture_name = "((PlArray)$capture_name)";
2200 }
2201 elsif ($sigil eq '%') {
2202 $capture_name = "((PlHash)$capture_name)";
2203 }
2204 $Perlito5::Java::Java_var_name{ $_->{_id} } = $capture_name;
2205 $i++;
2206 }
2207  
2208 my @js_block;
2209 if ($self->{_do_block}) {
2210 # do-block
2211 local $Perlito5::JAVA_CAN_RETURN = 0;
2212 @js_block = $block->emit_java( $level + 3, 'runtime' );
2213 }
2214 elsif ($self->{_eval_block}) {
2215 # eval-block
2216 $block->{top_level} = 1;
2217 $block->{eval_block} = 1;
2218 local $Perlito5::JAVA_CAN_RETURN = 1;
2219 @js_block = $block->emit_java( $level + 3, 'runtime' ),
2220 }
2221 else {
2222 local $Perlito5::JAVA_CAN_RETURN = 1;
2223 $block->{top_level} = 1;
2224 @js_block = $block->emit_java( $level + 3, 'runtime' );
2225 }
2226  
2227 if (!@js_block) {
2228 push @js_block, 'return PerlOp.context(want);';
2229 }
2230  
2231 my $captures = 'null';
2232 if (@captures_java) {
2233 $captures = "new PlObject[]{ " . join(', ', @captures_java) . " }";
2234 }
2235  
2236 my @closure_args = (
2237 $prototype,
2238 $captures,
2239 Perlito5::Java::pkg,
2240 $is_defined,
2241 );
2242 if (($self->{_do_block} || $self->{_eval_block}) && $outer_sub) {
2243 push @closure_args, $outer_sub;
2244 }
2245  
2246 my @perl_pos;
2247 if ($self->{pos}) {
2248 @perl_pos = (
2249 "public String perlFileName() {",
2250 [ "return " . Perlito5::Java::escape_string( $self->{pos}{file} ) . ";",
2251 ],
2252 "}",
2253 "public Integer perlLineNumber() {",
2254 [ "return " . (0 + $self->{pos}{line}) . ";",
2255 ],
2256 "}",
2257 );
2258 }
2259  
2260 my $method_decl;
2261 if ($self->{_do_block}) {
2262 $method_decl = "public PlObject apply_do_block(int want, int return_context, PlArray List__)";
2263 }
2264 else {
2265 $method_decl = "public PlObject apply(int want, PlArray List__)";
2266 unshift @js_block, "int return_context = want;";
2267 }
2268  
2269 my @s = (
2270 "new PlClosure(" . join( ", ", @closure_args ) . ") {",
2271 [
2272 @perl_pos,
2273 "public StackTraceElement firstLine() {",
2274 [ "return PlCx.mainThread.getStackTrace()[1];",
2275 ],
2276 "}",
2277 '@SuppressWarnings("unchecked")',
2278 $method_decl . " {",
2279 [ @js_block ],
2280 "}",
2281 "public StackTraceElement lastLine() {",
2282 [ "return PlCx.mainThread.getStackTrace()[1];",
2283 ],
2284 "}",
2285 ],
2286 "}",
2287 );
2288  
2289 if ( $self->{name} ) {
2290 return Perlito5::Java::emit_wrap_java($level,
2291 'PlV.cset(',
2292 [ Perlito5::Java::escape_string( $self->{namespace} . '::' . $self->{name} ) . ",",
2293 @s,
2294 ],
2295 ');',
2296 );
2297 }
2298 else {
2299 return "" . Perlito5::Java::emit_wrap_java($level, @s);
2300 }
2301  
2302 # PlClosure c = new PlClosure( "", new PlObject[]{ v1, v2, v3 } ) {
2303 # public PerlitoObject apply( context, args ) {
2304 # System.out.println("called MyClosure with " + this.env[2].toString());
2305 # return new PerlitoInt(0);
2306 # }
2307 # };
2308 # c.apply( context, args );
2309  
2310 }
2311 sub emit_java_get_decl { () }
2312 sub emit_java_has_regex { () }
2313 }
2314  
2315 1;
2316  
2317 =begin
2318  
2319 =head1 NAME
2320  
2321 Perlito5::Java::Emit - Code generator for Perlito Perl5-in-Java
2322  
2323 =head1 SYNOPSIS
2324  
2325 $ast->emit_java($level) # generated Perl5 code
2326  
2327 =head1 DESCRIPTION
2328  
2329 This module generates Java code for the Perlito compiler.
2330  
2331 =head1 AUTHORS
2332  
2333 Flavio Soibelmann Glock <fglock@gmail.com>.
2334 The Pugs Team.
2335  
2336 =head1 COPYRIGHT
2337  
2338 Copyright 2006, 2009, 2011, 2012 by Flavio Soibelmann Glock, Audrey Tang and others.
2339  
2340 This program is free software; you can redistribute it and/or modify it
2341 under the same terms as Perl itself.
2342  
2343 See L<http://www.perl.com/perl/misc/Artistic.html>
2344  
2345 =end