Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- macro_rules! reassign {
- // Init: manually feed incrementing indices
- (
- ( $($tt:tt)* ) = $expr:expr
- ) => (
- // let temp = $expr;
- reassign! {
- @write_with_type_annotation [ $($tt)* ] ()
- let temp = $expr;
- }
- reassign! {
- @indices [0 1 2 3 4 5 6 7 8 9 10 11 12]
- ( $($tt)* ) = temp
- }
- );
- // Handling left-hand-side step-by-step
- // New binding case
- (@indices
- [ $cur_index:tt $($rest_indices:tt)* ]
- (
- let $var:pat
- $(
- , $($rest:tt)*
- )?
- ) = $expr:ident
- ) => (
- let $var = $expr.$cur_index;
- reassign! {
- @indices [ $($rest_indices)* ]
- (
- $( $($rest)* )?
- ) = $expr
- }
- );
- // Nested tuple case
- (@indices
- [ $cur_index:tt $($rest_indices:tt)* ]
- (
- ( $($tt:tt)* )
- $(
- , $($rest:tt)*
- )?
- ) = $expr:ident
- ) => (
- reassign!( ($($tt)*) = $expr.$cur_index );
- reassign! {
- @indices [ $($rest_indices)* ]
- (
- $( $($rest)* )?
- ) = $expr
- }
- );
- // place expression case (`*(&mut ...)` or varname)
- (@indices
- [ $cur_index:tt $($rest_indices:tt)* ]
- (
- $var:expr
- $(
- , $($rest:tt)*
- )?
- ) = $expr:ident
- ) => (
- $var = $expr.$cur_index;
- reassign! {
- @indices [ $($rest_indices)* ]
- (
- $( $($rest)* )?
- ) = $expr
- }
- );
- // Termination
- (@indices
- $indices:tt
- () = $expr:ident
- ) => ();
- // Bad termination: exhausted indices
- (@indices
- []
- $vars:tt = $expr:ident
- ) => (
- compile_error! {
- "`reassign!` only supports up to 12-tuples"
- }
- );
- // Writing a type annotation to prevent the right hand side
- // from having extra (unused) elements:
- // New binding case
- (@write_with_type_annotation
- [ let $pat:pat $(, $($tt:tt)* )? ] // input
- (
- $($tys:tt)*
- )
- let $ident:ident = $expr:expr;
- ) => (reassign!(@write_with_type_annotation
- [ $( $($tt)* )? ]
- (
- $($tys)* _,
- )
- let $ident = $expr;
- ));
- // place expression case
- (@write_with_type_annotation
- [ $place:expr $(, $($tt:tt)* )? ] // input
- (
- $($tys:tt)*
- )
- let $ident:ident = $expr:expr;
- ) => (reassign!(@write_with_type_annotation
- [ $( $($tt)* )? ]
- (
- $($tys)* _,
- )
- let $ident = $expr;
- ));
- // End
- (@write_with_type_annotation
- [] // input
- ($($tuple_ty:tt)*)
- let $ident:ident = $expr:expr;
- ) => (
- let $ident: ($($tuple_ty)*) = $expr;
- );
- }
- fn main ()
- {
- let mut a = [0, 0];
- reassign! {
- (
- (a[0],), a[1], let z,
- ) = (
- (42,), 27, 0,
- )
- }
- dbg!(a.iter().sum::<i32>());
- dbg!(z);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement