Sidef/Types/Block/Block.pm untested

filter: Statementstmt n/a Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a SCAR -
1 package Sidef::Types::Block::Block;
2  
3 use utf8;
4 use 5.016;
5 use parent qw(Sidef::Object::Object);
6  
7 use List::Util qw();
8 use Scalar::Util qw();
9 use Sidef::Types::Number::Number;
10  
11 use overload
12 q{bool} => sub { 1 },
13 q{&{}} => sub { $_[0]->{code} },
14 q{""} => sub {
15 my ($self) = @_;
16  
17 my $name = $self->_name;
18 my $addr = Scalar::Util::refaddr($self);
19  
20 my @vars = map {
21 my $v = $_;
22 my $str = defined($v->{type}) ? Sidef::normalize_type($v->{type}) . ' ' : '';
23 $str .= $v->{slurpy} ? ($v->{array} ? '*' : ':') : '';
24 $str .= Sidef::normalize_type($v->{name});
25 $str .= defined($v->{subset}) ? ' < ' . Sidef::normalize_type($v->{subset}) : '';
26 $str .= $v->{has_value} ? ' = nil' : '';
27 $str;
28 } @{$self->{vars} // []};
29  
30 my $sig = @vars ? join(', ', @vars) : '';
31  
32 my $prefix =
33 $self->{type} eq 'block'
34 ? '{' . ($sig ? "|$sig|" : '')
35 : "func ($sig) {";
36  
37 return "$prefix #`($name|$addr) ... }";
38 };
39  
40 sub _name {
41 my ($self) = @_;
42 $self->{_name} //= do {
43 my $prefix =
44 exists($self->{class}) ? "$self->{class}."
45 : exists($self->{namespace}) ? "$self->{namespace}::"
46 : '';
47 Sidef::normalize_type($prefix . ($self->{name} // '__FUNC__'));
48 };
49 }
50  
51 sub new {
52 my (undef, %opt) = @_;
53  
54 bless {
55 name => '__BLOCK__',
56 type => 'block',
57 %opt
58 },
59 __PACKAGE__;
60 }
61  
62 #<<<
63 use constant {
64 IDENTITY => __PACKAGE__->new(is_identity => 1, name => 'Block.IDENTITY', code => sub { $_[0] }),
65 NULL_IDENTITY => __PACKAGE__->new(is_identity => 1, name => 'Block.NULL_IDENTITY', code => sub { }),
66 LIST_IDENTITY => __PACKAGE__->new(is_identity => 1, name => 'Block.LIST_IDENTITY', code => sub { (@_) }),
67 ARRAY_IDENTITY => __PACKAGE__->new(is_identity => 1, name => 'Block.ARRAY_IDENTITY', code => sub { Sidef::Types::Array::Array->new(@_) }),
68 };
69 #>>>
70  
71 sub identity { IDENTITY }
72 sub list_identity { LIST_IDENTITY }
73 sub array_identity { ARRAY_IDENTITY }
74 sub null_identity { NULL_IDENTITY }
75  
76 sub is_identity {
77 $_[0]->{is_identity}
78 ? Sidef::Types::Bool::Bool::TRUE
79 : Sidef::Types::Bool::Bool::FALSE;
80 }
81  
82 sub run {
83  
84 # Handle function calls
85 if ($_[0]->{type} eq 'func') {
86 return shift(@_)->call(@_);
87 }
88  
89 goto shift(@_)->{code};
90 }
91  
92 *do = \&run;
93  
94 sub curry {
95 my ($self, @args) = @_;
96 __PACKAGE__->new(code => sub { $self->call(@args, @_) });
97 }
98  
99 sub negate {
100 my ($self) = @_;
101 __PACKAGE__->new(
102 code => sub {
103 $self->run(@_)
104 ? Sidef::Types::Bool::Bool::FALSE
105 : Sidef::Types::Bool::Bool::TRUE;
106 }
107 );
108 }
109  
110 sub pipe {
111 my ($block1, $block2) = @_;
112 __PACKAGE__->new(code => sub { $block2->call($block1->call(@_)) });
113 }
114  
115 sub once {
116 my ($self) = @_;
117 my ($called, $result);
118 __PACKAGE__->new(
119 code => sub {
120 $called and return $result;
121 $called = 1;
122 $result = $self->run(@_);
123 }
124 );
125 }
126  
127 sub constant {
128 my (undef, $value) = @_;
129 __PACKAGE__->new(code => sub { $value });
130 }
131  
132 sub retry {
133 my ($self, $n) = @_;
134 $n = CORE::int($n // 1);
135 __PACKAGE__->new(
136 code => sub {
137 my @args = @_;
138 my $attempts = 0;
139 my $result;
140 while (1) {
141 $result = eval { $self->call(@args) };
142 last unless $@;
143 ++$attempts;
144 $attempts >= $n and die $@;
145 }
146 $result;
147 }
148 );
149 }
150  
151 # Recursively walks the ISA hierarchy to discover additional method candidates
152 # from parent classes, appending them (with their kids/fallback) to @$methods.
153 sub _collect_inherited_methods {
154 my ($self, $methods) = @_;
155  
156 my $limit = 4096;
157 my %visited;
158  
159 sub {
160 my ($block) = @_;
161  
162 my $name = $block->{name};
163 my @isa = do {
164 no strict 'refs';
165 @{$block->{class} . '::ISA'};
166 };
167  
168 foreach my $class (@isa) {
169 next if $visited{$class}++;
170 substr($class, 0, 14) eq 'Sidef::Runtime' or next;
171  
172 my $method = do {
173 no strict 'refs';
174 ${$class . '::__SIDEF_CLASS_METHODS__'}{$name};
175 };
176  
177 defined($method) or next;
178  
179 push @$methods, $method;
180 push @$methods, @{$method->{kids}} if exists $method->{kids};
181 push @$methods, $method->{fallback} if exists $method->{fallback};
182  
183 if (--$limit == 0) {
184 die "[ERROR] Too deep or cyclic class inheritance!";
185 }
186  
187 __SUB__->($method);
188 }
189 }
190 ->($self);
191 }
192  
193 # Builds the full list of candidate methods: self, kids, fallback, and any
194 # candidates found by walking the class inheritance hierarchy.
195 sub _collect_candidate_methods {
196 my ($self) = @_;
197  
198 my @methods = ($self);
199  
200 if (exists $self->{kids}) {
201 push @methods, @{$self->{kids}};
202 }
203  
204 if (exists $self->{fallback}) {
205 push @methods, $self->{fallback};
206 }
207  
208 if (defined $self->{class} and defined $self->{name}) {
209 $self->_collect_inherited_methods(\@methods);
210 }
211  
212 return @methods;
213 }
214  
215 # Validates type and subset constraints for each parameter and assembles the
216 # final positional argument list for the call. Returns an \@pos_args arrayref,
217 # or undef if any constraint check fails.
218 sub _build_pos_args {
219 my ($method, $seen, $vars) = @_;
220  
221 my @pos_args;
222  
223 foreach my $var (@$vars) {
224 if (exists($var->{type}) or exists($var->{subset})) {
225  
226 if (exists $seen->{$var->{name}}) {
227 my $value = $seen->{$var->{name}};
228  
229 if (exists $var->{type}) {
230 (ref($value) eq $var->{type} or UNIVERSAL::isa($value, $var->{type}))
231 or return undef;
232  
233 if (exists $var->{where_block}) {
234 $var->{where_block}($value) or return undef;
235 }
236 elsif (exists $var->{where_expr}) {
237 $value eq $var->{where_expr} or return undef;
238 }
239 }
240  
241 if (exists $var->{subset}) {
242 if (UNIVERSAL::isa($var->{subset}, 'Sidef::Object::Object')) {
243 UNIVERSAL::isa($var->{subset}, ref($value)) or return undef;
244 }
245  
246 if (exists $var->{where_block}) {
247 $var->{where_block}($value) or return undef;
248 }
249 elsif (exists $var->{where_expr}) {
250 $value eq $var->{where_expr} or return undef;
251 }
252  
253 my $sub = UNIVERSAL::can($var->{subset}, '__subset_validation__');
254 ($sub ? $sub->($value) : 1) or return undef;
255 }
256  
257 push @pos_args, $value;
258 }
259 elsif (exists $var->{has_value}) {
260 push @pos_args, undef;
261 }
262 else {
263 return undef;
264 }
265  
266 }
267 elsif (exists $seen->{$var->{name}}) {
268  
269 if (exists($var->{where_block})) {
270 my $value =
271 exists($var->{slurpy})
272 ? Sidef::Types::Array::Array->new([@{$seen->{$var->{name}}}])
273 : $seen->{$var->{name}};
274  
275 if (exists $var->{where_block}) {
276 $var->{where_block}($value) or return undef;
277 }
278 }
279 elsif (exists $var->{where_expr}) {
280 $var->{where_expr} eq $seen->{$var->{name}} or return undef;
281 }
282  
283 push @pos_args, exists($var->{slurpy})
284 ? @{$seen->{$var->{name}}}
285 : $seen->{$var->{name}};
286 }
287 elsif (exists $var->{slurpy}) {
288 ## ok - slurpy with no args supplied is valid
289 }
290 elsif (exists $var->{has_value}) {
291 push @pos_args, undef;
292 }
293 else {
294 return undef;
295 }
296 }
297  
298 return \@pos_args;
299 }
300  
301 # Partitions @$args into named and positional arguments, then binds them to the
302 # method's parameter list in order. Returns a \%seen hashref mapping variable
303 # names to their bound values, or undef if the method signature does not match.
304 sub _resolve_args {
305 my ($self, $method, $args, $vars) = @_;
306  
307 my $table = $self->{table};
308 my %seen;
309 my @left_args;
310  
311 # Separate named params from positional args, validating named params exist.
312 foreach my $arg (@$args) {
313 if (ref($arg) eq 'Sidef::Variable::NamedParam') {
314 exists($table->{$arg->{name}}) or return undef;
315 my $info = $vars->[$table->{$arg->{name}}];
316 $seen{$arg->{name}} =
317 exists($info->{slurpy})
318 ? $arg->{value}
319 : $arg->{value}[-1];
320 }
321 else {
322 push @left_args, $arg;
323 }
324 }
325  
326 # Bind remaining positional args to unbound parameters, in declaration order.
327 foreach my $var (@$vars) {
328 next if exists $seen{$var->{name}};
329 last unless @left_args;
330  
331 if (exists $var->{slurpy}) {
332 $seen{$var->{name}} = [splice(@left_args)];
333 last;
334 }
335 else {
336 $seen{$var->{name}} = shift(@left_args);
337 }
338 }
339  
340 # Any leftover positional args mean this method does not match.
341 return undef if @left_args;
342  
343 return \%seen;
344 }
345  
346 # Main entry point: finds and dispatches to the first matching method candidate.
347 sub _multiple_dispatch {
348 my ($self, @args) = @_;
349  
350 my @methods = $self->_collect_candidate_methods;
351  
352 foreach my $method (@methods) {
353  
354 if ($method->{type} eq 'block') {
355 return ($method, $method->{code}(@args));
356 }
357  
358 my $vars = exists($method->{vars}) ? $method->{vars} : [];
359 my $seen = $self->_resolve_args($method, \@args, $vars) // next;
360 my $pos_args = _build_pos_args($method, $seen, $vars) // next;
361  
362 return ($method, $method->{code}->(@$pos_args));
363 }
364  
365 _dispatch_error($self, \@methods, \@args);
366 }
367  
368 # Returns the display type string for an argument (used in the error header line).
369 sub _arg_type_str {
370 my ($arg) = @_;
371 return
372 ref($arg) ? Sidef::normalize_type(ref($arg))
373 : defined($arg) ? Sidef::normalize_type($arg)
374 : 'nil';
375 }
376  
377 # Returns the display value string for an argument (used in the "invoked as" line).
378 sub _arg_value_str {
379 my ($arg) = @_;
380 return
381 ref($arg) && UNIVERSAL::can($arg, 'dump') ? $arg->dump
382 : ref($arg) ? Sidef::normalize_type(ref($arg))
383 : defined($arg) ? Sidef::normalize_type($arg)
384 : 'nil';
385 }
386  
387 # Formats a single parameter's signature fragment, e.g. "*SomeType varname < SubType".
388 sub _param_str {
389 my ($var) = @_;
390 return
391 (exists($var->{slurpy}) ? '*' : '')
392 . (exists($var->{type}) ? Sidef::normalize_type($var->{type}) . ' ' : '')
393 . $var->{name}
394 . (exists($var->{subset}) ? ' < ' . Sidef::normalize_type($var->{subset}) : '');
395 }
396  
397 # Formats a complete method signature string, e.g. "methodName(TypeA a, *B b)".
398 sub _method_signature_str {
399 my ($method) = @_;
400 my @params = map { _param_str($_) } @{$method->{vars} // []};
401 return $method->_name . '(' . join(', ', @params) . ')';
402 }
403  
404 # Dies with a detailed message describing the failed dispatch and all candidates.
405 sub _dispatch_error {
406 my ($self, $methods, $args) = @_;
407  
408 my $name = $self->_name;
409 my $arg_types = join(', ', map { _arg_type_str($_) } @$args);
410 my $arg_values = join(', ', map { _arg_value_str($_) } @$args);
411 my $candidates = join("\n ", map { _method_signature_str($_) } @$methods);
412  
413 die "[ERROR] $self->{type} `$name` does not match $name($arg_types)"
414 . ", invoked as $name($arg_values)"
415 . "\n\nPossible candidates are: "
416 . "\n "
417 . $candidates . "\n\n";
418 }
419  
420 sub call {
421 my ($block, @args) = @_;
422  
423 # Fast block call routing
424 if ($block->{type} eq 'block') {
425 shift @_;
426 goto $block->{code};
427 }
428  
429 my ($self, @objs) = $block->_multiple_dispatch(@args);
430  
431 # Check the return types
432 if (exists $self->{returns}) {
433  
434 if ($#{$self->{returns}} != $#objs) {
435 die sprintf("[ERROR] Wrong number of return values from %s `%s`: got %d, but expected %d\n",
436 $self->{type}, $self->_name, scalar(@objs), scalar(@{$self->{returns}}));
437 }
438  
439 foreach my $i (0 .. $#{$self->{returns}}) {
440 my $ret_type = $self->{returns}[$i];
441 if (!(ref($objs[$i]) eq $ret_type or UNIVERSAL::isa($objs[$i], $ret_type))) {
442 die sprintf("[ERROR] Invalid return-type for value[%d] from %s `%s`: got `%s`, but expected `%s`\n",
443 $i, $self->{type}, $self->_name,
444 Sidef::normalize_type(ref($objs[$i])),
445 Sidef::normalize_type($ret_type));
446 }
447 }
448 }
449  
450 wantarray ? @objs : $objs[-1];
451 }
452  
453 {
454 my $ref = \&UNIVERSAL::AUTOLOAD;
455  
456 sub get_value {
457 my ($self) = @_;
458 sub {
459 my @args = @_;
460 local *UNIVERSAL::AUTOLOAD = $ref;
461 if (defined($a) or defined($b)) { push @args, $a, $b }
462 elsif (defined($_)) { unshift @args, $_ }
463 $self->call(map { Sidef::Types::Perl::Perl->to_sidef($_) } @args);
464 };
465 }
466 }
467  
468 sub capture {
469 my ($self) = @_;
470  
471 open my $str_h, '>:utf8', \my $str;
472 if (defined(my $old_h = select($str_h))) {
473 $self->run();
474 close $str_h;
475 select $old_h;
476 }
477  
478 Sidef::Types::String::String->new($str)->decode_utf8;
479 }
480  
481 *cap = \&capture;
482  
483 sub compose {
484 my ($block1, $block2) = @_;
485 __PACKAGE__->new(
486 code => sub {
487 $block1->call($block2->call(@_));
488 }
489 );
490 }
491  
492 sub repeat {
493 my ($block, $num) = @_;
494  
495 if (ref($num) eq __PACKAGE__) {
496 goto &compose;
497 }
498  
499 $num->times($block);
500 }
501  
502 sub nest {
503 my ($block, $num, $value) = @_;
504  
505 $value //= Sidef::Types::Number::Number::ZERO;
506  
507 foreach my $i (1 .. CORE::int($num)) {
508 $value = $block->run($value);
509 }
510  
511 $value;
512 }
513  
514 sub exec {
515 my ($self, @args) = @_;
516 $self->run(@args);
517 $self;
518 }
519  
520 sub while {
521 my ($self, $condition) = @_;
522  
523 while ($condition->run) {
524 $self->run;
525 }
526  
527 $self;
528 }
529  
530 sub loop {
531 my ($self) = @_;
532  
533 while (1) {
534 $self->run;
535 }
536  
537 $self;
538 }
539  
540 sub if {
541 my ($self, $bool) = @_;
542 $bool ? $self->run : $bool;
543 }
544  
545 sub __fdump {
546 my ($self, $obj) = @_;
547  
548 my $ref = ref($obj);
549  
550 if ($ref eq 'Sidef::Types::Number::Number') {
551 my ($type, $str) = $obj->_dump();
552 return
553 scalar {
554 dump => $type eq 'int'
555 ? "${ref}::_set_int('${str}')"
556 : "${ref}::_set_str('${type}', '${str}')"
557 };
558 }
559  
560 if ($ref eq 'Sidef::Module::OO' or $ref eq 'Sidef::Module::Func') {
561  
562 my $module =
563 ref($obj->{module})
564 ? Data::Dump::Filtered::dump_filtered($obj->{module}, __SUB__)
565 : qq{"$obj->{module}"};
566  
567 my $module_name = ref($obj->{module}) || $obj->{module};
568 return scalar {dump => qq{do { use $ref; eval "require $module_name"; bless({ module => $module }, "$ref"); }}};
569 }
570  
571 die "[ERROR] Blocks cannot be serialized!" if $ref eq 'Sidef::Types::Block::Block';
572 return;
573 }
574  
575 sub ffork {
576 my ($self, @args) = @_;
577  
578 state $x = require Data::Dump::Filtered;
579 open(my $fh, '+>', undef); # an anonymous temporary file
580 my $fork = Sidef::Types::Block::Fork->new(fh => $fh);
581  
582 # Try to fork
583 my $pid = fork() // die "[ERROR] Cannot fork";
584  
585 if ($pid == 0) {
586 srand();
587 my @objs = ($self->call(@args));
588 print $fh scalar Data::Dump::Filtered::dump_filtered(@objs, \&__fdump);
589 exit 0;
590 }
591  
592 $fork->{pid} = $pid;
593 $fork;
594 }
595  
596 *start = \&ffork;
597  
598 sub fork {
599 my ($self, @args) = @_;
600  
601 my $fork = Sidef::Types::Block::Fork->new();
602  
603 my $pid = CORE::fork() // die "[ERROR] Cannot fork: $!";
604 if ($pid == 0) {
605 srand();
606 $self->call(@args);
607 exit 0;
608 }
609  
610 $fork->{pid} = $pid;
611 $fork;
612 }
613  
614 sub thread {
615 my ($self, @args) = @_;
616 state $x = do {
617 eval { require forks; } // require threads;
618 *threads::get = \&threads::join;
619 *threads::wait = \&threads::join;
620 1;
621 };
622 Sidef::Module::OO->__NEW__(threads->create({'context' => 'list', 'exit' => 'thread_only'}, sub { $self->call(@args) }));
623 }
624  
625 *thr = \&thread;
626  
627 sub _iterate {
628 my ($callback, @objs) = @_;
629  
630 foreach my $obj (@objs) {
631  
632 $obj // last;
633  
634 my $sub = (ref($obj) && UNIVERSAL::can($obj, 'iter')) || do {
635 my $arr = eval { ref($obj) ? $obj->to_a : Sidef::Types::Array::Array->new($obj) };
636 ref($arr) ? do { $obj = $arr; UNIVERSAL::can($obj, 'iter') } : undef;
637 };
638  
639 my $break;
640 my $iter = $sub ? $sub->($obj) : $obj->iter;
641  
642 while (1) {
643 $break = 1;
644 $callback->($iter->run // do { undef $break; last });
645 undef $break;
646 }
647 return if $break; # Sidef block-exit control flow
648 }
649  
650 return 1;
651 }
652  
653 sub time {
654 my ($self) = @_;
655 require Time::HiRes;
656 my $t0 = [Time::HiRes::gettimeofday()];
657 $self->run;
658 Sidef::Types::Number::Number->new(scalar Time::HiRes::tv_interval($t0));
659 }
660  
661 sub for {
662 my ($self, @objs) = @_;
663 _iterate($self, @objs);
664 $self;
665 }
666  
667 *each = \&for;
668 *foreach = \&for;
669  
670 sub map {
671 my ($self, @objs) = @_;
672  
673 my @array;
674 _iterate(sub { push @array, $self->run(@_) }, @objs);
675 Sidef::Types::Array::Array->new(\@array);
676 }
677  
678 sub grep {
679 my ($self, @objs) = @_;
680  
681 my @array;
682 _iterate(sub { push @array, @_ if $self->run(@_) }, @objs);
683 Sidef::Types::Array::Array->new(\@array);
684 }
685  
686 sub first {
687 my ($self, $n, $range) = @_;
688  
689 state $inf_range = Sidef::Types::Number::Number->inf->range;
690  
691 $range //= $inf_range;
692  
693 my @array;
694 my $max = CORE::int($n // 1);
695  
696 _iterate(
697 sub {
698 if ($self->run(@_)) {
699 push @array, @_;
700 last if (@array >= $max);
701 }
702 },
703 $range
704 );
705  
706 defined($n)
707 ? Sidef::Types::Array::Array->new(\@array)
708 : $array[0];
709 }
710  
711 sub nth {
712 my ($self, $n, $range) = @_;
713  
714 state $inf_range = Sidef::Types::Number::Number->inf->range;
715  
716 $range //= $inf_range;
717  
718 my $k = 0;
719 my $nth = undef;
720  
721 $n = CORE::int($n);
722 $n > 0 or return undef;
723  
724 _iterate(
725 sub {
726 if ($self->run(@_) and ++$k == $n) {
727 $nth = $_[0];
728 last;
729 }
730 },
731 $range
732 );
733  
734 return $nth;
735 }
736  
737 sub sum { $_[1]->sum_by($_[0]) }
738 *Σ = \&sum;
739 sub prod { $_[1]->prod_by($_[0]) }
740 *Π = \&prod;
741  
742 sub cache {
743 my ($self) = @_;
744 $self->{is_cached} && return $self;
745 state $x = require Memoize;
746 $self->{code} = Memoize::memoize($self->{code});
747 $self->{is_cached} = 1;
748 $self;
749 }
750  
751 sub uncache {
752 my ($self) = @_;
753 $self->{is_cached} || return $self;
754 state $x = require Memoize;
755 if (defined(my $uncached = eval { Memoize::unmemoize($self->{code}) })) {
756 $self->{code} = $uncached;
757 $self->{is_cached} = 0;
758 }
759 $self;
760 }
761  
762 sub flush_cache {
763 my ($self) = @_;
764 $self->{is_cached} || return $self;
765 state $x = require Memoize;
766 eval { Memoize::flush_cache($self->{code}) };
767 $self;
768 }
769  
770 sub dump {
771 Sidef::Types::String::String->new("$_[0]");
772 }
773  
774 *to_s = \&dump;
775 *to_str = \&dump;
776  
777 {
778 no strict 'refs';
779  
780 foreach my $name (qw(bsearch bsearch_le bsearch_ge bsearch_inverse)) {
781  
782 *{__PACKAGE__ . '::' . $name} = sub {
783 my ($self, $x, $y) = @_;
784  
785 my $from = $x // Sidef::Types::Number::Number::ZERO;
786 my $upto = $y // $from->inc->mul(Sidef::Types::Number::Number::TWO);
787  
788 while (1) {
789 my $k = $from->$name($upto, $self);
790  
791 if (defined($k) and $k->is_between($from, $upto)) {
792 return $k;
793 }
794  
795 $from = $upto->inc;
796 $upto = $from->add($from);
797 }
798  
799 return Sidef::Types::Number::Number::MONE;
800 };
801 }
802  
803 *{__PACKAGE__ . '::' . '*'} = \&repeat;
804 *{__PACKAGE__ . '::' . '<<'} = \&for;
805 *{__PACKAGE__ . '::' . '>>'} = \&map;
806 *{__PACKAGE__ . '::' . '&'} = \&grep;
807 *{__PACKAGE__ . '::' . '∘'} = \&compose;
808 }
809  
810 1