/
code.rakumod
1953 lines (1717 loc) Β· 73.4 KB
/
code.rakumod
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
# A blockoid represents the block part of some kind of code declaration.
class RakuAST::Blockoid is RakuAST::SinkPropagator {
has RakuAST::StatementList $.statement-list;
method new(RakuAST::StatementList $statement-list?) {
my $obj := nqp::create(self);
nqp::bindattr($obj, RakuAST::Blockoid, '$!statement-list',
$statement-list // RakuAST::StatementList.new);
$obj
}
method propagate-sink(Bool $is-sunk) {
$!statement-list.propagate-sink($is-sunk, :has-block-parent(True))
}
method IMPL-TO-QAST(RakuAST::IMPL::QASTContext $context, :$immediate) {
my $stmts := $!statement-list.IMPL-TO-QAST($context);
if nqp::elems($stmts.list) == 0 {
$stmts.push(QAST::WVal.new( :value(Nil) ));
}
$stmts
}
method visit-children(Code $visitor) {
$visitor($!statement-list);
}
method IMPL-CAN-INTERPRET() {
$!statement-list.IMPL-CAN-INTERPRET
}
method IMPL-INTERPRET(RakuAST::IMPL::InterpContext $ctx) {
$!statement-list.IMPL-INTERPRET($ctx)
}
}
class RakuAST::OnlyStar is RakuAST::Blockoid {
method new() {
my $obj := nqp::create(self);
nqp::bindattr($obj, RakuAST::Blockoid, '$!statement-list',
RakuAST::StatementList.new(
RakuAST::Statement::Expression.new(:expression(RakuAST::Term::Whatever.new)),
));
$obj
}
method IMPL-TO-QAST(RakuAST::IMPL::QASTContext $context, :$immediate) {
QAST::Op.new(
:op('dispatch'),
QAST::SVal.new( :value('boot-resume') ),
QAST::IVal.new( :value(nqp::const::DISP_ONLYSTAR) ));
}
}
# Marker for all code-y things.
class RakuAST::Code is RakuAST::Node {
has Bool $.custom-args;
has Mu $!qast-block;
method set-custom-args() {
nqp::bindattr(self, RakuAST::Code, '$!custom-args', True);
}
method IMPL-CLOSURE-QAST(RakuAST::IMPL::QASTContext $context, Bool :$regex) {
my $code-obj := self.meta-object;
$context.ensure-sc($code-obj);
my $clone := QAST::Op.new(
:op('callmethod'), :name('clone'),
QAST::WVal.new( :value($code-obj) )
);
self.IMPL-TWEAK-REGEX-CLONE($context, $clone) if $regex;
QAST::Op.new( :op('p6capturelex'), $clone )
}
method IMPL-QAST-BLOCK(RakuAST::IMPL::QASTContext $context, str :$blocktype,
RakuAST::Expression :$expression) {
unless ($!qast-block) {
self.IMPL-FINISH-CODE-OBJECT($context, :$blocktype, :$expression);
}
$!qast-block
}
method IMPL-FINISH-CODE-OBJECT(RakuAST::IMPL::QASTContext $context, str :$blocktype,
RakuAST::Expression :$expression) {
my $block := self.IMPL-QAST-FORM-BLOCK($context, :$blocktype, :$expression);
self.IMPL-LINK-META-OBJECT($context, $block);
nqp::bindattr(self, RakuAST::Code, '$!qast-block', $block);
}
method IMPL-STUB-CODE(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context) {
my $code-obj := self.meta-object;
my $precomp;
my $stub := nqp::freshcoderef(sub (*@pos, *%named) {
if self.IMPL-CAN-INTERPRET {
self.IMPL-INTERPRET(RakuAST::IMPL::InterpContext.new);
}
else {
my $code-obj := nqp::getcodeobj(nqp::curcode());
unless $precomp {
my $block := self.IMPL-QAST-BLOCK($context, :blocktype<declaration_static>);
$precomp := self.IMPL-COMPILE-DYNAMICALLY($resolver, $context, $block);
}
unless nqp::isnull($code-obj) {
return $code-obj(|@pos, |%named);
}
}
});
nqp::bindattr($code-obj, Code, '$!do', $stub);
nqp::markcodestatic($stub);
nqp::markcodestub($stub);
nqp::setcodeobj($stub, $code-obj);
# Create the compiler stuff array and stick it in the code object.
# Also add clearup task to remove it again later.
my @compstuff;
nqp::bindattr($code-obj, Code, '@!compstuff', @compstuff);
$context.add-cleanup-task(sub () {
nqp::bindattr($code-obj, Code, '@!compstuff', nqp::null());
});
@compstuff[2] := sub ($orig, $clone) {
my $do := nqp::getattr($clone, Code, '$!do');
nqp::markcodestub($do);
$context.add-cleanup-task(sub () {
nqp::bindattr($clone, Code, '@!compstuff', nqp::null());
});
}
$stub
}
method IMPL-LINK-META-OBJECT(RakuAST::IMPL::QASTContext $context, Mu $block) {
# Obtain the meta-object and connect it to the code block.
my $code-obj := self.meta-object;
$context.ensure-sc($code-obj);
# Associate QAST block with code object, which will ensure it is
# fixed up as needed.
$block.code_object($code-obj);
# Stash it under the QAST block unique ID.
my str $cuid := $block.cuid();
$context.sub-id-to-code-object(){$cuid} := $code-obj;
my @compstuff := nqp::getattr($code-obj, Code, '@!compstuff');
if $context.is-precompilation-mode {
@compstuff[2] := sub ($orig, $clone) {
my $do := nqp::getattr($clone, Code, '$!do');
nqp::markcodestub($do);
$context.add-cleanup-task(sub () {
nqp::bindattr($clone, Code, '@!compstuff', nqp::null());
});
$context.add-clone-for-cuid($clone, $cuid);
}
}
my $fixups := QAST::Stmts.new();
unless $context.is-precompilation-mode {
# We need to do a fixup of the code block for the non-precompiled case.
$fixups.push(
QAST::Op.new(
:op('bindattr'),
QAST::WVal.new( :value($code-obj) ),
QAST::WVal.new( :value(Code) ),
QAST::SVal.new( :value('$!do') ),
QAST::BVal.new( :value($block) )
)
);
@compstuff[2] := sub ($orig, $clone) {
$context.ensure-sc($clone);
$context.add-cleanup-task(sub () {
nqp::bindattr($clone, Code, '@!compstuff', nqp::null());
});
$context.add-clone-for-cuid($clone, $cuid);
my $tmp := $fixups.unique('tmp_block_fixup');
$fixups.push(QAST::Stmt.new(
QAST::Op.new(
:op('bind'),
QAST::Var.new( :name($tmp), :scope('local'), :decl('var') ),
QAST::Op.new( :op('clone'), QAST::BVal.new( :value($block) ) )
),
QAST::Op.new(
:op('bind'),
QAST::Var.new(
:name('$!do'), :scope('attribute'),
QAST::WVal.new( :value($clone) ),
QAST::WVal.new( :value(Code) )
),
QAST::Var.new( :name($tmp), :scope('local') ),
),
QAST::Op.new(
:op('setcodeobj'),
QAST::Var.new( :name($tmp), :scope('local') ),
QAST::WVal.new( :value($clone) )
)));
}
@compstuff[3] := $fixups;
}
@compstuff[0] := $block;
$context.add-code-ref(nqp::getattr($code-obj, Code, '$!do'), $block);
$context.add-fixup-task(-> {
$fixups
});
}
method IMPL-COMPILE-DYNAMICALLY(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context, Mu $block) {
my $wrapper := QAST::Block.new(QAST::Stmts.new(), $block);
$wrapper.annotate('DYN_COMP_WRAPPER', 1);
my $compunit := QAST::CompUnit.new(
:hll('Raku'),
:sc($context.sc()),
:compilation_mode(0),
$wrapper
);
my $comp := nqp::getcomp('Raku');
my $precomp := $comp.compile($compunit, :from<qast>, :compunit_ok(1));
nqp::dispatch(
'boot-syscall',
'set-compunit-resolver',
$precomp,
-> $name {
my $result := $resolver.resolve-lexical($name);
if $result {
nqp::istype($result, RakuAST::CompileTimeValue)
?? $result.compile-time-value
!! Mu
}
else {
nqp::die("No lexical found with name $name via resolver");
}
},
-> $dyn-name {
my $dynamic-fallback := $resolver.resolve-lexical-in-outer('&DYNAMIC-FALLBACK');
my $without-star := nqp::replace($dyn-name, 1, 1, '');
$dynamic-fallback.compile-time-value()($dyn-name, $without-star)
}
);
my $mainline := $comp.backend.compunit_mainline($precomp);
$mainline();
# Fix up Code object associations (including nested blocks).
# We un-stub any code objects for already-compiled inner blocks
# to avoid wasting re-compiling them, and also to help make
# parametric role outer chain work out. Also set up their static
# lexpads, if they have any.
my @coderefs := $comp.backend.compunit_coderefs($precomp);
my int $num-subs := nqp::elems(@coderefs);
my int $i := -1;
my $result;
while ++$i < $num-subs {
my $subid := nqp::getcodecuid(@coderefs[$i]);
# un-stub code objects for blocks we just compiled:
my %sub-id-to-code-object := $context.sub-id-to-code-object();
if nqp::existskey(%sub-id-to-code-object, $subid) {
my $code-obj := %sub-id-to-code-object{$subid};
nqp::setcodeobj(@coderefs[$i], $code-obj);
nqp::bindattr($code-obj, Code, '$!do', @coderefs[$i]);
my $fixups := nqp::getattr($code-obj, Code, '@!compstuff')[3];
if $fixups {
$fixups.pop() while $fixups.list;
}
nqp::bindattr($code-obj, Code, '@!compstuff', nqp::null());
}
# un-stub clones of code objects for blocks we just compiled:
my %sub-id-to-cloned-code-objects := $context.sub-id-to-cloned-code-objects();
if nqp::existskey(%sub-id-to-cloned-code-objects, $subid) {
for %sub-id-to-cloned-code-objects{$subid} -> $code-obj {
my $clone := nqp::clone(@coderefs[$i]);
nqp::setcodeobj($clone, $code-obj);
nqp::bindattr($code-obj, Code, '$!do', $clone);
my $fixups := nqp::getattr($code-obj, Code, '@!compstuff')[3];
if $fixups {
$fixups.pop() while $fixups.list;
}
nqp::bindattr($code-obj, Code, '@!compstuff', nqp::null());
}
}
my %sub-id-to-sc-idx := $context.sub-id-to-sc-idx();
if nqp::existskey(%sub-id-to-sc-idx, $subid) {
nqp::markcodestatic(@coderefs[$i]);
nqp::scsetcode($context.sc, %sub-id-to-sc-idx{$subid}, @coderefs[$i]);
}
if $subid eq $block.cuid {
# Remember the VM coderef that maps to the thing we were originally
# asked to compile.
$result := @coderefs[$i];
}
}
$result
}
method IMPL-APPEND-SIGNATURE-RETURN(RakuAST::IMPL::QASTContext $context, Mu $qast-stmts) {
my $signature := self.signature;
if $signature && $signature.provides-return-value {
$qast-stmts.push($signature.returns.IMPL-TO-QAST($context));
}
$qast-stmts
}
method needs-sink-call() { False }
method signature() { Nil }
}
# The base of all expression thunks, which produce a code object of some kind
# that wraps the thunk.
class RakuAST::ExpressionThunk is RakuAST::Code is RakuAST::Meta is RakuAST::BeginTime {
has RakuAST::ExpressionThunk $.next;
has RakuAST::Signature $!signature;
method set-next(RakuAST::ExpressionThunk $next) {
nqp::bindattr(self, RakuAST::ExpressionThunk, '$!next', $next);
Nil
}
method thunk-kind() {
self.HOW.name(self)
}
method is-begin-performed-before-children() { False }
method PERFORM-BEGIN(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context) {
self.IMPL-STUB-CODE($resolver, $context);
Nil
}
# Called to produce the QAST::Block for the thunk, which should be pushed
# into the passed `$target`. If there is a next thunk in `$!next` then it
# should be compiled recursively and the expression passed along; otherwise,
# the expression itself should be compiled and used as the body.
method IMPL-THUNK-CODE-QAST(RakuAST::IMPL::QASTContext $context, Mu $target,
RakuAST::Expression $expression) {
my $block := self.IMPL-QAST-BLOCK($context, :$expression);
# Link and push the produced code block.
$target.push($block);
}
method IMPL-QAST-FORM-BLOCK(RakuAST::IMPL::QASTContext $context,
str :$blocktype, RakuAST::Expression :$expression!) {
# From the block, compiling the signature.
my $signature := self.IMPL-GET-OR-PRODUCE-SIGNATURE;
my $block := QAST::Block.new(
:blocktype('declaration_static'),
QAST::Stmts.new(
$signature.IMPL-QAST-BINDINGS($context)
));
$block.arity($signature.arity);
# If there's an inner thunk the body evaluates to that.
if $!next {
$!next.IMPL-THUNK-CODE-QAST($context, $block[0], $expression);
$block.push($!next.IMPL-THUNK-VALUE-QAST($context));
}
# Otherwise, we evaluate to the expression.
else {
$block.push(self.IMPL-THUNK-TWEAK-EXPRESSION($context,
$expression.IMPL-EXPR-QAST($context)));
}
$block
}
# Produces a Code object that corresponds to the thunk.
method IMPL-THUNK-VALUE-QAST(RakuAST::IMPL::QASTContext $context) {
self.IMPL-CLOSURE-QAST($context)
}
# The type of code object produced. Defaults to Code; override to produce
# something else.
method IMPL-THUNK-OBJECT-TYPE() { Code }
# The signature for the code object produced. Defaults to the empty
# signature; override to produce something else
method IMPL-THUNK-SIGNATURE() {
RakuAST::Signature.new
}
# A method to tweak the expression QAST that is produced. Override it
# to do such a tweak.
method IMPL-THUNK-TWEAK-EXPRESSION(RakuAST::IMPL::QASTContext $context, Mu $qast) {
$qast
}
# A callback for when the thunk meta-object is produced, potentially to
# update some other meta-object that wants to reference it.
method IMPL-THUNK-META-OBJECT-PRODUCED(Mu $meta) {
}
method IMPL-GET-OR-PRODUCE-SIGNATURE() {
$!signature // nqp::bindattr(self, RakuAST::ExpressionThunk, '$!signature',
self.IMPL-THUNK-SIGNATURE)
}
method PRODUCE-META-OBJECT() {
my $code := nqp::create(self.IMPL-THUNK-OBJECT-TYPE);
my $signature := self.IMPL-GET-OR-PRODUCE-SIGNATURE;
nqp::bindattr($code, Code, '$!signature', $signature.meta-object);
nqp::bindattr($signature.meta-object, Signature, '$!code', $code);
self.IMPL-THUNK-META-OBJECT-PRODUCED($code);
$code
}
}
# A code object that can have placeholder parameters.
class RakuAST::PlaceholderParameterOwner is RakuAST::Node {
# Any placeholder parameters that have been attached
has Mu $!attached-placeholder-parameters;
# A map grouping placeholder parameters by name, for error checking and
# compilation.
has Mu $!placeholder-map;
# Cached generated placeholder signature.
has RakuAST::Signature $!placeholder-signature;
method add-placeholder-parameter(RakuAST::VarDeclaration::Placeholder $placeholder) {
unless nqp::islist($!attached-placeholder-parameters) {
nqp::bindattr(self, RakuAST::PlaceholderParameterOwner,
'$!attached-placeholder-parameters', []);
}
nqp::push($!attached-placeholder-parameters, $placeholder);
Nil
}
method clear-placeholder-attachments() {
nqp::bindattr(self, RakuAST::PlaceholderParameterOwner,
'$!attached-placeholder-parameters', nqp::null());
Nil
}
method has-placeholder-parameters() {
my $params := $!attached-placeholder-parameters;
nqp::islist($params) && nqp::elems($params) ?? True !! False
}
method IMPL-PLACEHOLDER-MAP() {
unless nqp::ishash($!placeholder-map) {
my %map;
if self.has-placeholder-parameters {
for $!attached-placeholder-parameters -> $param {
my str $key := $param.lexical-name;
(%map{$key} || (%map{$key} := [])).push($param);
}
}
nqp::bindattr(self, RakuAST::PlaceholderParameterOwner,
'$!placeholder-map', %map);
}
$!placeholder-map
}
# Gets the placeholder signature. Only reliable after resolution has taken
# place.
method placeholder-signature() {
# Return Nil if there isn't one to generate, or the cached one if we have
# it.
return Nil unless self.has-placeholder-parameters();
return $!placeholder-signature if $!placeholder-signature;
# Group and sort parameters.
my @positionals;
my @nameds;
my @slurpies;
for self.IMPL-PLACEHOLDER-MAP() {
my $placeholder := $_.value[0];
if nqp::istype($placeholder, RakuAST::VarDeclaration::Placeholder::Positional) {
my int $insert-at := 0;
my str $desigil-insert := nqp::substr($placeholder.lexical-name, 1);
while $insert-at < nqp::elems(@positionals) {
my str $desigil-cur := nqp::substr(@positionals[$insert-at].lexical-name, 1);
last if $desigil-insert lt $desigil-cur;
$insert-at++;
}
nqp::splice(@positionals, [$placeholder], $insert-at, 0);
}
elsif nqp::istype($_, RakuAST::VarDeclaration::Placeholder::Named) {
@nameds.push($placeholder);
}
else {
@slurpies.push($placeholder);
}
}
# Add to signature.
my @parameters;
for @positionals, @nameds, @slurpies -> @placeholders {
for @placeholders {
@parameters.push($_.generate-parameter());
}
}
my $signature := RakuAST::Signature.new(:@parameters);
nqp::bindattr(self, RakuAST::PlaceholderParameterOwner,
'$!placeholder-signature', $signature);
$signature
}
}
# A block, either without signature or with only a placeholder signature.
class RakuAST::Block is RakuAST::LexicalScope is RakuAST::Term is RakuAST::Code is RakuAST::Meta
is RakuAST::BlockStatementSensitive is RakuAST::SinkPropagator
is RakuAST::Blorst is RakuAST::ImplicitDeclarations
is RakuAST::AttachTarget is RakuAST::PlaceholderParameterOwner
is RakuAST::BeginTime {
has RakuAST::Blockoid $.body;
# Should this block have an implicit topic, in the absence of a (perhaps
# placeholder) signature?
# 0 = no implicit topic
# 1 = optional implicit topic
# 2 = required implicit topic
# 3 = required implicit topic populated from exception
has int $!implicit-topic-mode;
# Should this block declare a fresh implicit `$/`?
has int $!fresh-match;
# Should this block declare a fresh implicit `$!`?
has int $!fresh-exception;
method new(RakuAST::Blockoid :$body, Bool :$implicit-topic, Bool :$required-topic) {
my $obj := nqp::create(self);
nqp::bindattr($obj, RakuAST::Block, '$!body', $body // RakuAST::Blockoid.new);
nqp::bindattr_i($obj, RakuAST::Block, '$!implicit-topic-mode', 1);
$obj
}
method replace-body(RakuAST::Blockoid $new-body) {
nqp::bindattr(self, RakuAST::Block, '$!body', $new-body);
Nil
}
method set-implicit-topic(Bool $implicit, Bool :$required, Bool :$exception) {
nqp::bindattr_i(self, RakuAST::Block, '$!implicit-topic-mode', $implicit
?? ($exception ?? 3 !!
$required ?? 2 !!
1)
!! 0);
Nil
}
method set-fresh-variables(Bool :$match, Bool :$exception) {
nqp::bindattr_i(self, RakuAST::Block, '$!fresh-match', $match ?? 1 !! 0);
nqp::bindattr_i(self, RakuAST::Block, '$!fresh-exception', $exception ?? 1 !! 0);
}
method attach-target-names() {
self.IMPL-WRAP-LIST(['block'])
}
method clear-attachments() {
self.clear-handler-attachments();
self.clear-placeholder-attachments();
Nil
}
method propagate-sink(Bool $is-sunk) {
$!body.apply-sink($is-sunk);
}
method PRODUCE-IMPLICIT-DECLARATIONS() {
my @implicit;
if $!implicit-topic-mode == 1 {
@implicit[0] := RakuAST::VarDeclaration::Implicit::BlockTopic.new:
parameter => self.signature ?? False !! True;
}
elsif $!implicit-topic-mode == 2 {
@implicit[0] := RakuAST::VarDeclaration::Implicit::BlockTopic.new:
:required,
parameter => self.signature ?? False !! True;
}
elsif $!implicit-topic-mode == 3 {
@implicit[0] := RakuAST::VarDeclaration::Implicit::BlockTopic.new(:required,
:exception);
}
if $!fresh-match {
nqp::push(@implicit, RakuAST::VarDeclaration::Implicit::Special.new(:name('$/')));
}
if $!fresh-exception {
nqp::push(@implicit, RakuAST::VarDeclaration::Implicit::Special.new(:name('$!')));
}
self.IMPL-WRAP-LIST(@implicit)
}
method is-begin-performed-before-children() { False }
method PERFORM-BEGIN(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context) {
# Make sure that our placeholder signature has resolutions performed,
# and that we don't produce a topic parameter.
my $placeholder-signature := self.placeholder-signature;
if $placeholder-signature {
$placeholder-signature.IMPL-CHECK($resolver, $context, True);
if $!implicit-topic-mode {
my $topic := self.IMPL-UNWRAP-LIST(self.get-implicit-declarations)[0];
$topic.set-parameter(False);
}
}
self.IMPL-STUB-CODE($resolver, $context);
Nil
}
method PRODUCE-META-OBJECT() {
# Create block object and install signature. If it doesn't have one, then
# we can create it based upon the implicit topic it may or may not have.
my $block := nqp::create(Block);
my $signature := self.signature || self.placeholder-signature;
if $signature {
nqp::bindattr($block, Code, '$!signature', $signature.meta-object);
nqp::bindattr($signature.meta-object, Signature, '$!code', $block);
}
elsif $!implicit-topic-mode {
my constant REQUIRED-TOPIC-SIG := -> {
my $param := nqp::create(Parameter);
nqp::bindattr_s($param, Parameter, '$!variable_name', '$_');
my $sig := nqp::create(Signature);
nqp::bindattr($sig, Signature, '@!params', [$param]);
nqp::bindattr_i($sig, Signature, '$!arity', 1);
nqp::bindattr($sig, Signature, '$!count', nqp::box_i(1, Int));
$sig
}();
my constant OPTIONAL-TOPIC-SIG := -> {
my $param := nqp::create(Parameter);
nqp::bindattr_s($param, Parameter, '$!variable_name', '$_');
nqp::bindattr_i($param, Parameter, '$!flags', 2048 + 16384); # Optional + default from outer
my $sig := nqp::create(Signature);
nqp::bindattr($sig, Signature, '@!params', [$param]);
nqp::bindattr_i($sig, Signature, '$!arity', 0);
nqp::bindattr($sig, Signature, '$!count', nqp::box_i(1, Int));
$sig
}();
nqp::bindattr($block, Code, '$!signature', $!implicit-topic-mode == 1
?? OPTIONAL-TOPIC-SIG
!! REQUIRED-TOPIC-SIG);
}
$block
}
method IMPL-QAST-FORM-BLOCK(RakuAST::IMPL::QASTContext $context, str :$blocktype,
RakuAST::Expression :$expression) {
# Form block with declarations.
my $block := QAST::Block.new(
:$blocktype,
self.IMPL-QAST-DECLS($context)
);
# Compile body and, if needed, a signature, and set up arity and any
# exception rethrow logic.
my $body-qast := self.IMPL-APPEND-SIGNATURE-RETURN($context,
$!body.IMPL-TO-QAST($context));
my $signature := self.signature || self.placeholder-signature;
if $signature {
$block.push($signature.IMPL-QAST-BINDINGS($context, :needs-full-binder(self.custom-args)));
$block.custom_args(1) if self.custom-args;
$block.arity($signature.arity);
$block.annotate('count', $signature.count);
}
elsif $!implicit-topic-mode == 1 {
$block.arity(0);
$block.annotate('count', 1);
}
elsif $!implicit-topic-mode >= 2 {
$block.arity(1);
$block.annotate('count', 1);
}
my $is-handler := $!implicit-topic-mode == 3 ?? True !! False;
$block.push(self.IMPL-WRAP-SCOPE-HANDLER-QAST($context, $body-qast, :$is-handler));
$block
}
method IMPL-QAST-DECL-CODE(RakuAST::IMPL::QASTContext $context) {
# Form the block itself and link it with the meta-object.
self.IMPL-QAST-BLOCK($context, :blocktype('declaration_static'));
}
method IMPL-EXPR-QAST(RakuAST::IMPL::QASTContext $context, :$immediate) {
if $immediate {
# For now, assume we never need a code object for such a block. The
# closure clone is done for us by the QAST compiler.
my $block := self.IMPL-QAST-FORM-BLOCK($context, :blocktype('immediate'));
self.IMPL-LINK-META-OBJECT($context, $block);
$block
}
else {
# Not immediate, so already produced as a declaration above; just
# closure clone it. Only invoke if it's a bare block.
# Ensure the block is linked when our outer block gets cloned before
# our IMPL-QAST-DECL-CODE is called.
self.IMPL-QAST-BLOCK($context, :blocktype('declaration_static'));
my $ast := self.IMPL-CLOSURE-QAST($context);
self.bare-block
?? QAST::Op.new( :op('call'), $ast )
!! $ast
}
}
method bare-block() {
self.is-block-statement
}
# Applies the block or hash disambiguation algorithm, to determine whether
# a circumfix:<{ }> should compile as a block or a hash. If it should
# compile as a block, returns identity. Otherwise, returns an instance of
# RakuAST::Circumfix::HashComposer. Note that this method - nor the block
# vs hash distinction - does NOT impact upon the compilation of this node
# if it is in the AST. This method is for use by a compiler that may have
# parsed things tentatively as a block to obtain the actual node to use.
# If constructing AST synthetically, just make the correct thing in the
# first place.
method block-or-hash() {
my @statements := self.IMPL-UNWRAP-LIST(self.body.statement-list.statements);
my int $num-statements := nqp::elems(@statements);
if $num-statements == 0 {
# Empty block is always an empty hash composer
RakuAST::Circumfix::HashComposer.new
}
elsif $num-statements > 1 {
# Multiple statements is always a block
self
}
else {
# Must be an expression statement.
my $statement := @statements[0];
unless nqp::istype($statement, RakuAST::Statement::Expression) {
return self;
}
my $expression := $statement.expression;
# If it's a comma list, then obtain the first element. Otherwise,
# we have the thing to test already.
my int $is-comma := nqp::istype($expression, RakuAST::ApplyListInfix) &&
nqp::istype($expression.infix, RakuAST::Infix) &&
$expression.infix.operator eq ',';
my $test := $is-comma
?? self.IMPL-UNWRAP-LIST($expression.operands)[0]
!! $expression;
# It's a block unless we have:
return self unless
# A fatarrow or colonpair
nqp::istype($test, RakuAST::FatArrow) ||
nqp::istype($test, RakuAST::ColonPair) ||
# The Pair infix operator
nqp::istype($test, RakuAST::ApplyInfix) &&
nqp::istype($test.infix, RakuAST::Infix) &&
$test.infix.operator eq '=>' ||
# A hash sigil'd variable
nqp::istype($test, RakuAST::Var) && $test.sigil eq '%';
# Looks like a hash, but check for declarations or $_ usage.
my int $seen-decl-or-topic;
$expression.visit: -> $node {
# Don't walk into other scopes
if nqp::istype($node, RakuAST::LexicalScope) {
0
}
# If it's a declaration, it blocks; walk no futher
elsif nqp::istype($node, RakuAST::Declaration) {
$seen-decl-or-topic := 1;
0
}
# If it's a usage of the topic, it also blocks; walk no further
elsif nqp::istype($node, RakuAST::Var::Lexical) && $node.name eq '$_' ||
nqp::istype($node, RakuAST::Term::TopicCall) {
$seen-decl-or-topic := 1;
0
}
# Otherwise, keep looking
else {
1
}
}
$seen-decl-or-topic
?? self
!! RakuAST::Circumfix::HashComposer.new($expression)
}
}
method visit-children(Code $visitor) {
$visitor($!body);
}
}
# A pointy block (-> $foo { ... }).
class RakuAST::PointyBlock is RakuAST::Block {
has RakuAST::Signature $.signature;
method new(RakuAST::Signature :$signature, RakuAST::Blockoid :$body) {
my $obj := nqp::create(self);
nqp::bindattr($obj, RakuAST::PointyBlock, '$!signature', $signature
// RakuAST::Signature.new);
nqp::bindattr($obj, RakuAST::Block, '$!body', $body // RakuAST::Blockoid.new);
$obj
}
method replace-signature(RakuAST::Signature $new-signature) {
nqp::bindattr(self, RakuAST::PointyBlock, '$!signature', $new-signature);
Nil
}
method bare-block() { False }
method propagate-sink(Bool $is-sunk) {
self.body.apply-sink($is-sunk);
$!signature.apply-sink(True);
}
method visit-children(Code $visitor) {
$visitor($!signature);
$visitor(self.body);
}
method PERFORM-BEGIN(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context) {
# Make sure that our placeholder signature has resolutions performed,
# and that we don't produce a topic parameter.
if $!signature {
$!signature.IMPL-CHECK($resolver, $context, True);
}
my $placeholder-signature := self.placeholder-signature;
if $placeholder-signature {
$placeholder-signature.IMPL-CHECK($resolver, $context, True);
if nqp::getattr(self, RakuAST::Block, '$!implicit-topic-mode') {
my $topic := self.IMPL-UNWRAP-LIST(self.get-implicit-declarations)[0];
$topic.set-parameter(False);
}
}
self.IMPL-STUB-CODE($resolver, $context);
Nil
}
}
# Done by all kinds of Routine.
class RakuAST::Routine is RakuAST::LexicalScope is RakuAST::Term is RakuAST::Code
is RakuAST::Meta is RakuAST::Declaration is RakuAST::Attaching
is RakuAST::ImplicitDeclarations is RakuAST::AttachTarget
is RakuAST::PlaceholderParameterOwner is RakuAST::ImplicitLookups
is RakuAST::BeginTime is RakuAST::TraitTarget {
has RakuAST::Name $.name;
has RakuAST::Signature $.signature;
has str $!multiness;
has RakuAST::Package $!package;
method multiness() {
my $multiness := $!multiness;
nqp::isnull_s($multiness) ?? '' !! $multiness
}
method replace-name(RakuAST::Name $new-name) {
nqp::bindattr(self, RakuAST::Routine, '$!name', $new-name);
Nil
}
method replace-signature(RakuAST::Signature $new-signature) {
nqp::bindattr(self, RakuAST::Routine, '$!signature', $new-signature);
Nil
}
method attach-target-names() {
self.IMPL-WRAP-LIST(['routine', 'block'])
}
method attach(RakuAST::Resolver $resolver) {
if self.scope eq 'our' || self.scope eq 'unit' {
my $package := $resolver.find-attach-target('package');
nqp::bindattr(self, RakuAST::Routine, '$!package', $package // $resolver.global-package);
}
}
method clear-attachments() {
self.clear-handler-attachments();
self.clear-placeholder-attachments();
Nil
}
method PRODUCE-IMPLICIT-LOOKUPS() {
self.IMPL-WRAP-LIST([
RakuAST::Type::Setting.new(RakuAST::Name.from-identifier('Callable'))
])
}
method PRODUCE-META-OBJECT() {
my $routine := nqp::create(self.IMPL-META-OBJECT-TYPE);
my $signature := self.placeholder-signature || self.signature;
nqp::bindattr($routine, Code, '$!signature', $signature.meta-object);
nqp::bindattr($signature.meta-object, Signature, '$!code', $routine);
if $signature.meta-object.has_returns {
my @lookups := self.IMPL-UNWRAP-LIST(self.get-implicit-lookups);
my $Callable := @lookups[0].compile-time-value;
$routine.HOW.mixin(
$routine,
$Callable.HOW.parameterize($Callable, $signature.meta-object.returns)
);
}
if nqp::istype(self.body, RakuAST::OnlyStar) {
$routine.set_onlystar;
}
nqp::bindattr($routine, Routine, '$!package', $!package.compile-time-value) if $!package;
$routine
}
method is-begin-performed-before-children() { False }
method PERFORM-BEGIN(RakuAST::Resolver $resolver, RakuAST::IMPL::QASTContext $context) {
# Make sure that our placeholder signature has resolutions performed.
my $placeholder-signature := self.placeholder-signature;
if $placeholder-signature {
$placeholder-signature.IMPL-CHECK($resolver, $context, True);
}
# Make sure that our signature has resolutions performed.
if $!signature {
$!signature.set-default-type(
RakuAST::Type::Simple.new(
RakuAST::Name.from-identifier('Any'),
),
);
$!signature.IMPL-CHECK($resolver, $context, True);
}
if self.multiness eq 'multi' {
my $name := '&' ~ self.name.canonicalize;
my $proto := $resolver.resolve-lexical($name, :current-scope-only);
if $proto {
$proto := $proto.compile-time-value;
}
else {
my $scope := $resolver.current-scope;
if $proto := $resolver.resolve-lexical($name) {
$proto := $proto.compile-time-value.derive_dispatcher;
}
elsif $proto := $resolver.resolve-lexical-constant-in-outer($name) {
$proto := $proto.compile-time-value.derive_dispatcher;
}
else {
my $proto-ast := RakuAST::Sub.new(
:scope<my>,
:name(self.name),
:signature(RakuAST::Signature.new(
:parameters(self.IMPL-WRAP-LIST([
RakuAST::Parameter.new(
:slurpy(RakuAST::Parameter::Slurpy::Capture),
)
])),
)),
:body(RakuAST::OnlyStar.new),
:multiness<proto>,
);
$proto-ast.ensure-begin-performed($resolver, $context);
$proto := $proto-ast.meta-object;
$scope.add-generated-lexical-declaration(
RakuAST::VarDeclaration::Implicit::Block.new(:block($proto-ast))
);
}
$scope.add-generated-lexical-declaration(
RakuAST::VarDeclaration::Implicit::Constant.new(:$name, :value($proto))
);
}
$proto.add_dispatchee(self.meta-object);
}
elsif self.multiness eq 'proto' {
nqp::bindattr(self.meta-object, Routine, '@!dispatchees', []);
}
my $stub := self.IMPL-STUB-CODE($resolver, $context);
nqp::setcodename($stub, $!name.canonicalize) if $!name;
# Apply any traits.
self.apply-traits($resolver, $context, self)
}
method PRODUCE-IMPLICIT-DECLARATIONS() {
my $slash := 1;
my $exclamation-mark := 1;
my $underscore := 1;
my @declarations;
if $!signature {
$!signature.IMPL-ENSURE-IMPLICITS;