Re: [PATCH 5/7] rust: init: add `..Zeroable::zeroed()` syntax for zeroing all missing fields

From: Benno Lossin
Date: Sun Jun 25 2023 - 12:46:32 EST


On 6/25/23 16:17, Björn Roy Baron wrote:
> On Sunday, June 25th, 2023 at 15:07, Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>> On 25.06.23 14:56, Björn Roy Baron wrote:
>>> On Saturday, June 24th, 2023 at 23:14, Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>>
>>>>>> + // Ensure that the struct is indeed `Zeroable`.
>>>>>> + is_zeroable(slot);
>>>>>> + // SAFETY: The type implements `Zeroable` by the check above.
>>>>>> + unsafe { ::core::ptr::write_bytes(slot, 0, 1) };
>>>>>> + $init_zeroed // this will be `()` if set.
>>>>>
>>>>> How does this work? Shouldn't there be a ; after $init_zeroed to consume the () value?
>>>>
>>>> It is the last expression of a block and since it is `()` it is ok
>>>> (adding a ; would also be ok, but it is not necessary).
>>>
>>> I'm surprised it is considered the last expression of a block. Unlike with {} using $()? will still
>>> allow variables defined inside this as if they were outside of it. Also I can't reproduce this
>>> behavior with:
>>>
>>> macro_rules! foo {
>>> ($($a:expr)?) => {
>>> $($a)?
>>> bar();
>>> }
>>> }
>>>
>>> fn main() {
>>> foo!(());
>>> }
>>>
>>> Is there something I'm missing?
>>>
>>> Cheers,
>>> Björn
>>
>> Not sure what you mean with "allow variables defined inside this
>> as if they were outside of it". But note that in the macro `$init_zeroed`
>> is the last expression of a block. Here is a small example:
>
> $(let $this = unsafe { ::core::ptr::NonNull::new_unchecked(slot) };)? comes after
> this code in the same block that contains struct __InitOk;. And after that another
> $crate::__init_internal!() invocation. That is why I don't get that this is allowed
> at all.
>

Oh I see the issue now, I thought I wrote
```
$({
fn assert_zeroable<T: Zeroable>(ptr: *mut T) {}
// Ensure that the struct is indeed `Zeroable`.
assert_zeroable(slot);
// SAFETY: The type implements `Zeroable` by the check above.
unsafe { ::core::ptr::write_bytes(slot, 0, 1) };
$init_zeroed // this will be `()` if set.
})?
```

But I forgot the inner `{}`. Good catch!

--
Cheers,
Benno

>>
>> ```
>> macro_rules! foo {
>> ($($a:expr)?) => {{
>> $(
>> bar();
>> $a
>> )?
>> }};
>> }
>>
>> fn bar() {}
>>
>> fn main() {
>> foo!(());
>> foo!();
>> }
>> ```
>>
>> it expands to this:
>> ```
>> fn main() {
>> {
>> bar();
>> ()
>> };
>> {};
>> }
>> ```
>>
>> --
>> Cheers,
>> Benno
>>