Skip to content

Commit e7aa936

Browse files
committed
add code blocks to [try_][pin_]init! macros
Allow writing `_: { /* any number of statements */ }` in initializers to run arbitrary code during initialization. It also allows declaring values that can be used later in the initializer: init!(MyStruct { _: { let val = if check_something() { 42 } else { 0 }; }, foo: Foo::new(val), }) Signed-off-by: Benno Lossin <[email protected]>
1 parent 5d2996b commit e7aa936

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/macros.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,21 @@ macro_rules! __init_internal {
12021202
// have been initialized. Therefore we can now dismiss the guards by forgetting them.
12031203
$(::core::mem::forget($guards);)*
12041204
};
1205+
(init_slot($($use_data:ident)?):
1206+
@data($data:ident),
1207+
@slot($slot:ident),
1208+
@guards($($guards:ident,)*),
1209+
// arbitrary code block
1210+
@munch_fields(_: { $($code:tt)* }, $($rest:tt)*),
1211+
) => {
1212+
$($code)*
1213+
$crate::__init_internal!(init_slot($($use_data)?):
1214+
@data($data),
1215+
@slot($slot),
1216+
@guards($($guards,)*),
1217+
@munch_fields($($rest)*),
1218+
);
1219+
};
12051220
(init_slot($use_data:ident): // `use_data` is present, so we use the `data` to init fields.
12061221
@data($data:ident),
12071222
@slot($slot:ident),
@@ -1351,6 +1366,19 @@ macro_rules! __init_internal {
13511366
);
13521367
}
13531368
};
1369+
(make_initializer:
1370+
@slot($slot:ident),
1371+
@type_name($t:path),
1372+
@munch_fields(_: { $($code:tt)* }, $($rest:tt)*),
1373+
@acc($($acc:tt)*),
1374+
) => {
1375+
$crate::__init_internal!(make_initializer:
1376+
@slot($slot),
1377+
@type_name($t),
1378+
@munch_fields($($rest)*),
1379+
@acc($($acc)*),
1380+
);
1381+
};
13541382
(make_initializer:
13551383
@slot($slot:ident),
13561384
@type_name($t:path),

tests/ui/compile-fail/init/wrong_generics2.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ help: you might have forgotten to add the struct literal inside the block
1212
--> src/macros.rs
1313
|
1414
~ ::core::ptr::write($slot, $t { SomeStruct {
15-
|9 $($acc)*
15+
|4 $($acc)*
1616
~ } });
1717
|
1818

0 commit comments

Comments
 (0)