The amount of things that “could be” determined at compilation is unlimited, but also, there must be a limit, and it happens to be before any mechanism that could warn about out-of-bounds access in this case.
More specifically, the thing (“problem”) that could happen for the compiler here is to determine that the code unconditionally panics, whilst unconditionally panicking is likely not the intended behavior. By the way, note that, without a doubt, the only expected and correct behavior of this code is to compile successfully and panic at run-time, and all that could be issued at compile-time is a lint (i.e. most commonly those are panics, though some lints are also configured to error by default, unless you disable them or they happen in a dependency of your crate).
The issue that this code has is also is a relatively imprecise measure – whilst “panics unconditionally” is quite precise, the part where we’d need to determine that panicking unconditionally is likely not the intended behavior might require more thought, though in this case it’s likely actually the part of determining the code panics unconditionally that isn’t easy.
The problem is that Rust code is designed exclusively for execution at run-time. While there is ongoing work to enable more and more code to support compile-time execution (via const fn
), slicing strings is not even part of this yet, and even operations that are const fn
are actually designed exclusively for supporting explicitly being executed at compile-time, as doing so can have side effects like
- taking a long time
- erroring
- having slightly different behavior compared to run-time
- etc…
so that using this mechanism for determining whether something panics unconditionally would be non-trivial, too.
That only leaves the option of (more or less) hard-coding certain operations that can be checked for whether they unconditionally panic. (In the general case, one would probably also need to hard code operations that are not used for intentionally creating panics, since otherwise it’d be impossible to know whether code was intended to unconditionally panic, after all.) That’s involving manual work, so it’s even more limited than the things that automated approaches could achieve, so it isn’t surprising that the vast majority of code that unconditionally panics will not be detected by existing lints, including this one.