Skip to content

Commit

Permalink
Move chrs() logic to List.chrs and make chrs() the gateway
Browse files Browse the repository at this point in the history
So that if you define your own .chrs method on a Foo object for some reason,
using chrs() will find the Foo.chrs.
  • Loading branch information
lizmat committed Mar 2, 2018
1 parent 85ad0eb commit 1894eac
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 25 deletions.
6 changes: 4 additions & 2 deletions src/core/Cool.pm
Expand Up @@ -117,9 +117,11 @@ my class Cool { # declared in BOOTSTRAP
method chr() {
self.Int.chr;
}
method chrs(Cool:D:) { chrs(self.list) }
method ords(Cool:D:) { self.Str.ords }

proto method chrs(|) {*}
multi method chrs(Cool:D:) { self.list.chrs }

method ords(Cool:D:) { self.Str.ords }

method flip() {
self.Str.flip
Expand Down
33 changes: 33 additions & 0 deletions src/core/List.pm
Expand Up @@ -1454,6 +1454,39 @@ my class List does Iterable does Positional { # declared in BOOTSTRAP
method pop(|) is nodal {
X::Immutable.new(:typename<List>, :method<pop>).throw
}

multi method chrs(List:D: --> Str:D) {
nqp::if(
self.is-lazy,
Failure.new(X::Cannot::Lazy.new(action => 'chrs')),
nqp::stmts(
(my int $i = -1),
(my int $elems = self.elems), # reifies
(my $result := nqp::setelems(nqp::list_s,$elems)),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
nqp::if(
nqp::istype((my $value := nqp::atpos($!reified,$i)),Int),
nqp::bindpos_s($result,$i,nqp::chr($value)),
nqp::if(
nqp::istype($value,Str),
nqp::if(
nqp::istype(($value := +$value),Failure),
(return $value),
nqp::bindpos_s($result,$i,nqp::chr($value))
),
(return Failure.new(X::TypeCheck.new(
operation => "converting element #$i to .chr",
got => $value,
expected => Int
)))
)
)
),
nqp::join("",$result)
)
)
}
}

# The , operator produces a List.
Expand Down
24 changes: 1 addition & 23 deletions src/core/Str.pm
Expand Up @@ -3122,29 +3122,7 @@ multi sub infix:<coll>(Str:D \a, Str:D \b) { die "coll NYI on JVM" }
#?endif

proto sub chrs(|) {*}
multi sub chrs(*@c --> Str:D) {
fail X::Cannot::Lazy.new(action => 'chrs') if @c.is-lazy;
my $list := nqp::getattr(@c,List,'$!reified');
my int $i = -1;
my int $elems = nqp::elems($list);
my $result := nqp::list_s;
nqp::setelems($result,$elems);

my $value;
nqp::istype(($value := nqp::atpos($list,$i)),Int)
?? nqp::bindpos_s($result,$i,nqp::chr($value))
!! nqp::istype($value, Str)
?? (nqp::istype(($value := +$value), Failure)
?? return $value
!! nqp::bindpos_s($result,$i,nqp::chr($value)))
!! fail X::TypeCheck.new(
operation => "converting element #$i to .chr",
got => $value,
expected => Int)
while nqp::islt_i(++$i,$elems);

nqp::join("",$result)
}
multi sub chrs(*@c --> Str:D) { @c.chrs }

proto sub parse-base(|) {*}
multi sub parse-base(Str:D $str, Int:D $radix) { $str.parse-base($radix) }
Expand Down

0 comments on commit 1894eac

Please sign in to comment.