Skip to content

Commit

Permalink
Implement Str.parse-names
Browse files Browse the repository at this point in the history
Functionality:
- similar to "\c[BELL, BLACK HEART SUIT]", except can be used by
    users at runtime, without requiring EVAL/nqp in user's code
- Unlike \c[…] does not allow comments or anything similarly isoteric.
    The idea is this will process some sort of user input, so we want
    it just as liberal as necesary (whitespace around char names is allowed).

Naming:
- the name follows Str.parse-base that parses a string containing numerals
    in some base; whereas this routine parses a string of character names
  • Loading branch information
zoffixznet committed Mar 2, 2017
1 parent 164e393 commit 5c1761a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/core/Exception.pm
Expand Up @@ -1810,6 +1810,14 @@ my class X::Phaser::PrePost is Exception {
}
}

my class X::Str::InvalidCharName is Exception {
has $.name;
method message() {
$!name.chars ?? "Unrecognized character name [{$!name}]"
!! "Cannot use empty name as character name"
}
}

my class X::Str::Numeric is Exception {
has $.source;
has $.pos;
Expand Down
21 changes: 21 additions & 0 deletions src/core/Str.pm
@@ -1,6 +1,7 @@
my class Cursor {... }
my class Range {... }
my class Match {... }
my class X::Str::InvalidCharName { ... }
my class X::Str::Numeric { ... }
my class X::Str::Match::x { ... }
my class X::Str::Subst::Adverb { ... }
Expand Down Expand Up @@ -1353,6 +1354,24 @@ my class Str does Stringy { # declared in BOOTSTRAP
}
}

method parse-names(Str:D:) {
my \names := nqp::split(',', self);
my int $elems = nqp::elems(names);
my int $i = -1;
my str $res = '';
nqp::while(
nqp::islt_i( ($i = nqp::add_i($i,1)), $elems ),
($res = nqp::concat($res,
nqp::unless(
nqp::getstrfromname(nqp::atpos(names, $i).trim),
X::Str::InvalidCharName.new(
:name(nqp::atpos(names, $i).trim)
).fail
))),
);
$res
}

multi method split(Str:D: Regex:D $pat, $limit is copy = Inf;;
:$v is copy, :$k, :$kv, :$p, :$skip-empty) {

Expand Down Expand Up @@ -2972,6 +2991,8 @@ sub chrs(*@c) returns Str:D {
proto sub parse-base(|) { * }
multi sub parse-base(Str:D $str, Int:D $radix) { $str.parse-base($radix) }

sub parse-names(Str:D $str) { $str.parse-names }

proto sub substr(|) { * }
multi sub substr(Str:D \what, Int:D \start) {
my str $str = nqp::unbox_s(what);
Expand Down
1 change: 1 addition & 0 deletions t/spectest.data
Expand Up @@ -1089,6 +1089,7 @@ S32-str/numeric.t
S32-str/ords.t
S32-str/pack.t
S32-str/parse-base.t
S32-str/parse-names.t
S32-str/pos.t
S32-str/rindex.t
S32-str/samemark.t
Expand Down

0 comments on commit 5c1761a

Please sign in to comment.