/
Internals.pm6
1797 lines (1646 loc) · 67.3 KB
/
Internals.pm6
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
my class DateTime { ... }
my role IO { ... }
my class IO::Handle { ... }
my class IO::Path { ... }
my class Rakudo::Metaops { ... }
my class List::Reifier { ... }
my class X::Assignment::ToShaped { ... }
my class X::Cannot::Lazy { ... }
my class X::IllegalDimensionInShape { ... }
my class X::IllegalOnFixedDimensionArray { ... }
my class X::Localizer::NoContainer { ... }
my class X::Str::Sprintf::Directives::BadType { ... }
my class X::Str::Sprintf::Directives::Count { ... }
my class X::Str::Sprintf::Directives::Unsupported { ... }
my class X::TypeCheck { ... }
# Marker symbol for 6.c-mode regex boolification.
my class Rakudo::Internals::RegexBoolification6cMarker { }
my class Rakudo::Internals {
# for use in nqp::splice
my $empty := nqp::list;
our class CompilerServices {
has Mu $!compiler;
has Mu $!current-match;
method generate_accessor(str $name, Mu \package_type, str $attr_name, Mu \type, int $rw) {
$!compiler.generate_accessor(
$!current-match, $name, package_type, $attr_name, type, $rw);
}
method generate_buildplan_executor(Mu \obj, Mu \buildplan) {
$!compiler.generate_buildplan_executor(
$!current-match, obj, buildplan)
}
}
# Marker symbol for lexicals that we have lowered away.
class LoweredAwayLexical {
method dynamic() { False }
}
# rotate nqp list to another given list without using push/pop
method RotateListToList(\from,\n,\to) {
nqp::stmts(
(my $from := nqp::getattr(from,List,'$!reified')),
nqp::if((my int $elems = nqp::elems($from)),
nqp::stmts(
(my $to := nqp::getattr(to,List,'$!reified')),
(my int $i = -1),
(my int $j = nqp::mod_i(nqp::sub_i(nqp::sub_i($elems,1),n),$elems)),
nqp::if(nqp::islt_i($j,0),($j = nqp::add_i($j,$elems))),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
nqp::bindpos(
$to,
($j = nqp::mod_i(nqp::add_i($j,1),$elems)),
nqp::atpos($from,$i)
),
),
),
),
to
)
}
method RANGE-AS-ints ($range, $exception) {
# Convert a Range to min/max values that can fit into an `int`
# Treats values smaller than int.Range.min as int.Range.min
# Treats values larger than int.Range.max as int.Range.max
# Throws $exception for non-Numeric ranges or ranges with any NaN endpoints
# If $exception is a Str, calls `die $exception`
my $min := $range.min;
my $max := $range.max;
nqp::unless(
nqp::istype($min, Numeric) && nqp::isfalse($min.isNaN)
&& nqp::istype($max, Numeric) && nqp::isfalse($max.isNaN),
nqp::if(nqp::istype($exception, Str), die($exception), $exception.throw));
# Get rid of Infs
$min := Int($min + $range.excludes-min) // -2**63;
$max := Int($max - $range.excludes-max) // 2**63-1;
# we have isbig_I, but it tells whether the value is above max int32 value
nqp::if( nqp::islt_I(nqp::decont($min), -2**63),
$min = -2**63);
nqp::if( nqp::isgt_I(nqp::decont($max), 2**63-1),
$max = 2**63-1);
($min, $max);
}
method SET_LEADING_DOCS($obj, $docs) {
my $current_why := $obj.WHY;
if $current_why {
my $end := nqp::elems($*POD_BLOCKS) - 1;
my $i := $end;
while $i >= 0 {
if $docs === nqp::atpos($*POD_BLOCKS, $i) {
nqp::splice($*POD_BLOCKS, $empty, $i, 1);
last;
}
$i := $i - 1;
}
$current_why._add_leading(~$docs);
} else {
$obj.set_why($docs);
}
}
method SET_TRAILING_DOCS($obj, $docs) {
my $current_why := $obj.WHY;
if $current_why {
$current_why._add_trailing(~$docs);
} else {
$obj.set_why($docs);
$*POD_BLOCKS.push($docs);
}
}
method EXPORT_SYMBOL(\exp_name, @tags, Mu \sym) {
my @export_packages = $*EXPORT;
for nqp::hllize(@*PACKAGES).list {
unless .WHO.EXISTS-KEY('EXPORT') {
.WHO<EXPORT> := Metamodel::PackageHOW.new_type(:name('EXPORT'));
.WHO<EXPORT>.^compose;
}
@export_packages.append: .WHO<EXPORT>;
}
for @export_packages -> $p {
for @tags -> $tag {
my $install_in;
if $p.WHO.EXISTS-KEY($tag) {
$install_in := $p.WHO.{$tag};
}
else {
$install_in := Metamodel::PackageHOW.new_type(:name($tag));
$install_in.^compose;
$p.WHO{$tag} := $install_in;
}
if $install_in.WHO.EXISTS-KEY(exp_name) {
unless ($install_in.WHO){exp_name} =:= sym {
X::Export::NameClash.new(symbol => exp_name).throw;
}
}
$install_in.WHO{exp_name} := sym;
}
}
0;
}
method createENV(int $bind) {
nqp::stmts(
(my $hash := nqp::hash),
(my $iter := nqp::iterator(nqp::getenvhash)),
nqp::while(
$iter,
nqp::bindkey(
$hash,
nqp::iterkey_s(nqp::shift($iter)),
nqp::if(
$bind,
val(nqp::iterval($iter)),
nqp::p6scalarfromdesc(nqp::null) = val(nqp::iterval($iter))
)
)
),
nqp::p6bindattrinvres(
nqp::create(nqp::if($bind,Map,Hash)),Map,'$!storage',$hash
)
)
}
# Helper method for prefix:<let>/prefix:<temp>, which really do the same
# thing apart from where they store data. Takes the IterationBuffer in
# which to save data, the container to be inspected, and the type of op
# for any error messaging.
method TEMP-LET(\restore, \cont, str $localizer) is raw {
nqp::stmts(
(my int $i = nqp::elems(restore)),
nqp::while(
nqp::isgt_i($i,0),
nqp::if(
nqp::eqaddr(nqp::atpos(restore,($i = nqp::sub_i($i,2))),cont),
(return-rw cont)
)
),
nqp::if(
nqp::istype(cont,Failure),
cont.exception.throw,
nqp::stmts(
nqp::push(restore,cont),
nqp::if(
nqp::iscont(cont),
nqp::push(restore,nqp::decont(cont)),
nqp::if(
nqp::istype(cont,Array),
nqp::push(restore,cont.clone),
nqp::if(
nqp::istype(cont,Hash),
nqp::push(restore,
nqp::p6bindattrinvres(
Hash.^parameterize(Mu,Mu).new,
Hash, '$!descriptor',
nqp::getattr(cont, Hash, '$!descriptor')).STORE: cont),
nqp::stmts(
nqp::pop(restore), # lose the erroneously pushed value
X::Localizer::NoContainer.new(:$localizer).throw
)
)
)
)
)
),
cont
)
}
# fast whitespace trim: str to trim, str to store trimmed str
method !TRIM(\string, \trimmed --> Nil) {
my int $pos = nqp::chars(string) - 1;
my int $left =
nqp::findnotcclass(nqp::const::CCLASS_WHITESPACE, string, 0, $pos + 1);
$pos = $pos - 1
while nqp::isge_i($pos, $left)
&& nqp::iscclass(nqp::const::CCLASS_WHITESPACE, string, $pos);
trimmed = nqp::islt_i($pos, $left)
?? ''
!! nqp::substr(string, $left, $pos + 1 - $left);
Nil
}
# fast key:value split: Str to split, str to store key, str to store value
method KEY_COLON_VALUE(Str $command, \key, \value --> Nil) {
my str $str = nqp::unbox_s($command);
my int $index = nqp::index($str,':');
if nqp::isgt_i($index,0) {
self!TRIM(nqp::substr($str,0,$index),key);
self!TRIM(nqp::substr($str,$index + 1,nqp::chars($str) - $index),value);
}
elsif nqp::islt_i($index,0) {
self!TRIM($str,key);
value = '';
}
else {
key = '';
self!TRIM(nqp::substr($str,1,nqp::chars($str) - 1),value);
}
Nil
}
# key space value split: Str to split, str to store key, str to store value
method KEY_SPACE_VALUE(Str $command, \key, \value --> Nil) {
my str $str = nqp::unbox_s($command);
my int $index = nqp::index($str,' ');
if nqp::isgt_i($index,0) {
key = nqp::substr($str,0,$index);
value = nqp::substr($str,$index + 1,nqp::chars($str) - $index);
}
elsif nqp::islt_i($index,0) {
key = $str;
value = '';
}
else {
key = '';
value = nqp::substr($str,1,nqp::chars($str) - 1);
}
Nil
}
# Fast mapping for identicals
### If updating encodings here, also update src/core.c/Encoding/Registry.pm6
my $encodings := nqp::hash(
# utf8
'utf8', 'utf8',
'utf-8', 'utf8',
# utf8-c8
'utf8-c8', 'utf8-c8',
'utf8c8', 'utf8-c8',
'utf-8-c8', 'utf8-c8',
# utf16
'utf16', 'utf16',
'utf-16', 'utf16',
# utf16le
'utf16le', 'utf16le',
'utf-16le', 'utf16le',
'utf16-le', 'utf16le',
'utf-16-le', 'utf16le',
# utf16be
'utf16be', 'utf16be',
'utf-16be', 'utf16be',
'utf16-be', 'utf16be',
'utf-16-be', 'utf16be',
# utf32
'utf32', 'utf32',
'utf-32', 'utf32',
# ascii
'ascii', 'ascii',
# iso-8859-1 according to http://de.wikipedia.org/wiki/ISO-8859-1
'iso-8859-1', 'iso-8859-1',
'iso_8859-1:1987', 'iso-8859-1',
'iso_8859-1', 'iso-8859-1',
'iso-ir-100', 'iso-8859-1',
'latin1', 'iso-8859-1',
'latin-1', 'iso-8859-1',
'csisolatin1', 'iso-8859-1',
'l1', 'iso-8859-1',
'ibm819', 'iso-8859-1',
'cp819', 'iso-8859-1',
# windows-1251
'windows-1251', 'windows-1251',
'windows1251', 'windows-1251',
# windows-1252
'windows-1252', 'windows-1252',
'windows1252', 'windows-1252',
# ShiftJIS
'windows-932', 'windows-932',
'windows932', 'windows-932',
# GB2312
'gb2312', 'gb2312',
# GB18030
'gb18030', 'gb18030',
);
method NORMALIZE_ENCODING(Str:D \encoding) {
nqp::ifnull(
nqp::atkey($encodings,encoding),
nqp::ifnull(
nqp::atkey($encodings,nqp::lc(encoding)),
nqp::lc(encoding)
)
)
}
# 1 if all elements of given type, otherwise 0
method ALL_TYPE(\values,\type) {
nqp::if(
(my int $elems = values.elems), # reifies
nqp::stmts(
(my $values := nqp::getattr(values,List,'$!reified')),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems)
&& nqp::istype(nqp::atpos($values,$i),type),
nqp::null
),
nqp::iseq_i($i,$elems)
)
)
}
# 1 if all elems defined && type, otherwise 0
method ALL_DEFINED_TYPE(\values,\type) {
nqp::if(
(my int $elems = values.elems), # reifies
nqp::stmts(
(my $values := nqp::getattr(values,List,'$!reified')),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems)
&& nqp::istype(nqp::atpos($values,$i),type)
&& nqp::defined(nqp::atpos($values,$i)),
nqp::null
),
nqp::iseq_i($i,$elems)
)
)
}
# 1 if any element of defined && type, otherwise 0
method ANY_DEFINED_TYPE(\values,\type) {
nqp::if(
(my int $elems = values.elems), # reifies
nqp::stmts(
(my $values := nqp::getattr(values,List,'$!reified')),
(my int $i = -1),
nqp::until(
nqp::iseq_i(($i = nqp::add_i($i,1)),$elems)
|| (nqp::istype(nqp::atpos($values,$i),type)
&& nqp::defined(nqp::atpos($values,$i))),
nqp::null
),
nqp::isne_i($i,$elems)
)
)
}
method TRANSPOSE(Str:D $string, Str:D $original, Str:D $final) {
nqp::join($final,nqp::split($original,$string))
}
method TRANSPOSE-ONE(Str:D $string, Str:D $original, Str:D $final) {
nqp::if(
nqp::iseq_i((my int $index = nqp::index($string, $original)), -1),
$string,
nqp::concat(
nqp::substr($string,0,$index),
nqp::concat(
$final,
nqp::substr($string,nqp::add_i($index,nqp::chars($original)))
)
)
)
}
my constant \SHAPE-STORAGE-ROOT := do {
my Mu $root := nqp::newtype(nqp::knowhow(), 'Uninstantiable');
nqp::setparameterizer($root, -> $, $key {
my $dims := $key.elems.pred;
my $type := $key.AT-POS(1);
my $dim_type := nqp::newtype($key.AT-POS(0), 'MultiDimArray');
nqp::composetype($dim_type, nqp::hash('array',
nqp::hash('dimensions', $dims, 'type', $type)));
nqp::settypehll($dim_type, 'perl6');
$dim_type
});
nqp::settypehll($root, 'perl6');
$root
}
method SHAPED-ARRAY-STORAGE(\spec, Mu \meta-obj, Mu \type) {
nqp::stmts(
(my $types := nqp::list(meta-obj)), # meta + type of each dimension
(my $dims := nqp::list_i), # elems per dimension
nqp::if(
nqp::istype(spec,List),
nqp::stmts( # potentially more than 1 dim
(my $spec := nqp::getattr(nqp::decont(spec),List,'$!reified')),
(my int $elems = nqp::elems($spec)),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
nqp::if(
nqp::istype((my $dim := nqp::atpos($spec,$i)),Whatever),
X::NYI.new(feature => 'Jagged array shapes').throw,
nqp::if(
nqp::istype(($dim := nqp::decont($dim.Int)),Failure),
$dim.throw,
nqp::if(
nqp::isbig_I($dim) || nqp::isle_i($dim,0),
X::IllegalDimensionInShape.new(:$dim).throw,
nqp::stmts(
nqp::push($types,type),
nqp::push_i($dims,$dim)
)
)
)
)
)
),
nqp::stmts( # only 1 dim
nqp::push($types,type),
nqp::push_i($dims,spec.Int)
)
),
nqp::setdimensions(
nqp::create(nqp::parameterizetype(SHAPE-STORAGE-ROOT,$types)),
$dims
)
)
}
our role ImplementationDetail {
method new(|) { die self.gist }
method gist(--> Str:D) {
"The '{self.^name}' class is a Rakudo-specific
implementation detail and has no serviceable parts inside"
}
method Str( --> Str:D) { self.gist }
method perl(--> Str:D) { self.gist }
}
our role ShapedArrayCommon {
method !illegal($operation) {
X::IllegalOnFixedDimensionArray.new(:$operation).throw
}
proto method pop(::?CLASS:D: |) { self!illegal("pop") }
proto method shift(::?CLASS:D: |) { self!illegal("shift") }
proto method splice(::?CLASS:D: |) { self!illegal("splice") }
proto method push(|c) is nodal {
self.DEFINITE ?? self!illegal("push") !! self.Any::push(|c)
}
proto method append(|c) is nodal {
self.DEFINITE ?? self!illegal("append") !! self.Any::append(|c)
}
proto method unshift(|c) is nodal {
self.DEFINITE ?? self!illegal("unshift") !! self.Any::unshift(|c)
}
proto method prepend(|c) is nodal {
self.DEFINITE ?? self!illegal("prepend") !! self.Any::prepend(|c)
}
proto method STORE(::?CLASS:D: |) {*}
multi method STORE(::?CLASS:D: Slip:D \slip) {
nqp::eqaddr(slip,Empty)
?? X::AdHoc.new( payload => "Cannot Empty a shaped array as its size is fixed").throw
!! self.STORE(slip.List)
}
# illegal unless overridden for 1dimmed case
method reverse(::?CLASS:D: |) { self!illegal("reverse") }
method rotate(::?CLASS:D: |) { self!illegal("rotate") }
multi method values(::?CLASS:D:) { Seq.new(self.iterator) }
multi method keys(::?CLASS:D:) {
Seq.new(Rakudo::Iterator.ShapeIndex(self.shape))
}
multi method invert(::?CLASS:D:) {
Seq.new(Rakudo::Iterator.Invert(self.pairs.iterator))
}
# These work on the flat view
method roll(|c) { self.flat.roll(|c) }
method pick(|c) { self.flat.pick(|c) }
method permutations(|c) { self.flat.permutations(|c) }
method combinations(|c) { self.flat.combinations(|c) }
method join(|c) { self.flat.join(|c) }
method sort(|c) { self.flat.sort(|c) }
multi method gist(::?CLASS:D:) {
self.gistseen('Array', { self!gist(nqp::create(Array),self.shape) })
}
method !gist(@path, @dims) {
if @dims.elems == 1 {
'[' ~ (^@dims[0]).map({ self.AT-POS(|@path, $_).gist }).join(' ') ~ ']';
}
else {
my @nextdims = @dims[1..^@dims.elems];
'[' ~ (^@dims[0]).map({ self!gist((flat @path, $_), @nextdims) }).join(' ') ~ ']';
}
}
multi method perl(::?CLASS:D \SELF:) {
SELF.perlseen('Array', {
self.^name
~ '.new(:shape'
~ nqp::decont(self.shape).perl
~ ', '
~ self!perl(nqp::create(Array), self.shape)
~ ')'
~ (nqp::iscont(SELF) ?? '.item' !! '')
})
}
method !perl(@path, @dims) {
if @dims.elems == 1 {
'[' ~
(^@dims[0]).map({ nqp::decont(self.AT-POS(|@path, $_)).perl }).join(', ') ~
',' x (@dims[0] == 1 && nqp::istype(self.AT-POS(|@path, 0), Iterable)) ~
']'
}
else {
my @nextdims = @dims[1..^@dims.elems];
'[' x (@path.elems > 0) ~
(^@dims[0]).map({ self!perl((flat @path, $_), @nextdims) }).join(', ') ~
',' x (@dims[0] == 1) ~
']' x (@path.elems > 0)
}
}
multi method Slip() {
Slip.from-iterator(self.iterator)
}
proto method AT-POS(|) is raw {*}
multi method AT-POS(::?CLASS:U: |c) is raw {
self.Any::AT-POS(|c)
}
multi method AT-POS(::?CLASS:D:) is raw {
die "Must specify at least one index with {self.^name}.AT-POS"
}
proto method ASSIGN-POS(|) {*}
multi method ASSIGN-POS(::?CLASS:U: |c) {
self.Any::ASSIGN-POS(|c)
}
multi method ASSIGN-POS(::?CLASS:D:) {
die "Must specify at least one index and a value with {self.^name}.ASSIGN-POS"
}
multi method ASSIGN-POS(::?CLASS:D: $) {
die "Must specify at least one index and a value with {self.^name}.ASSIGN-POS"
}
proto method EXISTS-POS(|) {*}
multi method EXISTS-POS(::?CLASS:U: |c) {
self.Any::EXISTS-POS(|c)
}
multi method EXISTS-POS(::?CLASS:D:) {
die "Must specify at least one index with {self.^name}.EXISTS-POS"
}
}
our class SupplySequencer {
has &!on-data-ready;
has &!on-completed;
has &!on-error;
has $!buffer;
has int $!buffer-start-seq;
has int $!done-target;
has int $!bust;
has $!lock;
submethod BUILD(
:&!on-data-ready!, :&!on-completed!, :&!on-error! --> Nil) {
$!buffer := nqp::list();
$!buffer-start-seq = 0;
$!done-target = -1;
$!bust = 0;
$!lock := Lock::Async.new;
}
method process(Mu \seq, Mu \data, Mu \err) {
$!lock.protect: {
if err {
&!on-error(err);
$!bust = 1;
}
elsif nqp::isconcrete(data) {
my int $insert-pos = seq - $!buffer-start-seq;
nqp::bindpos($!buffer, $insert-pos, data);
self!emit-events();
}
else {
$!done-target = seq;
self!emit-events();
}
}
}
method !emit-events() {
unless $!bust {
until nqp::elems($!buffer) == 0 || nqp::isnull(nqp::atpos($!buffer, 0)) {
&!on-data-ready(nqp::shift($!buffer));
$!buffer-start-seq = $!buffer-start-seq + 1;
}
if $!buffer-start-seq == $!done-target {
&!on-completed();
}
}
}
}
my int $sprintfHandlerInitialized = 0;
method initialize-sprintf-handler(--> Nil) {
class SprintfHandler {
method mine($x) { nqp::reprname($x) eq "P6opaque"; }
proto method int(|) {*}
multi method int(Mu:D \n) { n.Int }
multi method int(Mu:U \n) { n.Numeric.Int }
proto method float(|) {*}
multi method float(Numeric:D \n) { n }
multi method float(Mu \n) { n.Numeric }
}
unless $sprintfHandlerInitialized {
nqp::sprintfaddargumenthandler(SprintfHandler.new);
$sprintfHandlerInitialized = 1;
}
}
method MAYBE-GIST(Mu \thing) {
nqp::can(nqp::decont(thing), 'gist') ?? thing.gist !! thing.^name;
}
method SHORT-GIST(Mu \thing) {
my str $gist = self.MAYBE-GIST(thing);
nqp::if(
nqp::isgt_i(nqp::chars($gist), 23),
nqp::concat(nqp::substr($gist, 0, 20), '...'),
$gist);
}
method SUBSTR-START-OOR(\from,\max) {
Failure.new(X::OutOfRange.new(
:what('Start argument to substr'),
:got(from.gist),
:range("0.." ~ max),
:comment( nqp::istype(from, Callable) || -from > max
?? ''
!! "use *-{abs from} if you want to index relative to the end"),
))
}
method SUBSTR-CHARS-OOR(\chars) {
Failure.new(X::OutOfRange.new(
:what('Number of characters argument to substr'),
:got(chars.gist),
:range<0..^Inf>,
:comment("use *-{abs chars} if you want to index relative to the end"),
))
}
my $IS-WIN = do {
my str $os = Rakudo::Internals.TRANSPOSE(nqp::lc(
#?if jvm
nqp::atkey(nqp::jvmgetproperties,'os.name')
#?endif
#?if !jvm
nqp::atkey(nqp::backendconfig,'osname')
#?endif
)," ","");
nqp::hllbool(
nqp::iseq_s($os,'mswin32')
|| nqp::iseq_s($os,'mingw')
|| nqp::iseq_s($os,'msys')
|| nqp::iseq_s($os,'cygwin')
)
}
method IS-WIN() { $IS-WIN }
method NUMERIC-ENV-KEY(\key) {
%*ENV.EXISTS-KEY(key)
?? %*ENV.AT-KEY(key)
?? +%*ENV.AT-KEY(key)
!! 0
!! Nil
}
method error-rcgye() { # red clear green yellow eject
self.NUMERIC-ENV-KEY("RAKUDO_ERROR_COLOR") // !self.IS-WIN
?? ("\e[31m", "\e[0m", "\e[32m", "\e[33m", "\x[23CF]")
!! ("", "", "", "", "<HERE>");
}
my num $init-time-num = nqp::time_n;
method INITTIME() is raw { $init-time-num }
#?if moar
my $init-thread := nqp::currentthread();
method INITTHREAD() { $init-thread }
#?endif
my $escapes := nqp::hash(
"\0", '\0',
'$', '\$',
'@', '\@',
'%', '\%',
'&', '\&',
'{', '\{',
"\b", '\b',
"\x0A", '\n',
"\r", '\r',
"\t", '\t',
'"', '\"',
'\\', '\\\\',
);
method PERLIFY-STR(Str \string) {
sub char-to-escapes(Str $char) is pure {
#?if !jvm
'\x[' ~ $char.NFC.list.map({.base: 16}).join(',') ~ ']'
#?endif
#?if jvm
'\x[' ~ $char.ord.base(16) ~ ']'
#?endif
}
# Under NFG-supporting implementations, must be sure that any leading
# combiners are escaped, otherwise they will be combined onto the "
# under concatenation closure, which ruins round-tripping. Also handle
# the \r\n grapheme correctly.
my str $to-escape = nqp::unbox_s(string);
return '' if nqp::isnull_s($to-escape); # nothing to escape
my str $escaped = '';
my int $chars = nqp::chars($to-escape);
my int $i = -1;
while ($i = $i + 1) < $chars {
my str $char = nqp::substr($to-escape, $i, 1);
#?if !jvm
my int $ord = nqp::ord($char);
$escaped ~= nqp::isge_i($ord,256)
&& +uniprop-str($ord,'Canonical_Combining_Class')
?? char-to-escapes($char)
!! nqp::iseq_s($char,"\r\n") ?? '\r\n' !!
#?endif
#?if jvm
$escaped ~=
#?endif
nqp::existskey($escapes,$char)
?? nqp::atkey($escapes,$char)
!! nqp::iscclass(nqp::const::CCLASS_PRINTING,$char,0)
?? $char
!! char-to-escapes($char);
}
$escaped
}
# easy access to compile options
my Mu $compiling-options := %*COMPILING ?? nqp::atkey(%*COMPILING, '%?OPTIONS') !! nqp::hash();
# running with --ll-exception
method LL-EXCEPTION() {
nqp::existskey($compiling-options, 'll-exception')
?? '--ll-exception'
!! Empty
}
# running with --profile
method PROFILE() {
nqp::existskey($compiling-options, 'profile')
?? '--profile'
!! Empty
}
# running with --optimize=X
method OPTIMIZE() {
nqp::existskey($compiling-options, 'optimize')
?? '--optimize=' ~ nqp::atkey($compiling-options, 'optimize')
!! Empty
}
# whatever specified with -I
method INCLUDE() {
nqp::existskey($compiling-options,'I')
?? do {
my $I := nqp::atkey($compiling-options,'I');
nqp::islist($I) ?? $I !! nqp::list($I)
}
!! nqp::list()
}
#?if moar
method PRECOMP-EXT(--> "moarvm") { }
method PRECOMP-TARGET(--> "mbc") { }
#?endif
#?if jvm
method PRECOMP-EXT( --> "jar") { }
method PRECOMP-TARGET(--> "jar") { }
#?endif
#?if js
method PRECOMP-EXT( --> "js") { }
method PRECOMP-TARGET(--> "js") { }
#?endif
method get-local-timezone-offset() {
my $utc := time;
my Mu $fia := nqp::decodelocaltime(nqp::unbox_i($utc));
DateTime.new(
nqp::atpos_i($fia,5), # year
nqp::atpos_i($fia,4), # month
nqp::atpos_i($fia,3), # day
nqp::atpos_i($fia,2), # hour
nqp::atpos_i($fia,1), # minute
nqp::atpos_i($fia,0), # second
).posix(True) - $utc;
}
# Keep track of the differences between TAI and UTC for internal use.
# The "BEGIN" and "END" comments are for tools/update-tai-utc.pl.
#
# Some handy tables:
# http://tf.nist.gov/pubs/bulletin/leapsecond.htm
# http://hpiers.obspm.fr/eop-pc/earthor/utc/TAI-UTC_tab.html
my int constant $initial-offset = 10;
# TAI - UTC at the Unix epoch (1970-01-01T00:00:00Z).
#?if !js
my constant $dates = nqp::list_s(
#?endif
#?if js
my $dates := nqp::list_s(
#?endif
#BEGIN leap-second-dates
'1972-06-30',
'1972-12-31',
'1973-12-31',
'1974-12-31',
'1975-12-31',
'1976-12-31',
'1977-12-31',
'1978-12-31',
'1979-12-31',
'1981-06-30',
'1982-06-30',
'1983-06-30',
'1985-06-30',
'1987-12-31',
'1989-12-31',
'1990-12-31',
'1992-06-30',
'1993-06-30',
'1994-06-30',
'1995-12-31',
'1997-06-30',
'1998-12-31',
'2005-12-31',
'2008-12-31',
'2012-06-30',
'2015-06-30',
'2016-12-31',
#END leap-second-dates
);
# our %leap-seconds =
# @leap-second-dates Z=> $initial-offset + 1 .. *;
# So for any date $d in @leap-second-dates, $d 23:59:00 UTC
# is the leap second that made (or will make) UTC
# %leap-seconds{$d} seconds behind TAI.
# Ambiguous POSIX times.
#?if !js
my constant $posixes = nqp::list_i(
#?endif
#?if js
my $posixes := nqp::list_i(
#?endif
#BEGIN leap-second-posix
78796800,
94694400,
126230400,
157766400,
189302400,
220924800,
252460800,
283996800,
315532800,
362793600,
394329600,
425865600,
489024000,
567993600,
631152000,
662688000,
709948800,
741484800,
773020800,
820454400,
867715200,
915148800,
1136073600,
1230768000,
1341100800,
1435708800,
1483228800,
#END leap-second-posix
);
#?if !js
my int constant $elems = nqp::elems($dates);
#?endif
#?if js
my int $elems = nqp::elems($dates);
#?endif
method is-leap-second-date(\date) {
nqp::hllbool(
nqp::stmts(
(my str $date = date),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems)
&& nqp::isgt_s($date,nqp::atpos_s($dates,$i)),
nqp::null
),
nqp::islt_i($i,$elems) && nqp::iseq_s($date,nqp::atpos_s($dates,$i))
)
)
}
method tai-from-posix(\posix, int $prefer-leap-second) {
nqp::stmts(
(my int $p = posix.floor),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems)
&& nqp::isgt_i($p,nqp::atpos_i($posixes,$i)),
nqp::null
),
posix + nqp::add_i(
nqp::add_i($initial-offset,$i),
nqp::islt_i($i,$elems)
&& nqp::not_i($prefer-leap-second)
&& nqp::iseq_i($p,nqp::atpos_i($posixes,$i))
)
)
}
method posix-from-tai(\tai) {
nqp::stmts(
(my int $t = tai.floor - $initial-offset),
(my int $i = -1),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems)
&& nqp::islt_i(nqp::atpos_i($posixes,$i),nqp::sub_i($t,$i)),
nqp::null
),
(tai - nqp::add_i($initial-offset,$i),
nqp::hllbool(
nqp::islt_i($i,$elems)
&& nqp::iseq_i(nqp::atpos_i($posixes,$i),nqp::sub_i($t,$i))
)
)
)
}
my $initializers;
#nqp::print("running mainline\n");
#method INITIALIZERS() { $initializers }