/
Compiler.nqp
1066 lines (890 loc) · 35 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
use QASTNode;
# The different types of js things a Chunk expr can be
my $T_OBJ := 0;
my $T_INT := 1; # We use a javascript number but always treat it as a 32bit integer
my $T_NUM := 2; # We use a javascript number for that
my $T_STR := 3; # We use a javascript str for that
my $T_BOOL := 4; # Something that can be used in boolean context in javascript. To the user it should be presented as a 0 or 1
my $T_VOID := -1; # Value of this type shouldn't exist, we use a "" as the expr
my $T_NONVAL := -2; # something that is not a nqp value
# turn a string into a javascript literal
sub quote_string($str) {
# This could be simplified a lot when running on none-parrot nqps, as most of the complexity is required to transform \x{...} which is parrot nqp::escape specific
my $out := '';
my $quoted := nqp::escape($str);
# We use a lot of variables to keep track of the state as we can only iterate the chars sequentialy
# nqp::escape on nqp-p returns \x{..} on parrot which we have to transform
my $backslash := 0;
my $x := 0;
my $curly := 0;
my $escape := '';
for nqp::split('',$quoted~'') -> $c {
if $backslash && $c eq 'e' {
$out := $out ~ 'x1b';
} elsif $backslash && $c eq 'a' {
$out := $out ~ 'x07';
} elsif $backslash && $c eq 'x' {
$x := 1;
} elsif $x && $c eq '{' {
$x := 0;
$curly := 1;
} elsif $curly && $c eq '}' {
$out := $out ~ 'u'~nqp::x("0",4-nqp::chars($escape))~$escape;
$escape := '';
$curly := 0;
} elsif $curly {
$escape := $escape ~ $c;
} else {
$out := $out ~ $c;
}
$backslash := !$backslash && $c eq '\\';
}
"\""~$out~"\"";
}
class Chunk {
has int $!type; # the js type of $!expr
has str $!expr; # a javascript expression without side effects
has $!node; # a QAST::Node that contains info for source maps
has @!setup; # stuff that needs to be executed before the value of $!expr can be used, this contains strings and Chunks.
method new($type, $expr, @setup, :$node) {
my $obj := nqp::create(self);
$obj.BUILD($type, $expr, @setup, :$node);
$obj
}
method BUILD($type, $expr, @setup, :$node) {
$!type := $type;
$!expr := $expr;
@!setup := @setup;
$!node := $node if nqp::defined($node);
}
method join() {
my $js := '';
for @!setup -> $part {
if nqp::isstr($part) {
$js := $js ~ $part;
} else {
$js := $js ~ $part.join;
}
}
$js;
}
method with_source_map_info() {
my @parts;
for @!setup -> $part {
if nqp::isstr($part) {
nqp::push(@parts,quote_string($part));
} else {
nqp::push(@parts,$part.with_source_map_info);
}
}
my $parts := '[' ~ nqp::join(',', @parts) ~ ']';
if nqp::defined($!node) && $!node.node {
my $node := $!node.node;
my $line := HLL::Compiler.lineof($node.orig(), $node.from(), :cache(1));
"\{\"line\": $line, \"parts\": $parts\}";
} else {
$parts;
}
}
method type() {
$!type;
}
method expr() {
$!expr;
}
method setup() {
@!setup;
}
}
# TODO think if we should be using such a complicated name mangling scheme
# It's separated into a role so we may replace it with an different scheme when we won't to reduce the output size
role DWIMYNameMangling {
# List taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
my %reserved_words;
for nqp::split(" ",'break case catch continue debugger default delete do else finally for function if in instanceof new return switch this throw try typeof var void while with implements interface let package private protected public static yield class enum export extends import super') {
%reserved_words{$_} := 1;
}
method is_reserved_word($identifier) {
nqp::existskey(%reserved_words, $identifier);
}
my %mangle;
%mangle<_> := 'UNDERSCORE';
%mangle<&> := 'AMPERSAND';
%mangle<:> := 'COLON';
%mangle<;> := 'SEMI';
%mangle<<> := 'LESS';
%mangle<>> := 'MORE';
%mangle<{> := 'CURLY_OPEN';
%mangle<}> := 'CURLY_CLOSE';
%mangle<[> := 'BRACKET_OPEN';
%mangle<]> := 'BRACKET_CLOSE';
%mangle<(> := 'PAREN_OPEN';
%mangle<)> := 'PAREN_CLOSE';
%mangle<~> := 'TILDE';
%mangle<+> := 'PLUS';
%mangle<=> := 'EQUAL';
%mangle<?> := 'QUESTION';
%mangle<!> := 'BANG';
%mangle</> := 'SLASH';
%mangle<*> := 'STAR';
%mangle<-> := 'MINUS';
%mangle<@> := 'AT';
%mangle<,> := 'COMMA';
%mangle<%> := 'PERCENT';
%mangle<¢> := 'CENT';
%mangle< > := 'SPACE';
%mangle<'> := 'SINGLE';
%mangle<"> := 'QUOTE';
%mangle<^> := 'CARET';
%mangle<.> := 'DOT';
%mangle<|> := 'PIPE';
%mangle<`> := 'BACKTICK';
%mangle<$> := 'DOLLAR';
%mangle<\\> := 'BACKSLASH';
method mangle_name($name) {
if self.is_reserved_word($name) {$name := "_$name"}
my $mangled := '';
for nqp::split('',$name) -> $char {
if nqp::iscclass(nqp::const::CCLASS_ALPHANUMERIC, $char, 0) {
$mangled := $mangled ~ $char;
} else {
if nqp::existskey(%mangle, $char) {
$mangled := $mangled ~ '_' ~ %mangle{$char} ~ '_';
} else {
$mangled := $mangled ~ '_' ~ nqp::ord($char) ~ '_';
}
}
}
$mangled;
}
}
class QAST::OperationsJS {
my %ops;
sub add_op($op, $cb) {
%ops{$op} := $cb;
}
sub add_simple_op($op, $return_type, @argument_types, $cb) {
%ops{$op} := sub ($comp, $node, :$want) {
my @exprs;
my @setup;
my $i := 0;
for $node.list -> $arg {
my $chunk := $comp.as_js($arg, :want(@argument_types[$i]));
@exprs.push($chunk.expr);
@setup.push($chunk);
$i := $i + 1;
}
Chunk.new($return_type, $cb(|@exprs), @setup, :$node);
};
}
sub add_infix_op($op, $left_type, $syntax, $right_type, $return_type) {
%ops{$op} := sub ($comp, $node, :$want) {
my $left := $comp.as_js($node[0], :want($left_type));
my $right := $comp.as_js($node[1], :want($right_type));
Chunk.new($return_type, "({$left.expr} $syntax {$right.expr})", [$left, $right], :$node);
};
}
add_infix_op('add_n', $T_NUM, '+', $T_NUM, $T_NUM);
add_infix_op('sub_n', $T_NUM, '-', $T_NUM, $T_NUM);
add_infix_op('mul_n', $T_NUM, '*', $T_NUM, $T_NUM);
# TODO - think about divide by zero
add_infix_op('div_n', $T_NUM, '/', $T_NUM, $T_NUM);
add_infix_op('mod_n', $T_NUM, '%', $T_NUM, $T_NUM);
add_simple_op('neg_n', $T_NUM, [$T_NUM], sub ($num) {"(-$num)"});
add_simple_op('neg_i', $T_INT, [$T_INT], sub ($num) {"(-$num)"});
add_infix_op('concat', $T_STR, '+', $T_STR, $T_STR);
add_infix_op('isle_n', $T_NUM, '<=', $T_NUM, $T_BOOL);
add_infix_op('islt_n', $T_NUM, '<', $T_NUM, $T_BOOL);
add_infix_op('isgt_n', $T_NUM, '>', $T_NUM, $T_BOOL);
add_infix_op('isge_n', $T_NUM, '>=', $T_NUM, $T_BOOL);
add_infix_op('iseq_n', $T_NUM, '==', $T_NUM, $T_BOOL);
add_infix_op('isne_n', $T_NUM, '!=', $T_NUM, $T_BOOL);
add_infix_op('iseq_i', $T_INT, '==', $T_INT, $T_BOOL);
add_infix_op('iseq_s', $T_STR, '==', $T_STR, $T_BOOL);
add_infix_op('isne_s', $T_STR, '!=', $T_STR, $T_BOOL);
add_infix_op('bitor_i', $T_INT, '|', $T_INT, $T_INT);
add_infix_op('bitand_i', $T_INT, '&', $T_INT, $T_INT);
add_infix_op('bitxor_i', $T_INT, '^', $T_INT, $T_INT);
add_infix_op('eqaddr', $T_OBJ, '===', $T_OBJ, $T_BOOL);
# Integer arithmetic
add_simple_op('add_i', $T_INT, [$T_INT, $T_INT], sub ($a, $b) {"(($a + $b) | 0)"});
add_simple_op('sub_i', $T_INT, [$T_INT, $T_INT], sub ($a, $b) {"(($a - $b) | 0)"});
add_simple_op('div_i', $T_INT, [$T_INT, $T_INT], sub ($a, $b) {"(($a / $b) | 0)"});
sub add_cmp_op($op, $type) {
add_simple_op($op, $T_INT, [$type, $type], sub ($a, $b) {
"($a < $b ? -1 : ($a == $b ? 0 : 1))"
});
}
add_cmp_op('cmp_i', $T_INT);
add_cmp_op('cmp_n', $T_NUM);
add_cmp_op('cmp_s', $T_STR);
for <preinc predec> -> $op {
add_op($op, sub ($comp, $node, :$want) {
my $action := $op eq 'preinc' ?? 'add_i' !! 'sub_i';
$comp.as_js(
QAST::Op.new(
:op('bind'),
$node[0],
QAST::Op.new(:op($action),$node[0],QAST::IVal.new(:value(1)))
),
:$want
);
});
}
for <postinc postdec> -> $op {
add_op($op, sub ($comp, $node, :$want) {
my $tmp := $*BLOCK.add_tmp();
my $var := $comp.as_js($node[0], :want($T_INT));
my $action := $op eq 'postinc' ?? 'add_i' !! 'sub_i';
my $do_action := $comp.as_js(
QAST::Op.new(
:op('bind'),
$node[0],
QAST::Op.new(:op($action),$node[0],QAST::IVal.new(:value(1)))
),
:want($T_VOID)
);
Chunk.new($T_INT, $tmp, [$var, "$tmp = {$var.expr};\n", $do_action]);
});
}
add_simple_op('chars', $T_INT, [$T_STR], sub ($string) {"$string.length"});
add_simple_op('join', $T_STR, [$T_STR, $T_OBJ], sub ($delim, $list) {"$list.join($delim)"});
add_simple_op('index', $T_INT, [$T_STR, $T_STR, $T_INT], sub ($string, $pattern, $from?) {
nqp::defined($from) ?? "$string.indexOf($pattern,$from)" !! "$string.indexOf($pattern)";
});
add_simple_op('substr', $T_STR, [$T_STR, $T_INT, $T_INT], sub ($string, $start, $length?) {
nqp::defined($length) ?? "$string.substr($start,$length)" !! "$string.substr($start)";
});
add_simple_op('chr', $T_STR, [$T_INT], sub ($code) {"String.fromCharCode($code)"});
add_simple_op('lc', $T_STR, [$T_STR], sub ($string) {"$string.toLowerCase()"});
add_simple_op('uc', $T_STR, [$T_STR], sub ($string) {"$string.toUpperCase()"});
add_simple_op('flip', $T_STR, [$T_STR], sub ($string) {"$string.split('').reverse().join('')"});
add_simple_op('ord', $T_INT, [$T_STR, $T_INT], sub ($string, $pos='0') {"$string.charCodeAt($pos)"});
add_simple_op('null', $T_OBJ, [], sub () {"null"});
add_op('getcomp', sub ($comp, $node, :$want) {
my $arg := $comp.as_js($node[0], :want($T_STR));
my $tmp := $*BLOCK.add_tmp();
Chunk.new($T_OBJ, $tmp , [$arg, "$tmp = nqp.op.getcomp({$arg.expr});\n"], :$node);
});
add_op('say', sub ($comp, $node, :$want) {
my $arg := $comp.as_js($node[0], :want($T_STR));
Chunk.new($T_VOID, "" , [$arg, "nqp.op.say({$arg.expr});\n"], :$node);
});
add_op('print', sub ($comp, $node, :$want) {
my $arg := $comp.as_js($node[0], :want($T_STR));
Chunk.new($T_VOID, "" , [$arg, "nqp.op.print({$arg.expr});\n"], :$node);
});
add_simple_op('isinvokable', $T_INT, [$T_OBJ], sub ($arg) {"nqp.op.isinvokable($arg)"});
# TODO - think if it's the correct thing to do
add_op('takeclosure', sub ($comp, $node, :$want) {
$comp.as_js($node[0], :want($T_OBJ));
});
add_op('istrue', sub ($comp, $node, :$want) {
$comp.as_js($node[0], :want($T_BOOL));
});
add_op('stringify', sub ($comp, $node, :$want) {
$comp.as_js($node[0], :want($T_STR));
});
add_op('numify', sub ($comp, $node, :$want) {
$comp.as_js($node[0], :want($T_NUM));
});
add_simple_op('falsey', $T_BOOL, [$T_BOOL], sub ($boolified) {"(!$boolified)"});
add_simple_op('not_i', $T_BOOL, [$T_INT], sub ($int) {"(!$int)"});
add_op('bind', sub ($comp, $node, :$want) {
my @children := $node.list;
if +@children != 2 {
nqp::die("A 'bind' op must have exactly two children");
}
unless nqp::istype(@children[0], QAST::Var) {
nqp::die("First child of a 'bind' op must be a QAST::Var");
}
# TODO take the type of variable into account
my $*BINDVAL := @children[1];
$comp.as_js(@children[0], :want($T_OBJ));
});
add_op('list', sub ($comp, $node, :$want) {
my @setup;
my @exprs;
for $node.list -> $elem {
my $chunk := $comp.as_js($elem, :want($T_OBJ));
@setup.push($chunk);
@exprs.push($chunk.expr);
}
Chunk.new($T_OBJ, '[' ~ nqp::join(',', @exprs) ~ ']' , @setup, :$node);
});
add_op('call', sub ($comp, $node, :$want) {
my $tmp := $*BLOCK.add_tmp();
my $args := nqp::clone($node.list);
my $callee := $node.name
?? $comp.as_js(QAST::Var.new(:name($node.name),:scope('lexical')), :want($T_OBJ))
!! $comp.as_js(nqp::shift($args), :want($T_OBJ));
my $compiled_args := $comp.args($args);
if nqp::islist($compiled_args) {
my @exprs;
my @setup := [$callee];
for $compiled_args -> $group {
@exprs.push($group.expr);
@setup.push($group);
}
@setup.push("$tmp = {$callee.expr}({@exprs.shift ~ '.concat(' ~ nqp::join(',', @exprs)}));\n");
Chunk.new($T_OBJ, $tmp , @setup, :$node);
} else {
Chunk.new($T_OBJ, $tmp , [$callee, $compiled_args, "$tmp = {$callee.expr}({$compiled_args.expr});\n"], :$node);
}
});
add_simple_op('split', $T_OBJ, [$T_STR, $T_STR], sub ($separator, $string) {
"({$string} == '' ? [] : {$string}.split({$separator}))"
});
add_simple_op('elems', $T_INT, [$T_OBJ], sub ($list) {"($list.length)"});
add_simple_op('islist', $T_BOOL, [$T_OBJ], sub ($obj) {"($obj instanceof Array)"});
for <ceil floor abs> -> $func {
add_simple_op($func ~ '_n', $T_NUM, [$T_NUM], sub ($arg) {"Math.$func($arg)"});
}
add_simple_op('abs_i', $T_INT, [$T_INT], sub ($arg) {"Math.abs($arg)"});
add_simple_op('pow_n', $T_NUM, [$T_NUM, $T_NUM], sub ($base, $exponent) {"Math.pow($base, $exponent)"});
for <if unless> -> $op_name {
add_op($op_name, sub ($comp, $node, :$want) {
unless nqp::defined($want) {
nqp::die("Unknown want");
}
my $operands := +$node.list;
nqp::die("Operation '"~$node.op~"' needs either 2 or 3 operands")
if $operands < 2 || $operands > 3;
# The 2 operand form of if in a non-void context also uses the cond as the return value
my $cond := $comp.as_js($node[0], :want( ($operands == 3 || $want == $T_VOID) ?? $T_BOOL !! $want));
my $then;
my $else;
my $result;
if $want != $T_VOID {
$result := $*BLOCK.add_tmp();
}
# See if any immediate block wants to be passed the condition.
my $im_then := (nqp::istype($node[1], QAST::Block) &&
$node[1].blocktype eq 'immediate' &&
$node[1].arity > 0) ?? 1 !! 0;
my $im_else := ($operands == 3 &&
nqp::istype($node[2], QAST::Block) &&
$node[2].blocktype eq 'immediate' &&
$node[2].arity > 0) ?? 1 !! 0;
# TODO if cond() -> $var {...}
my $boolifed_cond := $comp.coerce($cond, $T_BOOL);
if $node.op eq 'if' {
$then := $comp.as_js($node[1], :$want);
if $operands == 3 {
$else := $comp.as_js($node[2], :$want);
} else {
$else := $comp.coerce($cond, $want);
}
} else {
if $operands == 3 {
$then := $comp.as_js($node[2], :$want);
} else {
$then := $comp.coerce($cond, $want);
}
$else := $comp.as_js($node[1], :$want);
}
Chunk.new($want, $result, [
$boolifed_cond,
"if ({$boolifed_cond.expr}) \{",
$then,
$want != $T_VOID ?? "$result = {$then.expr}" !! '',
"\} else \{",
$else,
$want != $T_VOID ?? "$result = {$else.expr}" !! '',
"\}"
], :node($node));
});
}
for <while until repeat_while repeat_until> -> $op {
add_op($op, sub ($comp, $node, :$want) {
my $label;
my $handler := 1;
my @operands;
for $node.list {
if $_.named eq 'nohandler' { $handler := 0; }
elsif $_.named eq 'label' { $label := $_; }
else { @operands.push($_) }
}
return $comp.NYI("3 argument $op") if +@operands == 3;
# TODO - return value
# TODO while ... -> $cond {}
my $cond := $comp.as_js(@operands[0], :want($T_BOOL));
my $body := $comp.as_js(@operands[1], :want($T_VOID));
if $op eq 'while' || $op eq 'until' {
my $neg := $op eq 'while' ?? '!' !! '';
Chunk.new($T_VOID, '', [
"for (;;) \{\n",
$cond,
"if ($neg {$cond.expr}) \{break;\}\n",
$body,
"\}"
]);
} else {
my $neg := $op eq 'repeat_while' ?? '' !! '!';
Chunk.new($T_VOID, '', [
"do \{\n",
$body,
$cond,
"\} while ($neg {$cond.expr});"
]);
}
});
}
method compile_op($comp, $op, :$want) {
my str $name := $op.op;
if nqp::existskey(%ops, $name) {
%ops{$name}($comp, $op, :$want);
} else {
$comp.NYI("unimplemented QAST::Op {$op.op}");
}
}
}
class QAST::CompilerJS does DWIMYNameMangling {
# Holds information about the QAST::Block we're currently compiling.
# The currently compiled block is stored in $*BLOCK
my class BlockInfo {
has $!qast; # The QAST::Block
has $!outer; # Outer block's BlockInfo
has @!js_lexicals; # javascript variables we need to declare for the block
has $!tmp; # We use a bunch of TMP{$n} to store intermediate javascript results
has $!ctx; # The object we keep dynamic variables and exception handlers in
has @!params; # the parameters the block takes
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();
$!tmp := 0;
}
method add_js_lexical($name) {
@!js_lexicals.push($name);
}
method add_tmp() {
$!tmp := $!tmp + 1;
'TMP'~$!tmp;
}
method add_param($param) {
@!params.push($param);
}
method tmps() {
my @tmps;
my $i := 1;
while $i <= $!tmp {
@tmps.push('TMP'~$i);
$i := $i+1;
}
@tmps;
}
method js_lexicals() { @!js_lexicals }
method outer() { $!outer }
method qast() { $!qast }
method ctx(*@value) { $!ctx := @value[0] if @value;$!ctx}
method params() { @!params }
}
# TODO improve comments
# turns a list of arguments for a call into a js code according to our most generall calling convention
# $args is the list of QAST::Node arguments
# returns either a js code string which contains the arguments, or a list of js code strings that when executed create arrays of arguments (suitable for concatenating and passing into Function.apply)
method args($args) {
my @setup;
my @args;
my @named;
my @flat_named;
my @groups := [[]];
for $args -> $arg {
if nqp::istype($arg,QAST::SpecialArg) {
if $arg.flat {
if $arg.named {
# TODO - think about chunks
@flat_named.push(self.as_js($arg));
} else {
@groups.push(self.as_js($arg, :want($T_OBJ)));
@groups.push([]);
}
}
elsif $arg.named {
# TODO - think about chunks
@named.push(self.quote_string($arg.named)~":"~self.as_js($arg))
}
else {
@groups[@groups-1].push(self.as_js($arg, :want($T_OBJ)));
}
} else {
@groups[@groups-1].push(self.as_js($arg, :want($T_OBJ)));
}
}
@flat_named.unshift('{'~nqp::join(',',@named)~'}');
@groups[0].unshift("nqp.named({nqp::join(',',@flat_named)})");
@groups[0].unshift($*BLOCK.ctx);
my sub chunkify(@group, $pre = '', $post = '') {
my @exprs;
my @setup;
for @group -> $arg {
if nqp::isstr($arg) {
@exprs.push($arg);
} else {
@exprs.push($arg.expr);
@setup.push($arg);
}
}
Chunk.new($T_NONVAL, $pre ~ nqp::join(',', @exprs) ~ $post, @setup);
}
if +@groups == 1 {
return chunkify(@groups[0]);
}
my @js_args;
for @groups -> $group {
if nqp::islist($group) {
@js_args.push(chunkify($group, '[', ']')) if +$group
} else {
@js_args.push($group);
}
}
@js_args;
}
method compile_sig(@params) {
my $slurpy_named; # *%foo
my $slurpy; # *@foo
my @named; # :$foo
my @pos; # $foo
my $bind_named := '';
for @params {
if $_.slurpy {
#say("//NYI: slurpy params {$_.name}");
if $_.named {
$slurpy_named := $_;
} else {
$slurpy := $_;
}
} elsif $_.named {
#say("//NYI: named params");
unless self.is_dynamic_var($_) {
@named.push(self.mangle_name($_.name));
}
my $quoted := self.quote_string($_.named);
my $value := "_NAMED[$quoted]";
if $_.default {
$value := "(_NAMED.hasOwnProperty($quoted) ? $value : {self.as_js($_.default)})";
}
$bind_named := $bind_named ~ self.bind_var($_,self.js($value),1) ~ ";\n";
} else {
my $default := '';
if $_.default {
say("//NYI: default");
$default := self.as_js($_.default, :want($T_OBJ));
}
@pos.push([$_,$default]);
}
}
# if $slurpy_named {
# $bind_named := $bind_named ~ self.bind_var($slurpy_named,self.js('_NAMED'),1) ~ ";\n";
# }
my @sig := ['_NAMED','caller_ctx'];
for @pos -> $pos {
@sig.push(self.mangle_name($pos[0].name));
}
nqp::join(',', @sig);
}
method coerce($chunk, $desired) {
my $got := $chunk.type;
if $got != $desired {
if $desired == $T_NUM {
if $got == $T_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 {
my $tmp := $*BLOCK.add_tmp();
return Chunk.new($T_NUM, "(isNaN($tmp) ? 0 : $tmp)", [$chunk,"$tmp = parseFloat({$chunk.expr});\n"]);
return Chunk.new($T_NUM, $chunk.expr, [$chunk]);
}
}
if $got == $T_OBJ {
my %convert;
%convert{$T_STR} := 'to_str';
%convert{$T_NUM} := 'to_num';
%convert{$T_INT} := 'to_int';
%convert{$T_BOOL} := 'to_bool';
return Chunk.new($desired, 'nqp.' ~ %convert{$desired} ~ '(' ~ $chunk.expr ~ ')', [$chunk]);
}
if $desired == $T_STR {
if $got == $T_INT || $got == $T_NUM {
return Chunk.new($T_STR, $chunk.expr ~ '.toString()', [$chunk]);
}
if $got == $T_BOOL {
return Chunk.new($T_STR, "({$chunk.expr} ? '1' : '0')", [$chunk]);
}
}
if $desired == $T_OBJ {
if $got == $T_INT || $got == $T_NUM || $got == $T_STR {
return $chunk;
} elsif $got == $T_BOOL {
return Chunk.new($T_OBJ, "({$chunk.expr} ? 1 : 0)", [$chunk]);
} elsif $got == $T_VOID {
# TODO think what's the correct thing here
return Chunk.new($T_OBJ, "null", [$chunk]);
}
}
if $desired == $T_BOOL {
if $got == $T_INT || $got == $T_NUM {
return Chunk.new($T_BOOL, $chunk.expr, [$chunk]);
} elsif $got == $T_STR {
return Chunk.new($T_BOOL, "({$chunk.expr} != '0' && {$chunk.expr})", [$chunk]);
}
}
if $desired == $T_VOID {
return Chunk.new($T_VOID, "", $chunk.setup);
}
return Chunk.new($desired, "coercion($got, $desired, {$chunk.expr})", []) #TODO
}
$chunk;
}
# It's more usefull for me during this development to emit partial code instead of quiting
method NYI($msg) {
Chunk.new($T_VOID,"NYI($msg)",["// NYI: $msg\n"]);
#nqp::die("NYI: $msg");
}
method declare_js_vars(@vars) {
if +@vars {
'var '~nqp::join(",\n",@vars)~";\n";
} else {
'';
}
}
sub want($node, $desired) {
# TODO
}
proto method as_js($node, :$want) {
unless nqp::defined($want) {
nqp::die("Unknown want");
}
if nqp::defined($want) {
if nqp::istype($node, QAST::Want) {
self.NYI("QAST::Want");
# self.coerce(self.as_jast(want($node, $*WANT)), $*WANT)
}
else {
self.coerce({*}, $want)
}
}
else {
{*}
}
}
# 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';
}
# TODO save the value of the last statement
method compile_all_the_statements(QAST::Stmts $node, $want, :$resultchild) {
my @setup;
my @stmts := $node.list;
my int $n := +@stmts;
# my $all_void := $*WANT == $T_VOID;
unless nqp::defined($resultchild) {
$resultchild := $n - 1;
}
my $result := "";
my int $i := 0;
for @stmts {
my $chunk := self.as_js($_, :want($i == $resultchild ?? $want !! $T_VOID));
$result := $chunk.expr if $i == $resultchild;
nqp::push(@setup, $chunk);
$i := $i + 1;
}
Chunk.new($want, $result, @setup);
}
multi method as_js(QAST::Block $node, :$want) {
my $outer := try $*BLOCK;
self.compile_block($node, $outer, :$want);
}
method mangled_cuid($node) {
my $ret := '';
for nqp::split('',$node.cuid) -> $c {
$ret := $ret ~ ($c eq '.' ?? '_' !! $c);
}
$ret;
}
has %!cuids;
method register_cuid($node) {
%!cuids{$node.cuid} := 1;
}
method is_known_cuid($node) {
nqp::existskey(%!cuids, $node.cuid);
}
method compile_block(QAST::Block $node, $outer, :$want) {
my $cuid := self.mangled_cuid($node);
my $setup;
if self.is_known_cuid($node) {
$setup := [];
} else {
self.register_cuid($node);
my $*BINDVAL := 0;
my $*BLOCK := BlockInfo.new($node, (nqp::defined($outer) ?? $outer !! NQPMu));
my $create_ctx := self.create_fresh_ctx();
# TODO proper want handling
my $body_want := $T_OBJ;
my $stmts := self.compile_all_the_statements($node, $body_want);
my $sig := self.compile_sig($*BLOCK.params);
$setup := [
"$cuid = function($sig) \{",
self.declare_js_vars($*BLOCK.tmps),
self.declare_js_vars($*BLOCK.js_lexicals),
$create_ctx,
$stmts,
"return {$stmts.expr};\n",
"\};\n"];
}
if $node.blocktype eq 'immediate' {
self.NYI("immediate blocks");
} else {
Chunk.new($T_OBJ, $cuid, $setup);
}
}
has $!unique_vars;
method unique_var($prefix) {
$!unique_vars := $!unique_vars + 1;
$prefix~$!unique_vars;
}
method create_fresh_ctx() {
$*BLOCK.ctx(self.unique_var('ctx'));
self.create_ctx($*BLOCK.ctx);
}
method create_ctx($name) {
# TODO think about contexts
#"var $name = new nqp.Ctx(caller_ctx,{self.outer_ctx},'$name');\n";
"var $name = null;\n";
}
multi method as_js(QAST::IVal $node, :$want) {
Chunk.new($T_INT,'('~$node.value()~')',[],:$node);
}
multi method as_js(QAST::NVal $node, :$want) {
Chunk.new($T_NUM,'('~$node.value()~')',[],:$node);
}
multi method as_js(QAST::SVal $node, :$want) {
Chunk.new($T_STR,quote_string($node.value()),[],:$node);
}
multi method as_js(QAST::BVal $node, :$want) {
self.as_js($node.value, :$want);
}
multi method as_js(QAST::Stmts $node, :$want) {
if self.is_ctxsave($node) {
self.NYI("handle CTXSAVE");
} else {
self.compile_all_the_statements($node, $want);
}
}
multi method as_js(QAST::VM $node, :$want) {
# We ignore QAST::VM as we don't support a js specific one, and the ones nqp generate contain parrot specific stuff we don't care about.
Chunk.new($T_VOID,'',[]);
}
multi method as_js(QAST::Op $node, :$want) {
QAST::OperationsJS.compile_op(self, $node, :$want);
}
multi method as_js(QAST::CompUnit $node, :$want) {
# Should have a single child which is the outer block.
if +@($node) != 1 || !nqp::istype($node[0], QAST::Block) {
nqp::die("QAST::CompUnit should have one child that is a QAST::Block");
}
# Compile the block.
my $block_js := self.as_js($node[0], :want($T_VOID));
if nqp::defined($node.main) {
my $main_block := QAST::Block.new($node.main);
my $main := self.as_js($main_block, :want($T_VOID));
Chunk.new($T_VOID, "", [$block_js, $main, self.mangled_cuid($main_block) ~ "();\n"]);
} else {
$block_js;
}
}
method declare_var(QAST::Var $node) {
# TODO vars more complex the non-dynamic lexicals
if $node.decl eq 'var' {
$*BLOCK.add_js_lexical(self.mangle_name($node.name));
} elsif $node.decl eq 'param' {
if $node.scope eq 'local' || $node.scope eq 'lexical' {
$*BLOCK.add_param($node);
} else {
nqp::die("Parameter cannot have scope '{$node.scope}'; use 'local' or 'lexical'");
}
}
}
multi method as_js(QAST::Var $node, :$want) {
self.declare_var($node);
self.compile_var($node);
}
method var_is_lexicalish(QAST::Var $var) {
$var.scope eq 'lexical' || $var.scope eq 'typevar';
}
method as_js_clear_bindval($node, :$want) {