Skip to content

Commit

Permalink
Make List.index|indiced|contains issue a warning
Browse files Browse the repository at this point in the history
https://docs.raku.org/language/traps#Strings_are_not_Lists,_so_beware_indexing
shows that it is a very common newbie error to use the "index",
"contains" and "indices" methods on a List, not realizing that that will
first stringify the List (because Lists are Cool).  And this *not*
give the result one expects, or in a worse case, provide false positives.

    say ("a","b").contains("ab")   # True

This commit adds 3 'List:D: Str:D \needle' candidates which should catch
this type of newbie behaviour.  Should this be intended behaviour, then
the warning can be simply circumvented by adding ",0" (aka, starting
from the first position in the string).  Or by explicitely joining the
List first.

Please revert if this is somehow deemed unnecessary or unwelcome.
  • Loading branch information
lizmat committed Jan 23, 2020
1 parent 666f95c commit c9b0218
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/core.c/Cool.pm6
Expand Up @@ -188,7 +188,15 @@ my class Cool { # declared in BOOTSTRAP
self.Str.substr-eq($needle, $pos)
}

method !list-as-string($suggestion) is hidden-from-backtrace {
warn "Calling '.{callframe(2).code.name}' on a {self.^name}, did you mean '$suggestion'?";
}

proto method contains(|) {*}
multi method contains(List:D: Str:D \needle) { # Warn about newbie trap
self!list-as-string('needle (elem) list');
self.join.contains(needle, |%_)
}
multi method contains(Cool:D: Cool:D $needle --> Bool:D) {
nqp::hllbool(nqp::isne_i(nqp::index(self.Str,$needle.Str,0),-1))
}
Expand All @@ -209,6 +217,10 @@ my class Cool { # declared in BOOTSTRAP
}

proto method indices(|) {*}
multi method indices(List:D: Str:D \needle) { # Warn about newbie trap
self!list-as-string('.grep( ..., :k)');
self.join.indices(needle, |%_)
}
multi method indices(Cool:D: Cool:D $needle, :$overlap) {
self.Str.indices: $needle.Str, :$overlap
}
Expand All @@ -223,6 +235,10 @@ my class Cool { # declared in BOOTSTRAP
}

proto method index(|) {*}
multi method index(List:D: Str:D \needle) { # Warn about newbie trap
self!list-as-string('.first( ..., :k)');
self.join.index(needle, |%_)
}
multi method index(Cool:D: Cool:D $needle --> Int:D) {
nqp::if(
nqp::islt_i((my int $i = nqp::index(self.Str,$needle.Str)),0),
Expand Down

1 comment on commit c9b0218

@AlexDaniel
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you very much. ♥

Please sign in to comment.