Using unsafe blocks in let expressions
Mark Wielaard
mark@klomp.org
Wed Jul 21 21:09:38 GMT 2021
Hi,
I wanted to use an unsafe block in a let expression, which wasn't
accepted. The attached patch implements this.
I did want to add a testcase, but I couldn't come up with a test that
is correct and passes the type checker. The following works, but is
not correctly typed:
pub fn main ()
{
let mut num = 2;
// let r1 = &num as *const i32;
// let r1: *const i32 = #
let r1 = #
let r2 = unsafe { *r1 } + unsafe { *r1 };
let r3 = num;
num = 4;
let r4 = num + unsafe { *r1 } * r3;
let _eightteen = r2 + r3 + r4;
}
In this case r1 is a reference, not a raw pointer, so the code
shouldn't work, but it does. It does correctly add up to 18.
The two ways to make this code type correct don't work. The first
gives:
let_unsafe.rs:4:12: fatal error: Failed to lower expr: [&num as *const i32]
4 | let r1 = &num as *const i32;
| ^
The second gives:
let_unsafe.rs:7:21: error: expected reference type got * const i32
7 | let r2 = unsafe { *r1 } + unsafe { *r1 };
| ^
let_unsafe.rs:7:21: error: failed to type resolve expression
let_unsafe.rs:7:38: error: expected reference type got * const i32
7 | let r2 = unsafe { *r1 } + unsafe { *r1 };
| ^
let_unsafe.rs:7:38: error: failed to type resolve expression
let_unsafe.rs:7:18: error: cannot apply this operator to types <tyty::error> and <tyty::error>
7 | let r2 = unsafe { *r1 } + unsafe { *r1 };
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
Note that the error marker is wrong on the last line. I think that is
because of the way the pratt parser eats the token and then the code
does a locus - 1. Which ends up at the wrong place. I think instead of
a boolean we should pass the current token to get the correct
location.
Cheers,
Mark
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 0001-unsafe-blocks-can-be-used-in-expressions.patch
Type: text/x-diff
Size: 3078 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-rust/attachments/20210721/1c170716/attachment.bin>
More information about the Gcc-rust
mailing list