JE/toperl.pl untested

filter: Statementstmt 0.0% 0 / 317 Branchbran 0.0% 0 / 288 Conditioncond 0.0% 0 / 55 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 722 CC 145 SCAR 77.1
CC
145
Cov
0%
JE::Code::Statement::to_perl
2756.0
_term_to_perl
2756.0
JE::Code::Expression::to_perl
1806.0
CRAP 2237.8
1 package JE::Code;
2  
3 use strict;
4 use warnings; no warnings qw 'utf8 parenthesis';
5  
6 use constant 1.03 our $_const = do {
7 my $x = 0;
8 +{ map +($_ => $x++),
9 'cx_stm', # statement
10 'cx_void', # statement; retval ignored
11  
12 # expression contexts
13 'cx_void_expr',
14 'cx_any', # includes lvalue
15 'cx_rv', # rvalue
16 'cx_lv', # lvalue
17 'cx_bool', # plain boolean, not necessarily a JE::Boolean
18 'cx_str', # Perl scalar in UTF-16 (with surrogates)
19 'cx_num', # Perl scalar
20  
21 'ret_void', # no retval
22 'ret_maybe', # might have a retval (which could be an lval)
23 'ret_break', # break or continue
24 'ret_any', # includes lvalue
25 'ret_lv',
26 'ret_rv',
27 'ret_str',
28 'ret_num',
29 'ret_bool',
30 }
31 };
32 BEGIN { no strict; delete @{__PACKAGE__."::"}{_const => keys %$_const} }
33  
34 =begin notes
35  
36 The cx_stm constant for statement-level context applies to a context in
37 which any return type (including an lvalue) is expected, but an lvalue has
38 to have ->get called on it before it is returned.
39  
40 The to_perl methods take 1 argument, a cx_ constant, and return 2 or 3:
41 0. ret_ constant indicating possible return types
42 1. string of Perl code
43 ( 2. alternate string of Perl code that can be used only in some
44 contexts, such as "..." for JE::String->new(...) )
45  
46 The reason we have all those return values is most easily demonstrated by
47 example:
48  
49 For the + operator, we have two completely different behaviours, depending
50 on the types of the operands. If an operand can only be a string, we get:
51  
52 ret_str, 'JE::String->new($global, "...")', '"..."'
53  
54 If we see one of those, we can stringify the other operand, returning code
55 like this:
56  
57 "..." . [other operand]->to_string->value16
58  
59 We need to_perl’s second retval, for cases like - :
60  
61 [str operand]->to_number->value - [num operand]
62
63  
64 =end notes
65  
66 =cut
67  
68 sub _esc_str($) {
69 my $str = shift;
70 $str =~ s/(['\\])/\\$1/g;
71 "'$str'";
72 }
73  
74 our %labels;
75 our %loop_labels;
76 our $cache_indx;
77 our $code;
78  
79 no warnings 'redefine';
80 sub optimise {
81 my $self = shift;
82 local %labels; local %loop_labels; local $cache_indx;
83 local $code = $self;
84 my $global = $self->{global};
85 $self->set_global(undef);
86 $self->{psrc} = 'no warnings"utf8","exiting";'
87 . $self->{tree}->to_perl(cx_stm);
88 $self->{tree}=[$self->{tree}[0]];
89 $self->set_global($global);
90 }
91  
92 use Scalar::Util 'refaddr';
93  
94 sub JE::Code::Statement::to_perl {
95 my $stm = shift;
96 my $cx = shift;
97  
98 my $type = $$stm[1];
99 $type eq 'empty' and return ret_void, '';
100  
101 if($type eq 'function' ) {
102 (my $new_code_obj = bless {
103 map+($_=>$code->{$_}),qw/global source file line/
104 }, 'JE::Code')
105 ->{tree} = $$_[4];
106 $new_code_obj->{vars} = $$_[5];
107 $new_code_obj->optimise;
108 $$stm[4] = $new_code_obj;
109 return ret_void, '';
110 }
111  
112 my $pos = $$stm[0][0];
113  
114 if ($type eq 'labelled') {
115 my @labels = @$stm[2..$#$stm-1];
116  
117 my $is_loop =
118 $$stm[-1][1] =~ /^(?:do|while|for|switch)\z/;
119  
120 # We have to alias the labels to a single label, because
121 # Perl does not support multiple labels on a sin-
122 # gle statement. Nor can we stack them up with
123 # blocks, ( foo:{bar:{...}} ) because that won’t work
124 # for loop-control constructs (next foo). We have
125 # to rename them, since JS idents can have $ in them.
126 my $alias_to = refaddr $stm->[-1];
127 local @labels{@labels} = ($alias_to)x@labels;
128  
129 # ‘continue’ statements only look in this hash:
130 local @loop_labels{@labels} = ($alias_to)x@labels
131 if $is_loop;
132  
133 my($rettype,$code) = $$stm[-1]->to_perl($cx);
134 return
135 $rettype,
136 # loops add their own label, since some have to put
137 # something before it
138 $is_loop ? $code :
139 "JE_Code_$alias_to:" . (
140 $$stm[-1][1] =~ /^{/
141 ? $code
142 : length $code ? "{$code}" : '{;}'
143 ); # Without the ; it’s a hash.
144 }
145  
146 if ($type eq 'statements') {
147  
148 # At run time, the statements are executed one by one, and
149 # the return value of the last statement that actually
150 # returned one is returned. To avoid passing cx_stm context
151 # when cx_void will do, we work backwards.
152 # ~~~ This logic is currently flawed. It needs to account
153 # for a ‘break’ or similar in between two ret_any stms.
154 # And also ‘return’ satetments.
155  
156 my @code; my $last_rettype;
157 for (@$stm[reverse 2..$#$stm]) {
158 my($rettype,$code) = $_->to_perl($cx);
159 $last_rettype = $rettype;
160 push @code, $code;
161 if($rettype != ret_void && $rettype != ret_maybe) {
162 $cx = cx_void
163 }
164 }
165 my $code = join '', reverse @code;
166 # $rettype will be undefined if this is an empty block
167 return defined $last_rettype?$last_rettype:ret_void, $code;
168 }
169 if ($type eq 'var') {
170 # The Perl code looks like this:
171 # $scope->find_var("foo")->set( ...expr... );
172  
173 my $stm_code = '';
174 for (@$stm[2..$#$stm]) { if (@$_ == 2) {
175  
176 my($rettype,$code) = _term_to_perl($$_[1],cx_rv);
177 $stm_code .=
178 '$scope->find_var(' . _esc_str($$_[0]) .')->set('
179 . $code . ");";
180 }}
181 return ret_void, $stm_code;
182 }
183 if ($type eq 'if') {
184 # 2 3 4
185 # we have: expr statement statement?
186  
187 my($rettype,$code) = $$stm[2]->to_perl(cx_bool);
188 my $stm_code = "if($code){";
189  
190 ($rettype,$code) = $$stm[3]->to_perl($cx);
191 $stm_code .= "$code}";
192  
193 my $rettype2;
194 if(exists $$stm[4]) {
195 ($rettype2,$code) = $$stm[4]->to_perl($cx);
196 $stm_code .= "else{$code}"
197 }
198 return $cx == cx_void ? ret_void
199 : (defined $rettype2 ? $rettype2 == ret_void : 1)
200 && $rettype == ret_void
201 ? ret_void
202 : ret_maybe,
203 $stm_code
204 }
205 if ($type =~ /^(?:do|while|for|switch)\z/) {
206 # We have one of the following:
207 #
208 # 1 2 3 4 5
209 # 'do' statement expression
210 # 'while' expression statement
211 # 'for' expression 'in' expression statement
212 # 'for' var_decl 'in' expression statement
213 # 'for' expression expression expression statement
214 # 'for' var_decl expression expression statement
215 #
216 # In those last two cases, expression may be 'empty'.
217 # (See further down for 'switch').
218  
219 my $label = refaddr $stm;
220 my $stm_code = "JE_Code_$label:";
221  
222 # Alias for simple break/continue statements with-
223 # out a label:
224 local $labels{''} = local $loop_labels{''} = $label;
225  
226 if ($type eq 'do') {
227 # For a do statement we need two loop labels:
228 # outer: {
229 # do { inner: {
230 #
231 # }} while foo
232 # }
233 # continue statements use the inner label.
234  
235 # In case there are aliases to the existing label:
236 my @js_labels = grep $labels{$_} == $label =>=>
237 keys %loop_labels;
238 local @loop_labels{'',@js_labels} =
239 ($label.'c')x(@js_labels+1);
240  
241 my($rettype,$code) = $$stm[2]->to_perl($cx);
242 my(undef,$boolcode)
243 = $$stm[3]->to_perl(cx_bool);
244 return $rettype,
245 "$stm_code\{do{JE_Code_${label}c:{" .
246 (length $code ? $code : ';') # foo:{} is a hash
247 ."}}while "
248 . "$boolcode}";
249 }
250 elsif ($type eq 'while') {
251 my(undef,$boolcode)
252 = $$stm[2]->to_perl(cx_bool);
253 my($rettype,$code) = $$stm[3]->to_perl($cx);
254 return $rettype,
255 "${stm_code}while($boolcode){$code}";
256 }
257 elsif ($type eq 'for' and $$stm[3] eq 'in') {
258 # for(var i = 3 in ...) {
259 # break;
260 # }
261 # translates into
262 # $scope->find_var('i')->set(3);
263 # JE_Code_loop: for((my $o = ...)->keys) {
264 # next if not defined $o->prop($_);
265 # # in which case it's been deleted
266 # $scope->find_var('i')->set($_);
267 # last JE_Code_loop;
268 # }
269 # (except that the arguments to ->set() have to be
270 # expressions returning JE::(Number|String)). For
271 # statements without the ‘var’, we don’t evaluate
272 # the lhs before the loop, but only in the loop. It
273 # takes the place of $scope->find_var.
274  
275 my $left_side = $$stm[2];
276 if ($left_side->[1] eq 'var') {
277 substr $stm_code,0,0 =>=
278 ($left_side->to_perl(cx_void))[1];
279 $left_side = _esc_str($left_side->[2][0]);
280 # now contains the identifier within a
281 # Perl string
282 }
283  
284 (undef,my $obj_code) = $$stm[4]->to_perl(cx_rv);
285 $stm_code .=
286 "for((my\$o=$obj_code)->keys){" .
287 'next if!defined prop$o $_;' .
288
289 ( ref $left_side
290 ? ( $left_side->to_perl(cx_lv) )[1]
291 : "\$scope->find_var($left_side)" ) .
292 '->set(_new JE\'String $global,$_);';
293  
294 my($rettype, $code) = $$stm[5]->to_perl($cx);
295  
296 return $rettype, "$stm_code$code}";
297 }
298 elsif ($type eq 'for') { # for(;;)
299 $stm_code .= 'for(';
300 if(ref $$stm[2]) {
301 my $code = ($$stm[2]->to_perl(cx_void))[1];
302 length $code and $stm_code .=
303 "do{$code}" # We need the do
304 } # because to_perl
305 $stm_code .= ';'; # returns whole
306 if(ref $$stm[3]) { # statements
307 my(undef,$code) =
308 $$stm[3]->to_perl(cx_bool);
309 $stm_code .= $code;
310 }
311 $stm_code .= ';';
312  
313 ref $$stm[4] and $stm_code .=
314 ( $$stm[4]->to_perl(cx_void_expr) )[1];
315
316 my($rettype, $code) = $$stm[5]->to_perl($cx);
317 return $rettype, "$stm_code){$code}";
318 }
319 else { # switch
320 # $stm->[2] is the parenthesized
321 # expression.
322 # Each pair of elements thereafter
323 # represents one case clause, an expr
324 # followed by statements, except for
325 # the default clause, which has the
326 # string 'default' for its first elem
327  
328 # We need to turn something like
329 # switch(3) {
330 # case 5: a();
331 # default: f();
332 # case 3636:
333 # case 838: break;
334 # case 3: h();
335 # }
336 # into
337 # JE_Code_loop: for(3) {
338 # $_->id eq 5->id and goto JE_Code_case1;
339 # $_->id eq 3636->id and goto JE_Code_case2;
340 # $_->id eq 838->id and goto JE_Code_case3;
341 # $_->id eq 3->id and goto JE_Code_case4;
342 # goto JE_Code_default;
343 # JE_Code_case1: $scope->find_var('a')->call;
344 # JE_Code_default: $scope->find_var('f')->call;
345 # JE_Code_case2: ;
346 # JE_Code_case3: last JE_Code_loop;
347 # JE_Code_case4: $scope->find_var('f')->call;
348 # }
349 # (except that the expressions are more complex).
350
351 # header
352 $stm_code .= 'for(' .
353 ( $$stm[2]->to_perl(cx_rv) )[1] . '){';
354
355 # Go through the case clauses and add goto state-
356 # ments to $stm_code while also creating the state-
357 # ments that go further down.
358  
359 my $more_statements = '';
360 my($n, $there_is_a_default) = 1;
361 while (($n+=2) < @$stm) {
362 if($$stm[$n] eq 'default') {
363 $more_statements .=
364 'JE_Code_default:';
365 ++ $there_is_a_default
366 }
367 else {
368 $stm_code .= 'id$_ eq ' .
369 ($$stm[$n]->to_perl(cx_rv))[1] .
370 "->id&&goto JE_Code_case$n;";
371 $more_statements.="JE_Code_case$n:"
372 }
373 my $stm = ( $$stm[$n+1]->to_perl($cx) )[1];
374 $more_statements .= length $stm?$stm:';' ;
375 } ;
376  
377 return $cx==ret_void ? ret_void : ret_maybe, # ~~~ need to do some detecting
378 # for the rettype
379 $stm_code . (
380 $there_is_a_default
381 ? 'goto JE_Code_default' : 'last'
382 ) . ";$more_statements}"
383 } # switch
384 }
385 if ($type eq 'continue') {
386 my $label = exists $$stm[2] ? $$stm[2] : '';
387 return ret_break, exists $loop_labels{$label}
388 ? "next JE_Code_$loop_labels{$label};"
389 : "die q[continue $label: label '$label' not found];"
390 }
391 if ($type eq 'break') {
392 my $label = exists $$stm[2] ? $$stm[2] : '';
393 return ret_break, exists $labels{$label}
394 ? "last JE_Code_$labels{$label};"
395 : "die q[break $label: label '$label' not found];"
396 }
397 if ($type eq 'return') {
398 return ret_any, '$return=' . ( exists $$stm[2]
399 ? ($$stm[2]->to_perl(cx_rv))[1]
400 : 'undef'
401 ) . ';last RETURN;' ;
402 }
403 if ($type eq 'with') {
404 my($rettype, $code) = $$stm[3]->to_perl($cx);
405 return $rettype,
406 '{local$scope=bless[@$scope,'
407 . ($$stm[2]->to_perl(cx_rv))[1]
408 . "->to_object],'JE::Scope';$code}";
409 }
410 if ($type eq 'throw') {
411 return ret_void,'die '.($$stm[2]->to_perl(cx_rv))[1]. ';' ;
412 }
413 if ($type eq 'try') {
414 # We have one of the following:
415 # 1 2 3 4 5
416 # 'try' block ident block (catch)
417 # 'try' block block (finally)
418 # 'try' block ident block block (catch & finally)
419  
420 # For a try-catch, we can simply use eval{...;1}||do{...}.
421 # With finally, it’s a lot more complicated. We can’t use
422 # Scope::Guard, because a destructor can’t affect execution
423 # flow. So we have to set up a complicated net to catch
424 # every return/break/continue in addition to exceptions.
425 # For every unique value in %labels, we need a separate
426 # block. What we end up with is something like this:
427  
428 # ~~~(The inner do{} is actually redundant. Maybe I should
429 # refactor it a bit.)
430  
431 # { # lexical scope for all these variables:
432 # my $l; #label
433 # my $e; #exception
434 # my $c; #continue
435 # eval {
436 # JE_Code_labels: {
437 # RETURN: {
438 # JE_Code_1: for(0,1){ $_ and ++$c, last;
439 # JE_Code_2: for(0,1){ $_ and ++$c, last;
440 # JE_Code_3: for(0,1){ $_ and ++$c, last;
441 # my $r = $return;
442 # eval { ... try ...; last JE_Code_labels };
443 # ... catch ...;
444 # last JE_Code_labels;
445 # } $l = 3, last JE_Code_labels
446 # } $l = 2, last JE_Code_labels
447 # } $l = 1, last JE_Code_labels
448 # } $l = 'r'
449 # }
450 # 1
451 # } or $e=$@;
452 # my $r = $return;
453 # ... finally ...
454 # defined $e && die $e;
455 # $return = $r;
456 # $l and $l == 'r' ? last RETURN :
457 # $c ? next "JE_Code_$l" : last "JE_Code_$l"
458 # }
459  
460 # A catch’s do-block (this is not in a do when there is a
461 # finally) is as follows:
462 # do {
463 # $return = $r;
464 # ref $@ or $@ = _objectify_error($@);
465 # (my $o = new JE::Object $global)
466 # ->prop({
467 # name => 'e',
468 # value => $@,
469 # dontdel => 1,
470 # });
471 # local $scope = bless [
472 # @$scope, $o
473 # ], 'JE::Scope';
474 # ...code...
475 # };
476  
477 # Got that?
478  
479  
480 my $finally = $#$stm == 3 || $#$stm == 5;
481  
482 # try and catch
483  
484 my $inner_code = '';
485
486 # We don’t want try{3; throw...} to return 3, so we save
487 # the previous value of $return before entering the eval.
488  
489 my $we_can_catch = !ref $$stm[3];
490 $inner_code .= 'my$r=$return;eval{' if $we_can_catch;
491 my($rettype,$code) = $$stm[2]->to_perl($cx); # try
492 $inner_code .= $code;
493 $inner_code .= 'last JE_Code_labels;' if $finally;
494 if($we_can_catch) {
495 $inner_code .= ($finally ? '};' : '1}||do{')
496  
497 . '$return=$r;' # prevent { 3; throw ... }
498 # from returning 3
499 # Turn miscellaneous errors into
500 # Error objects
501 .q"ref$@or$@=_objectify_error($@);"
502  
503 .q"(my$o=new JE'Object $global)->prop({"
504 . 'name=>' . _esc_str($$stm[3]) . ','
505 . 'value=>$@,'
506 . 'dontdel=>1'
507 .'});'
508 .'local$scope='
509 . 'bless[@$scope,$o],"JE::Scope";';
510  
511 my($rettype, $code) = $$stm[4]->to_perl($cx);
512 $inner_code .= $code
513 . ($finally ? ';last JE_Code_labels' : '}');
514 }
515  
516 if ($finally) {
517 # get a list of labels
518 my @labels; my %seen;
519  
520 for(values %labels, values %loop_labels) {
521 push @labels, $_ unless $seen{$_}++
522 }
523  
524 my $stm_code =
525 '{'
526 . 'my($l,$e,$c);'
527 . 'eval{'
528 . 'JE_Code_labels:{'
529 . 'RETURN:{';
530  
531 $stm_code .=
532 "JE_Code_$_:for(0,1){\$_ and++\$c,last;",
533 for @labels;
534  
535 $stm_code .= $inner_code;
536  
537 $stm_code .=
538 '}$l='._esc_str($_).",last JE_Code_labels"
539 for reverse @labels;
540  
541 $stm_code .=
542 '}$l="r"'
543 . '}'
544 . '1'
545 . '}or$e=$@;'
546 . 'my$r=$return;'
547 . ( $$stm[-1]->to_perl(cx_void) )[1]
548 . 'defined$e&&die$e;'
549 . '$return=$r;'
550 . '$l and$l eq"r"?last RETURN:'
551 . '$c?eval"next JE_Code_$l"'
552 . ':eval"last JE_Code_$l"'
553 .'}';
554  
555 return $cx==ret_void ? ret_void : ret_maybe,
556 $stm_code;
557 }
558 else {
559 return $cx==ret_void ? ret_void : ret_maybe,
560 $we_can_catch ? "{$inner_code}" :
561 $inner_code;
562 }
563 # ~~~ need to do some detecting for the rettype
564  
565 }
566 }
567  
568  
569  
570 =begin for-me
571  
572 Types of expressions:
573  
574 'new' term args?
575  
576 'member/call' term ( subscript | args) *
577  
578 'postfix' term op
579  
580 'hash' term*
581  
582 'array' term? (comma term?)*
583  
584 'prefix' op+ term
585  
586 'lassoc' term (op term)*
587  
588 'assign' term (op term)* (term term)?
589 (the last two terms are the 2nd and 3rd terms of ? :
590  
591 'expr' term*
592 (commas are omitted from the array)
593  
594 'function' ident? params statements
595  
596 =end for-me
597  
598 =cut
599  
600  
601 # Note: each expression object is an array ref. The elems are:
602 # [0] - an array ref containing
603 # [0] - the starting position in the source code and
604 # [1] - the ending position
605 # [1] - the type of expression
606 # [2..$#] - the various terms/tokens that make up the expr
607  
608 sub JE::Code::Expression::to_perl {
609
610 #ret_rv, "hooha()" . ';' x ($_[1] == cx_stm || $_[1] == cx_void)
611  
612 # ~~~ ++ $ops>$counting and last JE_Code_OP if $counting;
613
614 my $expr = shift;
615 my $cx = shift;
616  
617 my $type = $$expr[1];
618  
619 # ~~~ $pos = $$expr[0][0];
620  
621 if ($type eq 'expr') {
622 my $sc = '';
623 $cx == cx_stm
624 ? ($sc = ';', $cx = cx_any) :
625 $cx == cx_void && ($sc = ';', $cx = cx_void_expr);
626  
627 if(@$expr == 3) { # no comma
628 my($rettype,$code) =
629 _term_to_perl($$expr[-1], $cx);
630 if($rettype == ret_lv && $sc) {
631 $code =
632 "{my\$v=$code;\$v->get;\$return=\$v}";
633 }elsif($rettype==ret_any && $sc){
634 $code = "{my\$v=$code;"
635 . 'ref$v eq"JE::LValue"&&$v->get'
636 . ';$return=$v'
637 .'}';
638 }
639 elsif($sc) {
640 $code = "\$return=$code;"
641 }
642 return $rettype, $code;
643 }
644 else { # comma op
645 my $result = join ',', map+
646 (_term_to_perl($_, cx_void_expr))[1],
647 @$expr[2..$#$expr-1];
648 $result .= ',';
649  
650 my($rettype,$code) =
651 _term_to_perl($$expr[-1], ret_rv);
652 $result .= $code;
653 if($sc) {
654 $result = "\$return=($result);";
655 }
656 else {
657 $result = "scalar($result)";
658 }
659  
660 return $cx == cx_void_expr ? ret_void : $rettype,
661 $result;
662 }
663 }
664 if ($type eq 'assign') {
665 my @copy = @$expr[2..$#$expr];
666 # Evaluation is done left-first in JS, unlike in
667 # Perl, so a = b = c is evaluated in this order:
668 # - evaluate a
669 # - evaluate b
670 # - evaluate c
671 # - assign c to b
672 # - assign b to a
673  
674 # Check first to see whether we have the terms
675 # of a ? : at the end:
676 my @qc_terms = @copy >= 3 && (
677 ref $copy[-2] # avoid stringification
678 || $copy[-2] =~ /^(?:[tfu]\z|[si0-9])/
679 )
680 ? (pop @copy, pop @copy) : ();
681 # @qc_terms is now in reverse order
682  
683 # Rough sketch of what we want to accomplish:
684  
685 # a += b += c += d
686 #
687 # do {
688 # my $l = a;
689 # $l->set($l->get + do{
690 # my $l = b;
691 # $l->set($l->get + do {
692 # my $l = c;
693 # $l->set($l->get + d)
694 # })
695 # })
696 # }
697  
698 # a = b
699 #
700 # a->set(b->get)
701  
702 # a += b = c
703 #
704 # do {
705 # my $l = a;
706 # $l->set($l->get + b->set(my $v = c))
707 # }
708  
709 # Get the first rhs ready:
710  
711 my $perl_expr = pop @copy;
712  
713 # Now apply ? : if it's there
714 if(@qc_terms) {
715 $perl_expr = (_term_to_perl($perl_expr,cx_bool))[1]
716 . '?' . (_term_to_perl($qc_terms[1],cx_rv))[1]
717 . ':' . (_term_to_perl($qc_terms[0],cx_rv))[1]
718 }
719 else {
720 $perl_expr = (_term_to_perl($perl_expr,cx_rv))[1];
721 }
722  
723 # short-circuit if we only have ? : and no assignment
724 # ~~~ check return types from both legs
725 return ret_rv, $perl_expr unless @copy;
726  
727 # Iterate through the ops, wrapping each previous expr with
728 # the current one.
729 while(@copy) {
730 my ($op, $term) = (pop @copy, pop @copy);
731 if(length $op > 1) {
732 $perl_expr = 'do{my$l='
733 . (_term_to_perl($term,cx_lv))[1] . ';'
734 . '$l->set('
735 . "'JE::Code::Expression::in".substr $op,0,-1,
736 . "'->(\$l->get,$perl_expr))}"
737 }
738 else {
739 $perl_expr =
740 (_term_to_perl($term,cx_lv))[1]
741 . "->set($perl_expr)"
742 }
743 }
744  
745 # ~~~ T and tainted $taint and $val->can('taint')
746 # and $val = taint $val $taint;
747  
748 return ret_rv, $perl_expr;
749 }
750 if($type eq 'lassoc') { # left-associative
751 my @copy = @$expr[2..$#$expr];
752 my $result = (_term_to_perl(shift @copy, cx_rv))[1];
753 while(@copy) {
754 # We have to deal with || && specially for the sake
755 # of short-circuiting
756 my $op = $copy[0];
757 if ($op =~ m&^(?:\&\&|\|\|)\z&) {
758 $result =
759 "$result$op "
760 .(_term_to_perl($copy[1],cx_rv))[1]
761 }
762 else {
763 $result = "'JE::Code::Expression::in$op'->"
764 . "($result,"
765 .(_term_to_perl($copy[1],cx_rv))[1]
766 .')'
767 }
768 splice @copy, 0, 2; # double shift
769 }
770 return ret_rv,$result;
771 }
772 if ($type eq 'prefix') {
773 # ~~~ taintedness
774 # $$expr[1] -- 'prefix'
775 # @$expr[2..-2] -- prefix ops
776 # $$expr[-1] -- operand
777 my $term = (
778 _term_to_perl( $$expr[-1],
779 $$expr[-2] =~ m-^(?:\+\+|\-\-)\z- ? cx_lv :
780 $$expr[-2] =~ m e^(?:typ\eof|d\el\et\e)\ze ? cx_any :
781 cx_rv
782 )
783 )[1];
784  
785 $term = "'JE::Code::Expression::pre$_'->($term)"
786 for reverse @$expr[2..@$expr-2];
787 return ret_rv, $term;
788 }
789 if ($type eq 'postfix') {
790 # ~~~ taintedness
791 # ~~~ These are supposed to use the same rules
792 # as the + and - infix ops for the actual
793 # addition part. Verify that they do this.
794  
795 # This will need to be made more efficient:
796 # do{
797 # my $l = ...; $l->set(
798 # "JE::Code::Expression::in+"->(
799 # $l->get,
800 # JE::Number->new($global, 1)
801 # )
802 # );
803 # $v
804 # }
805  
806 return ret_rv, 'do{'
807 . 'my$l=' . (_term_to_perl($$expr[2], cx_lv))[1] . ';'
808 . '$l->set('
809 . '"JE::Code::Expression::in+"->('
810 . 'my$v=$l->get->to_number,'
811 . _cached('JE\'Number->new($global,'
812 . (-1,1)[$$expr[3] eq '++']. ')')
813 . ')'
814 . ')'
815 . ';$v' x ($cx != cx_void_expr)
816 .'}'
817 }
818 if ($type eq 'new') {
819 # ~~~ ? T && tainted $taint
820 #~~~ ? map $_->can('taint') ?taint $_ $taint:$_,
821 return ret_rv, (_term_to_perl($$expr[2],cx_rv))[1]
822 .'->construct'
823 . ( @$expr == 4
824 ? '(' . $$expr[-1]->to_perl . ')'
825 : '' )
826 }
827 if($type eq 'member/call') {
828 my($type, $obj) = _term_to_perl( $$expr[2],
829 exists $$expr[3]
830 ? ref $$expr[3]eq 'JE::Code::Subscript'
831 ? cx_rv
832 : cx_any
833 : $cx
834 );
835 # ~~~ We can probably optimise this not to create LValue objects for calls,
836 # but use the ‘apply’ method directly.
837 for (3..$#$expr) {
838 my $cx = exists $$expr[$_+1]
839 ? ref $$expr[$_+1]eq 'JE::Code::Subscript'
840 ? cx_rv
841 : cx_any
842 : $cx;
843 if(ref $$expr[$_] eq 'JE::Code::Subscript') {
844 if($cx != cx_lv && $cx != cx_any) {
845 $obj .= '->prop('
846 . $$expr[$_]->to_perl
847 .')';
848 if($cx == cx_void_expr) {
849 $type = ret_void
850 } else {
851 $obj = "do{my\$v=$obj;"
852 . 'defined$v?$v:$global->undefined}';
853 $type = ret_rv;
854 }
855 }
856 else {
857 $obj = "JE'LValue->new($obj,"
858 . $$expr[$_]->to_perl . ')';
859 $type = ret_lv
860 }
861 }
862 else {
863 # ~~~ taintedness for calls
864 if($cx != cx_lv && $cx != cx_any) {
865 $obj = 'do{'
866 . "my\$v=$obj->call("
867 . $$expr[$_]->to_perl
868 . ');'
869 . 'ref$v eq"JE::LValue"' . (
870 $cx==cx_void_expr
871 ?'&&$v->get'
872 :'?$v->get:$v'
873 )
874 .'}';
875 $type = ret_rv;
876 }
877 else {
878 $obj = "$obj->call("
879 . $$expr[$_]->to_perl
880 .')';
881 $type = ret_any
882 }
883 # If $obj is an lvalue,
884 # JE::LValue::call will make
885 # the lvalue's base object the 'this'
886 # value. Otherwise,
887 # JE::Object::Function::call
888 # will make the
889 # global object the 'this' value.
890 }
891 # ~~~ need some error-checking
892 }
893 return $type, $obj; # which may be an lvalue
894 }
895 if($type eq 'array') {
896 if($#$expr < 2) {
897 return ret_rv, "JE'Object'Array->new(\$global)"
898 }
899 my @ary;
900 for (2..$#$expr) {
901 if(ref $$expr[$_] eq 'comma') {
902 ref $$expr[$_-1] eq 'comma' || $_ == 2
903 and push @ary, 'undef';
904 }
905 else {
906 push @ary,
907 (_term_to_perl( $$expr[$_], cx_rv ))[1];
908 }
909 }
910  
911 return ret_rv, 'do{my$a=new JE\'Object\'Array $global;'
912 . '$$$a{array}=[' . join(',',@ary) . '];$a}'
913 # sticking it in like that
914 # makes 'undef' elements non-
915 # existent, rather
916 # than undefined
917 }
918 if($type eq 'hash') {
919 local @_ = @$expr[2..$#$expr];
920 if(!@_) { return ret_rv, "JE'Object->new(\$global)"; }
921 my $obj = 'do{my$o=new JE\'Object $global;';
922 my ($key, $value);
923 while(@_) { # I have to loop through them to keep
924 # the order.
925 $key = _esc_str(shift);
926 $value = (_term_to_perl( shift, cx_rv ))[1];
927 $obj .= "\$o->prop($key,$value);";
928 }
929 return ret_rv, $obj . '$o}';
930 }
931 if ($type eq 'func') {
932 # format: [[...], function=> 'name',
933 # [ params ], $statements_obj, \@vars]
934 # or: [[...], function =>
935 # [ params ], $statements_obj, \@vars]
936  
937 # The code we need to produce will be like this:
938 # e.g.: function(foo){ bar }
939 # JE'Object'Function->new({
940 # scope=>$scope,
941 # argnames=>['foo'],
942 # function=>$$cache[0],
943 # })
944 # If there is a name (function x (){}), it’s a little
945 # more complex:
946 # do{
947 # my $f = JE'Object'Function->new({
948 # name => 'x',
949 # scope =>[@$scope, my $o = new JE::Object $global],
950 # ... argnames and function ...
951 # });
952 # $o->prop({ name => 'x', value => $f,
953 # readonly => 1, dontdel => 1 });
954 # $f
955 # }
956 # The code object has to be created beforehand and placed
957 # in the cache.
958 # ~~~ When we merge this with JE::Parser, the entire code
959 # for the code object can be placed in a
960 # $$cache[0]||=....
961  
962 my($name,$params,$statements) = ref $$expr[2] ?
963 (undef, @$expr[2,3]) : @$expr[2..4];
964 my $ret; my $scope;
965 if($name) {
966 $name = _esc_str($name);
967 $ret = 'do{my$f=';
968 # ~~~ I should be able to remove this ‘bless’. See
969 # the comment in jE::Object::Function::New
970 $scope = 'bless('
971 . '[@$scope,my$o=new JE\'Object $global]'
972 . ',"JE::Scope")'
973 }
974
975 my $c = $code->{cache}->[my $indx = $cache_indx++] = bless{
976 map+($_,$code->{$_}),qw/global source file line/
977 }, "JE::Code";
978 $c->{tree} = $statements;
979 $c->{vars} = $$expr[-1];
980 $c->optimise;
981  
982 $ret .=
983 "JE'Object'Function->new({"
984 . 'scope=>' . ($scope||'$scope') . ','
985 . (defined $name ? ("name=>$name,") : '')
986 . 'argnames=>[' . join(',',map _esc_str($_),@$params).'],'
987 . "function=>\$\$cache[$indx]"
988 .'})';
989 if($name) {
990 $ret .=
991 ';$o->prop({'
992 . "name=>$name,"
993 . 'value=>$f,'
994 . 'readonly=>1,'
995 . 'dontdel=>1'
996 .'})}'
997 }
998 return ret_rv,$ret;
999 }
1000 }
1001  
1002 sub _cached($) {
1003 my $code_str = shift;
1004 my $indx = $cache_indx++;
1005 return "(\$\$cache[$indx]||=$code_str)";
1006 }
1007  
1008 use constant nan => sin 9**9**9;
1009 use constant inf => 9**9**9;
1010  
1011 sub _term_to_perl {
1012 my $term = $_[0];
1013 my $cx = $_[1];
1014  
1015 # For booleans, we just use the expression itself, since the over-
1016 # loaded booleanness is much faster than ->to_boolean, which has to
1017 # create an object.
1018  
1019 # For strings and numbers, ->to_string->value16 is only slightly
1020 # faster than "" for objects, but the latter is 4x the speed for
1021 # strings and about 5% faster for strings (fewer method calls).
1022 # The converse holds true (exact speed differences aside) for
1023 # ->to_number->value vs 0+ (actually, in 5.8.8 the 0+ overload-
1024 # ing for JE::Number is slower than two method calls, but it’s
1025 # faster in 5.10). If we might have an object, we must
1026 # string-/numbify it immediately so that toString and
1027 # valueOf are called at the right time.
1028  
1029 # ~~~ Having said all that, we can’t use "..." because it will Uni-
1030 # codify the string (un-UTF-16-ify it). We probably need some
1031 # new method added to JE::Types and all the classes.
1032  
1033 if(ref $term eq 'JE::Code::Expression') {
1034 my($rettype,$code,$alt) = $term->to_perl($cx);
1035 return $rettype,
1036 $cx == cx_str ?
1037 defined $alt ? $alt : "$code->to_string->value16" :
1038 $cx == cx_num ?
1039 defined $alt ? $alt : "(0+$code)" :
1040 $cx == cx_bool ?
1041 defined $alt ? $alt : $code :
1042 $code
1043 }
1044 elsif(ref $term) { # ’better be’n array
1045 my $code = _cached("scalar(require JE'Object'RegExp,"
1046 . "JE'Object'RegExp->new(\$global,"
1047 . _esc_str($$term[0])
1048 . (defined $$term[1]?',' . _esc_str($$term[1]):'')
1049 . '))');
1050 return ret_rv,
1051 $cx == cx_str ?
1052 "$code->to_string->value16" :
1053 $cx == cx_num ?
1054 "(0+$code)" :
1055 $code
1056 }
1057  
1058 if($term =~ /^i/) {
1059 my $find = "\$scope->find_var("
1060 . _esc_str(substr $term,1)
1061 . ")";
1062 return
1063 $cx == cx_lv || $cx == cx_any ? ( ret_lv, $find ) :
1064 $cx==cx_str ?( ret_str, "$find->get->to_string->value16") :
1065 $cx==cx_bool?( ret_bool,"$find->get" ) :
1066 $cx==cx_num ?( ret_num, "(0+$find->get)" ) :
1067 ( ret_rv, "$find->get" )
1068 }
1069  
1070 return (ret_void,'0') if $cx == cx_void;
1071 return ret_rv,'die(new JE\'Object\'Error\'ReferenceError $global,'
1072 .'add_line_number"Cannot assign to a non-lvalue")'
1073 if $cx == cx_lv;
1074  
1075 $term eq'this'?
1076 $cx == cx_str ? (ret_str, "\$this->to_string->value16") :
1077 $cx == cx_bool ? (ret_bool, '$this') :
1078 $cx == cx_num ? (ret_num, '(0+$this)') :
1079 ( ret_rv, '$this', 0)
1080 :
1081 $term =~ /^s/ ? do {
1082 my $esc = _esc_str(my $str = substr $term,1);
1083 $cx == cx_str ? (ret_str, $esc) :
1084 $cx == cx_bool ? (ret_bool, 0+(length $term > 1)) :
1085 $cx == cx_num ? (ret_num,
1086 # ~~~ JE::Number probably needs a function for
1087 # this, as it is a repeat of code found else- # where (in JE::String)
1088 $str =~ /^[\p{Zs}\s\ck]*
1089 (
1090 [+-]?
1091 (?:
1092 (?=[0-9]|\.[0-9]) [0-9]* (?:\.[0-9]*)?
1093 (?:[Ee][+-]?[0-9]+)?
1094 |
1095 Infinity
1096 )
1097 [\p{Zs}\s\ck]*
1098 )?
1099 \z
1100 /ox ? defined $1 ? $1 eq 'Infinity' ? 9**9**9 : $1 : 0 :
1101 $str =~ /^ [\p{Zs}\s\ck]* 0[Xx] ([A-Fa-f0-9]+)
1102 [\p{Zs}\s\ck]*\z/ox
1103 ? hex $1 : nan
1104 ) : (
1105 ret_str, _cached "_new JE'String \$global,$esc",
1106 $esc
1107 )
1108 } :
1109 $term eq 't' ?
1110 $cx == cx_str ? (ret_str, '"true"') :
1111 $cx == cx_bool ? (ret_bool, 1) :
1112 $cx == cx_num ? (ret_num, 1) :
1113 ( ret_bool, '$global->true', 1)
1114 :
1115 $term eq 'f' ?
1116 $cx == cx_str ? (ret_str, '"false"') :
1117 $cx == cx_bool ? (ret_bool, 0) :
1118 $cx == cx_num ? (ret_num, 0) :
1119 ( ret_bool, '$global->false', 0)
1120 :
1121 $term eq 'n' ?
1122 $cx == cx_str ? (ret_str, '"null"') :
1123 $cx == cx_bool ? (ret_bool, 0) :
1124 $cx == cx_num ? (ret_num, 0) :
1125 ( ret_rv, '$global->null')
1126 :
1127 $cx == cx_str ? (ret_str,
1128 $term == inf ? '"Infinity"' :
1129 $term ==-+inf ? '"-Infinity"':
1130 $term == $term? $term :
1131 '"NaN"'
1132 ) :
1133 $cx == cx_bool ? (ret_bool, 0+($term && $term == $term)) :
1134 $cx == cx_num ? (ret_num, $term ) :
1135 ( ret_rv, _cached "JE'Number->new(\$global," . (
1136 $term == inf ? '"inf"' : $term == -+inf ? '"-inf"':
1137 $term == $term ? $term : '"nan"'
1138 ) . ')', $term )
1139 }
1140  
1141  
1142  
1143  
1144 sub JE::Code::Subscript::to_perl {
1145 my $val = (my $self = shift)->[1];
1146 ref $val ? $val->to_perl(cx_str) : _esc_str($val);
1147 }
1148  
1149  
1150  
1151  
1152 sub JE::Code::Arguments::to_perl {
1153 my $self = shift;
1154  
1155 join ',', map +(_term_to_perl($_,cx_rv))[1], @$self[1..$#$self];
1156 }
1157  
1158 1