-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Check for whether index is out of bound during compilation failed unexpectedly #124889
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This repros without the copying method. This panics at runtime: #[derive(Debug)]
struct Arr<T, const N: usize>([T; N]);
fn main() {
let arr = Arr(*b"Hello, world");
println!("{:?}", arr.0[20]);
// let inner = arr.0;
// println!("{:?}", inner[20]);
} While this gives a compiler error: #[derive(Debug)]
struct Arr<T, const N: usize>([T; N]);
fn main() {
let arr = Arr(*b"Hello, world");
// println!("{:?}", arr.0[20]);
let inner = arr.0;
println!("{:?}", inner[20]);
} |
Interestingly this panics: struct Arr([u8; 12]);
fn main() {
let arr = Arr(*b"Hello, world");
// Panics
println!("{:?}", arr.0[20]); But this (without the struct Arr([u8; 12]);
fn main() {
let arr = Arr(*b"Hello, world");
// Compiler errror
arr.0[20];
} Expanding the macros for the former println call (into HIR) gives: ::std::io::_print(format_arguments::new_v1(&["", "\n"],
&[format_argument::new_debug(&arr.0[20])]));
}; I guessed that the reference before struct Arr([u8; 12]);
fn main() {
let arr = Arr(*b"Hello, world");
// Panics
(&arr.0)[20];
} In fact, this happens even if you remove the enclosing struct: fn main() {
let arr: [u8; 12] = *b"Hello, world";
// Panic
(&arr)[20]; fn main() {
let arr: [u8; 12] = *b"Hello, world";
// Compile error
arr[20];
} So it appears that the issue is that the lint to check whether a constant index into a constant array or slice will be out of bounds occurs with arrays but not with slices. I don't know if this is a bug or not. |
@rustbot label +A-lint |
here's another example pub fn returns_slice() -> [(); 1] {
[()]
}
pub struct SliceStruct(pub [(); 1]);
pub fn built_for_this() -> SliceStruct {
SliceStruct([()])
}
fn main() {
// compiler error
returns_slice()[1];
// panics
built_for_this().0[1];
// compiler error
SliceStruct([()]).0[1];
} |
Fixed by #129517: https://rust.godbolt.org/z/KWK8c5Mr8 |
Thank you for notification! |
I tried these two codes:
I expected to see this happen:
When running
cargo build
,"index out of bounds: the length is 12 but the index is 20" should be indicated for both codes
Instead, this happened:
Only Code 2 had it
Meta
rustc --version --verbose
:Backtrace
Building:
Running(Code 1):
The text was updated successfully, but these errors were encountered: