/
Compiler.nqp
2134 lines (1771 loc) · 71.8 KB
/
Compiler.nqp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class QAST::CompilerJS does DWIMYNameMangling does SerializeOnce {
has $!nyi;
#= If the env var NQPJS_LOG is set log to nqpjs.log
method log(*@msgs) {
my %env := nqp::getenvhash();
if %env<NQPJS_LOG> {
my $log := open('nqpjs.log', :a);
$log.say(nqp::join(',', @msgs));
close($log);
}
}
# Holds information about the QAST::Block we're currently compiling.
# The currently compiled block is stored in $*BLOCK
my class BlockInfo does DWIMYNameMangling {
has $!qast; # The QAST::Block
has $!outer; # Outer block's BlockInfo
has @!js_lexicals; # javascript variables we need to declare for the block
has int $!tmp; # We use a bunch of TMP{$n} to store intermediate javascript results
has str $!ctx; # The object we keep dynamic variables and exception handlers in
has @!params; # the parameters the block takes
has @!variables; # the variables declared in this block
has %!variables; # the variables declared in this block
has %!cloned_inners; # Mapping of CUIDs of blocks we clone to register with the clone
has %!captured_inners; # Mapping of CUIDs of blocks we statically clone to register with the code
has %!var_types; # Mapping of lexical names to types
has %!mangled_lexicals;
has %!lexicalref_types;
has @!var_setup;
has %!statevars;
has int $!pass_on_exceptions;
method new($qast, $outer) {
my $obj := nqp::create(self);
$obj.BUILD($qast, $outer);
$obj
}
method BUILD($qast, $outer) {
$!qast := $qast;
$!outer := $outer;
@!js_lexicals := nqp::list();
@!params := nqp::list();
@!variables := nqp::list();
%!variables := nqp::hash();
$!tmp := 0;
%!cloned_inners := nqp::hash();
%!captured_inners := nqp::hash();
%!var_types := nqp::hash();
%!mangled_lexicals := nqp::hash();
%!lexicalref_types := nqp::hash();
@!var_setup := nqp::list();
%!statevars := nqp::hash();
$!pass_on_exceptions := 0;
}
method pass_on_exceptions() {
$!pass_on_exceptions;
}
method use_passing_on_of_exceptions() {
$!pass_on_exceptions := 1;
}
method add_var_setup($setup) {
@!var_setup.push($setup);
}
method var_setup() {
nqp::join('', @!var_setup);
}
method add_mangled_var(QAST::Var $var) {
$var.scope eq 'local' ?? self.mangle_local($var.name) !! self.add_mangled_lexical($var.name);
}
my int $unique := 0;
method add_mangled_lexical($name) {
$unique := $unique + 1;
%!mangled_lexicals{$name} := self.mangle_name($name) ~ $unique;
}
method mangle_own_lexical($name) {
if nqp::existskey(%!mangled_lexicals, $name) {
%!mangled_lexicals{$name}
} else {
nqp::null();
}
}
method mangle_var(QAST::Var $var) {
$var.scope eq 'local' ?? self.mangle_local($var.name) !! self.mangle_lexical($var.name);
}
method mangle_local($name) {
self.mangle_name($name) ~ '$local';
}
method mangle_lexical($name) {
my $info := self;
while $info {
if $info.mangle_own_lexical($name) -> $mangled {
return $mangled;
}
$info := $info.outer;
}
nqp::die("can't mangle $name");
}
method clone_inner($block) {
my int $cuid := $block.cuid;
my str $already := %!cloned_inners{$cuid};
if $already {
$already
}
else {
my str $reg := self.add_tmp;
%!cloned_inners{$cuid} := $reg;
$reg
}
}
method cloned_inners() { %!cloned_inners }
method capture_inner($block) {
my int $cuid := $block.cuid;
my str $already := %!captured_inners{$cuid};
if $already {
$already
}
else {
my str $reg := self.add_tmp;
%!captured_inners{$cuid} := $reg;
$reg
}
}
method captured_inners() { %!captured_inners }
method add_js_lexical($name) {
@!js_lexicals.push($name);
}
method add_js_lexical_with_value($name, $value) {
@!js_lexicals.push($name ~ " = $value");
}
method add_variable($var) {
if $var.scope ne 'local' {
@!variables.push($var);
%!variables{$var.name} := $var;
}
}
method register_lexicalref($var, $type) {
%!lexicalref_types{$var.name} := $type;
}
method lexicalref_type($var) { %!lexicalref_types{$var.name} }
method has_own_variable($name) {
nqp::existskey(%!variables, $name);
}
method add_tmp() {
$!tmp := $!tmp + 1;
'TMP'~$!tmp;
}
method add_param($param) {
@!params.push($param);
}
method statevars() {
%!statevars;
}
method add_statevar($value) {
my str $js_var := QAST::Node.unique('statevar');
%!statevars{$js_var} := $value;
$js_var;
}
method tmps() {
my @tmps;
my int $i := 1;
while $i <= $!tmp {
@tmps.push('TMP'~$i);
$i := $i+1;
}
@tmps;
}
method cuid() {
$!qast ?? $!qast.cuid !! NQPMu;
}
method var_type($var) { %!var_types{$var.name} }
method register_var_type($var, $type) { %!var_types{$var.name} := $type }
method js_lexicals() { @!js_lexicals }
method outer() { $!outer }
method qast() { $!qast }
method ctx(*@value) { $!ctx := @value[0] if @value;$!ctx}
method params() { @!params }
method variables() { @!variables }
has str $!first_time_marker;
method first_time_marker() {
if !$!first_time_marker {
$!first_time_marker := QAST::Node.unique('first_time');
}
$!first_time_marker;
}
method maybe_first_time_marker() {
$!first_time_marker;
}
method ctx_for_var($var, :$from_outer) {
my $info := self;
my int $depth := 0;
my $reached_closure_template := 0;
if $from_outer {
$reached_closure_template := $info.qast.blocktype ne 'immediate';
$depth := $depth + 1 if $reached_closure_template;
$info := $info.outer;
}
while $info {
return NQPMu if $info.qast && $info.qast.ann('DYN_COMP_WRAPPER');
$reached_closure_template := $reached_closure_template || $info.qast.blocktype ne 'immediate';
if $info.has_own_variable($var.name) {
%*USED_CTXS{$info.ctx} := $depth unless nqp::existskey(%*USED_CTXS, $info.ctx);
return $info.ctx;
}
$info := $info.outer;
$depth := $depth + 1 if $reached_closure_template;
}
}
}
method is_dynamic_var(BlockInfo $info, QAST::Var $var) {
# HACK due to a nqp misdesign we need to check the name for the * twigil
# TODO Make nqp mark dynamic variables explicitly
my str $name := $var.name;
if nqp::chars($name) > 2 {
my str $sigil := nqp::substr($name, 0, 1);
my str $twigil := nqp::substr($name, 1, 1);
if $twigil eq '*' || $twigil eq '?' {
return 1;
}
}
return 0 if $var.scope eq 'local';
if $*HLL eq 'perl6' { # To make binding of signatures work
return 1;
}
while $info {
if $info.has_own_variable($name) {
return ($info.qast ?? self.are_children_serializable($info.qast.cuid) !! 1);
}
if $info.qast && $info.qast.symbol($name) -> $symbol {
return 1;
}
$info := $info.outer;
}
return 1;
}
method is_valid_js_identifier($identifier) {
# TODO - implement a simplified version of https://mathiasbynens.be/notes/javascript-identifiers
0;
}
# turns a list of arguments for a call into a js code according to our most general calling convention
# $args is the list of QAST::Node arguments
# returns a Chunk containing either a comma separated list of arguments or an expression that evaluates to a array of arguments
method args($args, :$invocant) {
my @setup;
my @args;
my @named;
my @named_exprs;
my @named_groups;
my @groups := [[]];
for $args -> $arg {
if $arg.flat {
if $arg.named {
my $arg_chunk := self.as_js($arg, :want($T_OBJ));
@setup.push($arg_chunk);
if @named_exprs != 0 {
@named_groups.push('{' ~ nqp::join(',',@named_exprs) ~ '}');
nqp::setelems(@named_exprs, 0);
}
@named_groups.push("nqp.unwrapNamed({$arg_chunk.expr})");
}
else {
my $arg_chunk := self.as_js($arg, :want($T_OBJ));
@setup.push($arg_chunk);
@groups.push("({$arg_chunk.expr}).array");
@groups.push([]);
}
}
elsif $arg.named {
my $compiled_arg := self.as_js($arg, :want($T_CALL_ARG));
@setup.push($compiled_arg);
@named_exprs.push(quote_string($arg.named) ~ ":" ~ $compiled_arg.expr);
}
else {
my $compiled_arg := self.as_js($arg, :want($T_CALL_ARG));
@setup.push($compiled_arg);
@groups[@groups-1].push($compiled_arg.expr);
}
}
# We want to always have at leat 1 thing to pass as the named argument
if @named_exprs || @named_groups == 0 {
if @named_exprs == 0 {
@named_groups.push('null');
}
else {
@named_groups.push('{' ~ nqp::join(',',@named_exprs) ~ '}');
}
}
if $invocant {
@groups[0].unshift($invocant);
}
if +@named_groups > 1 {
@groups[0].unshift('nqp.named([' ~ nqp::join(',', @named_groups) ~ '])');
}
else {
@groups[0].unshift(@named_groups[0]);
}
@groups[0].unshift($*CTX);
if +@groups == 1 {
return Chunk.new($T_ARGS, nqp::join(',', @groups[0]), @setup);
}
my @js_args;
for @groups -> $group {
if nqp::islist($group) {
@js_args.push('[' ~ nqp::join(',', $group) ~ ']') if +$group;
}
else {
@js_args.push($group);
}
}
Chunk.new($T_ARGS_ARRAY, @js_args.shift ~ '.concat(' ~ nqp::join(',', @js_args) ~ ')', @setup);
}
method compile_sig(@params) {
my @sig := ['caller_ctx','_NAMED'];
my @setup;
my sub set_variable($var, $value) {
if self.is_dynamic_var($*BLOCK, $var) {
@setup.push("{$*CTX}[{quote_string($var.name)}] = $value;\n");
}
else {
my str $mangled := $*BLOCK.mangle_var($var);
$*BLOCK.add_js_lexical($mangled);
@setup.push("$mangled = $value;\n");
}
}
my int $pos_slurpy := 0;
my int $pos_required := 0;
my int $pos_optional := 0;
my int $named_slurpy := 0;
my @known_named;
for @params -> $param {
if $param.slurpy {
if $param.named {
$named_slurpy := 1;
set_variable($param, "nqp.slurpyNamed(HLL, _NAMED, {known_named(@known_named)})");
}
else {
$pos_slurpy := 1;
set_variable($param, "nqp.slurpyPos(HLL, arguments, {+@sig})");
}
} else {
my int $type := self.type_from_typeobj($param.returns);
my $suffix := self.suffix_from_type($type);
my sub unpack($value) {
if $type == $T_INT8 || $type == $T_INT16 {
self.int_to_fancy_int($type, "nqp.arg_i($*CTX, $value)");
}
else {
"nqp.arg$suffix({$type == $T_OBJ ?? 'HLL' !! $*CTX}, $value)";
}
}
if $param.named {
my @names := nqp::islist($param.named) ?? $param.named !! nqp::list($param.named);
for @names -> $name {
my str $quoted := quote_string($name);
@known_named.push($quoted);
@setup.push("if (_NAMED !== null && _NAMED.hasOwnProperty($quoted)) \{\n");
set_variable($param, unpack("_NAMED[$quoted]"));
@setup.push("\} else ");
}
@setup.push("\{\n");
if $param.default {
my $default := self.as_js($param.default, :want($type));
@setup.push($default);
set_variable($param, $default.expr);
}
else {
my str $required := quote_string(@names[nqp::elems(@names) - 1]);
@setup.push("nqp.missingNamed($required);\n");
}
@setup.push("\}\n");
}
else {
my str $tmp := self.unique_var('param');
@sig.push($tmp);
my str $set;
if self.is_dynamic_var($*BLOCK, $param) {
$set := "{$*CTX}[{quote_string($param.name)}] = ";
} else {
my str $name := $*BLOCK.mangle_var($param);
$*BLOCK.add_js_lexical($name);
$set := "$name = ";
}
if $param.default {
$pos_optional := $pos_optional + 1;
my $default_value := self.as_js($param.default, :want($type));
@setup.push(Chunk.void(
"if (arguments.length < {+@sig}) \{\n",
$default_value,
"$set {$default_value.expr};\n\} else \{\n$set {unpack($tmp)};\n\}\n"
));
}
else {
$pos_required := $pos_required + 1;
@setup.push($set ~ unpack($tmp) ~ ";\n");
}
}
}
for $param.list -> $param_setup {
@setup.push(self.as_js($param_setup, :want($T_OBJ)));
}
}
if ($pos_required) {
@setup.unshift("if (arguments.length < {$pos_required+2}) nqp.tooFewPos(arguments.length, {$pos_required+2});");
}
if (!$pos_slurpy) {
my $max := $pos_required + $pos_optional + 2;
@setup.unshift("if (arguments.length > $max) nqp.tooManyPos(arguments.length, $max);");
}
if !$named_slurpy {
if +@known_named {
@setup.unshift("if (_NAMED !== null) \{nqp.checkNamed({known_named(@known_named)}, _NAMED)\}\n");
} else {
@setup.unshift("if (_NAMED !== null) \{nqp.noNamed(_NAMED)\}\n");
}
}
Chunk.new($T_NONVAL, nqp::join(',', @sig), @setup);
}
#= Convert a 32bit integer which is a result of js expr $expr into integer type $type for storage
method int_to_fancy_int(int $type, str $expr) {
if $type == $T_INT8 || $type == $T_INT16 {
my int $shift := 32 - self.bits($type);
"($expr << $shift >> $shift)";
} else {
$expr;
}
}
method bits(int $type) {
if $type == $T_INT8 {
8
} elsif $type == $T_INT16 {
16
} else {
nqp::die("We can't determine the number of bits for $type");
}
}
method coerce(Chunk $chunk, $desired) {
my int $got := $chunk.type;
my int $got_int := $got == $T_INT || $got == $T_INT16 || $got == $T_INT8;
if $got != $desired {
if $desired == $T_VOID {
return Chunk.new($T_VOID, "", $chunk.setup);
}
if $desired == $T_CALL_ARG {
if $got == $T_OBJ {
return Chunk.new($T_CALL_ARG, $chunk.expr, $chunk);
}
if $got == $T_BOOL {
return Chunk.new($T_CALL_ARG, "new nqp.NativeIntArg({$chunk.expr} ? 1 : 0)", $chunk);
}
if $got_int {
return Chunk.new($T_CALL_ARG, "new nqp.NativeIntArg({$chunk.expr})", $chunk);
}
if $got == $T_NUM {
return Chunk.new($T_CALL_ARG, "new nqp.NativeNumArg({$chunk.expr})", $chunk);
}
if $got == $T_STR {
return Chunk.new($T_CALL_ARG, "new nqp.NativeStrArg({$chunk.expr})", $chunk);
}
}
if $desired == $T_NUM {
if $got_int {
# we store both as a javascript number, and 32bit integers fit into doubles
return Chunk.new($T_NUM, $chunk.expr, $chunk);
}
if $got == $T_BOOL {
return Chunk.new($T_NUM, "({$chunk.expr} ? 1 : 0)", $chunk);
}
if $got == $T_STR {
return Chunk.new($T_NUM, "nqp.strToNum({$chunk.expr})", $chunk);
}
}
if $desired == $T_INT {
if $got == $T_STR {
return Chunk.new($T_INT, "parseInt({$chunk.expr})", $chunk);
}
if $got == $T_NUM {
return Chunk.new($T_INT, "({$chunk.expr}|0)", $chunk);
}
if $got == $T_BOOL {
return Chunk.new($T_INT, "({$chunk.expr} ? 1 : 0)", $chunk);
}
if $got_int {
return Chunk.new($T_INT, $chunk.expr, $chunk);
}
}
if $got == $T_OBJ {
if $desired == $T_BOOL {
return Chunk.new($desired, "{$chunk.expr}.\$\$decont($*CTX).\$\$toBool($*CTX)", $chunk);
}
return QAST::OperationsJS.unbox(self, $*HLL, $desired, $chunk);
}
if $desired == $T_STR {
if $got_int {
return Chunk.new($T_STR, $chunk.expr ~ '.toString()', $chunk);
}
elsif $got == $T_NUM {
return Chunk.new($T_STR, "nqp.numToStr({$chunk.expr})", $chunk);
}
elsif $got == $T_BOOL {
return Chunk.new($T_STR, "({$chunk.expr} ? '1' : '0')", $chunk);
}
}
if $desired == $T_OBJ {
if $got == $T_BOOL {
$chunk := Chunk.new($T_INT, "({$chunk.expr} ? 1 : 0)", $chunk);
$got := $T_INT;
}
elsif $got == $T_VOID {
# TODO think what's the correct thing here
return Chunk.new($T_OBJ, "nqp.Null", $chunk);
}
if $*HLL eq 'nqp' {
if $got == $T_NUM || $got == $T_STR {
return $chunk;
}
elsif $got == $T_INT {
return Chunk.new($T_OBJ, "new nqp.NQPInt({$chunk.expr})", $chunk);
}
}
else {
my %convert;
%convert{$T_INT} := 'intToObj';
%convert{$T_INT8} := 'intToObj';
%convert{$T_INT16} := 'intToObj';
%convert{$T_NUM} := 'numToObj';
%convert{$T_STR} := 'strToObj';
nqp::die("Can't coerce $got to OBJ") unless nqp::existskey(%convert, $got);
return Chunk.new($T_OBJ, "nqp.{%convert{$got}}(HLL, {$chunk.expr})", $chunk);
}
}
if $desired == $T_BOOL {
if $got_int {
return Chunk.new($T_BOOL, $chunk.expr, $chunk);
} elsif $got == $T_NUM {
return Chunk.new($T_BOOL, "({$chunk.expr} !== 0)", $chunk);
} elsif $got == $T_STR {
return Chunk.new($T_BOOL, "({$chunk.expr} && {$chunk.expr} !== nqp.null_s)", $chunk);
}
}
if $desired == $T_INT8 || $desired == $T_INT16 {
my $int_chunk := $got == $T_INT ?? $chunk !! self.coerce($chunk, $T_INT);
return Chunk.new($desired, self.int_to_fancy_int($desired, $int_chunk.expr) , $int_chunk);
}
return Chunk.new($desired, "nqp.coercion($got, $desired, {$chunk.expr})") #TODO
}
$chunk;
}
my %control_id;
%control_id<last> := 1;
%control_id<redo> := 2;
%control_id<next> := 3;
my @handle_all := <last next redo>;
method handle_control($loop, $ctx, $body) {
my @handled := $*HLL eq 'nqp' ?? $loop.handled !! @handle_all;
if nqp::elems(@handled) > 0 {
my @setup;
if $loop.label {
my $label := self.as_js($loop.label, :want($T_OBJ));
@setup.push($label);
@setup.push("$ctx.\$\$label = {$label.expr};\n");
}
my @handle_exceptions;
my str $action := $*BLOCK.add_tmp;
for @handled -> $type {
my int $id := %control_id{$type};
@setup.push("$ctx.\$\${nqp::uc($type)} = function() \{$action = $id\};\n");
@handle_exceptions.push("if ($action === $id) \{ {self.do_control($type, $loop) } \}\n");
}
my str $unwind_marker := $*BLOCK.add_tmp;
Chunk.new($body.type, $body.expr, [
"$action = 0;\n",
"try \{\n",
"$ctx = new nqp.CtxJustHandler($*CTX, $*CTX, $*CTX.\$\$callThis);\n",
Chunk.void(|@setup),
"$unwind_marker = \{\};\n",
"$ctx.unwind = $unwind_marker;\n",
$body,
"\} catch (e) \{\n",
"if (e === $unwind_marker) \{\n",
Chunk.void(|@handle_exceptions),
"\}\n",
"throw (e);",
"\}\n"
]);
}
else {
Chunk.new($body.type, $body.expr, ["$ctx = $*CTX;", $body]);
}
}
# It's more useful for me during this development to emit partial code instead of quitting
method NYI($msg) {
if $!nyi eq 'ignore' {
}
elsif $!nyi eq 'warn' {
note("NYI: $msg");
}
Chunk.new($T_OBJ,"nqp.NYI({quote_string($msg)})",["console.trace(\"NYI: \"+{quote_string($msg)});\n"]);
#nqp::die("NYI: $msg");
}
method declare_js_vars(@vars) {
if +@vars {
'var '~nqp::join(",\n",@vars)~";\n";
}
else {
'';
}
}
has %!is_serializable;
method is_serializable($cuid) {
nqp::existskey(%!is_serializable, $cuid) ?? %!is_serializable{$cuid} !! 3;
}
method are_children_serializable($cuid) {
nqp::existskey(%!is_serializable, $cuid) ?? %!is_serializable{$cuid} == 2 !! 3;
}
proto method mark_serializable($node) {*}
method mark_children_serializable(QAST::Children $node) {
my int $serializable := 0;
for $node.list -> $child {
my int $is_child_serializable := self.is_ctxsave($node) || self.mark_serializable($child);
$serializable := $serializable || $is_child_serializable;
}
$serializable;
}
multi method mark_serializable(QAST::Block $node) {
my int $children_serializable := self.mark_children_serializable($node);
%!is_serializable{$node.cuid} := $children_serializable ?? 2 !! $node.blocktype ne 'immediate';
}
multi method mark_serializable(QAST::Children $node) {
self.mark_children_serializable($node);
}
multi method mark_serializable($other) {
}
my %want_char := nqp::hash($T_INT, 'I', $T_NUM, 'N', $T_STR, 'S', $T_VOID, 'v');
my sub want($node, $type) {
my @possibles := nqp::clone($node.list);
my $best := @possibles.shift;
return $best unless %want_char{$type};
my $char := %want_char{$type};
for @possibles -> $sel, $ast {
if nqp::index($sel, $char) >= 0 {
$best := $ast;
}
}
$best
}
proto method as_js($node, :$want) {
if nqp::defined($want) {
if nqp::istype($node, QAST::Want) {
self.coerce(self.as_js(want($node, $want), :$want), $want)
}
else {
self.coerce({*}, $want)
}
}
else {
nqp::die("Unknown want");
}
}
# detect the result of HLL::Compiler.CTXSAVE, we need to handle this specially as for performance reasons we store some lexicals as actual javascript lexicals instead of on the context
method is_ctxsave($node) {
+$node.list == 2
&& nqp::istype($node[0], QAST::Op)
&& $node[0].op eq 'bind'
&& +$node[0].list == 2
&& nqp::istype($node[0][0], QAST::Var)
&& $node[0][0].name eq 'ctxsave';
}
method chunk_sequence($type, @chunks, :$node, :$result_child = -1, :$expr) {
if nqp::defined($expr) && $result_child != -1 {
nqp::die("Can't pass both a :expr and :result_child");
}
my @setup;
my int $n := nqp::elems(@chunks);
my str $result_var;
my str $result;
if nqp::defined($expr) {
$result := $expr;
}
if $result_child != -1 && $result_child != $n - 1 {
$result_var := $*BLOCK.add_tmp;
$result := $result_var;
}
my int $i := 0;
while $i < $n {
my $chunk := @chunks[$i];
my str $chunk_expr := nqp::isstr($chunk) ?? $chunk !! $chunk.expr;
nqp::push(@setup, $chunk);
if $i == $result_child {
if $result_var {
@setup.push("$result_var = $chunk_expr;\n");
}
else {
$result := $chunk_expr;
}
}
$i := $i + 1;
}
Chunk.new($type, $result, @setup, :$node);
}
method compile_all_the_statements(QAST::Stmts $node, $want, :$result_child) {
my @chunks;
my @stmts := $node.list;
if $want == $T_VOID {
$result_child := -1;
}
elsif !nqp::defined($result_child) {
$result_child := +$node.list - 1;
}
my int $i := 0;
for @stmts -> $stmt {
my $chunk := self.as_js(@stmts[$i], :want($i == $result_child ?? $want !! $T_VOID));
@chunks.push($chunk);
$i := $i + 1;
}
self.chunk_sequence($want, @chunks, :$result_child, :$node);
}
multi method as_js(QAST::Block $node, :$want) {
my $outer := try $*BLOCK;
my $outer_loop := try $*LOOP;
self.compile_block($node, $outer, $outer_loop, :$want);
}
method mangled_cuid($cuid) {
'cuid'~$cuid;
}
has %!cuids;
method register_cuid($node) {
%!cuids{$node.cuid} := $node;
}
method is_known_cuid($node) {
nqp::existskey(%!cuids, $node.cuid);
}
has %!serialized_code_ref_info;
my class SerializedCodeRefInfo {
has $!closure_template;
has $!lexicals_type_info;
has $!outer_cuid;
has $!static_lexicals;
has $!statevars;
method outer_cuid() {$!outer_cuid}
method lexicals_type_info() {$!lexicals_type_info}
method closure_template() {$!closure_template}
method static_lexicals() {$!static_lexicals}
method statevars() {$!statevars}
}
method setup_cuids() {
my @declared;
my @vars;
for %!cuids {
my str $var := self.mangled_cuid($_.key);
@vars.push($var);
my int $has_statevars := nqp::existskey(%!serialized_code_ref_info, $_.key) && %!serialized_code_ref_info{$_.key}.statevars;
my $class := $has_statevars ?? 'CodeRefWithStateVars' !! 'CodeRef';
@declared.push("$var = new nqp.$class({quote_string($_.value.name)},{quote_string($_.key)})");
}
@declared.push("cuids = [{nqp::join(',', @vars)}]");
self.declare_js_vars(@declared);
}
method set_code_objects() {
my str $set := "";
for %!cuids {
my $code_obj := $_.value.code_object;
if nqp::isconcrete($code_obj) {
$set := $set ~ "{self.mangled_cuid($_.key)}.setCodeObj({self.value_as_js($code_obj)});\n";
}
}
$set;
}
method set_is_thunk_flags() {
my str $set := "";
for %!cuids {
if $_.value.is_thunk {
$set := $set ~ "{self.mangled_cuid($_.key)}.isThunk = true;\n";
}
}
$set;
}
method stored_result($chunk, :$want) {
if $chunk.type == $T_VOID || $want == $T_VOID {
Chunk.void($chunk, $chunk.expr~";\n", :node($chunk.node));
}
else {
my str $tmp := $*BLOCK.add_tmp();
Chunk.new($chunk.type, $tmp, [$chunk, "$tmp = {$chunk.expr};\n"], :node($chunk.node));
}
}
method type_info_for_lexicals(BlockInfo $block) {
my @type_info;
for $block.variables -> $var {
if self.is_dynamic_var($block, $var) {
nqp::push(@type_info,quote_string($var.name)
~ ': ' ~ nqp::objprimspec($var.returns));
}
}
'{' ~ nqp::join(',', @type_info) ~ '}';
}
method wrap_static_block($expected_outer, @output, $block) {
my int $missing_outer := $expected_outer.cuid ne $*BLOCK.cuid && $expected_outer.ctx ne 'null';
if $missing_outer {
@output.push("//Static wrapping\n");
@output.push("(function() \{\n");
@output.push("var {$expected_outer.ctx} = null;\n");
}
$block();
if $missing_outer {
@output.push("\})();\n");
}
}
method has_closure_template($block_info) {
$block_info.qast.blocktype ne 'immediate'
}
method clone_inners($block) {
my @clone_inners;
for $block.cloned_inners -> $kv {
my str $reg := $kv.value;
my str $cuid := self.mangled_cuid($kv.key);
my $block_info := %*BLOCKS_INFO{$kv.key};
if nqp::existskey(%*BLOCKS_STATEVARS, $kv.key) && !self.has_closure_template($block_info) {
@clone_inners.push(%*BLOCKS_STATEVARS{$kv.key});
}
self.wrap_static_block($block_info.outer, @clone_inners, -> {
my $outer := $block_info.outer.ctx;
if self.has_closure_template($block_info) {