Skip to content

Commit

Permalink
Fix unsafe blocks in s![] macro
Browse files Browse the repository at this point in the history
Before, the user could silently violate safety requirements of
`SliceInfo::new_unchecked` by directly calling `s![@parse
inconsistent_values]`, where `inconsistent_values` represents
inconsistent values for the dimensions, etc. Now, the macro calls
`SliceInfo::new_unchecked` only in the `($($t:tt)*)` arm, which always
constructs the correct values for the call.
  • Loading branch information
jturner314 authored and bluss committed Mar 9, 2024
1 parent 54b3ffb commit fa195d8
Showing 1 changed file with 29 additions and 32 deletions.
61 changes: 29 additions & 32 deletions src/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,14 +780,11 @@ macro_rules! s(
r => {
let in_dim = $crate::SliceNextDim::next_in_dim(&r, $in_dim);
let out_dim = $crate::SliceNextDim::next_out_dim(&r, $out_dim);
#[allow(unsafe_code)]
unsafe {
$crate::SliceInfo::new_unchecked(
[$($stack)* $crate::s!(@convert r, $s)],
in_dim,
out_dim,
)
}
(
[$($stack)* $crate::s!(@convert r, $s)],
in_dim,
out_dim,
)
}
}
};
Expand All @@ -797,14 +794,11 @@ macro_rules! s(
r => {
let in_dim = $crate::SliceNextDim::next_in_dim(&r, $in_dim);
let out_dim = $crate::SliceNextDim::next_out_dim(&r, $out_dim);
#[allow(unsafe_code)]
unsafe {
$crate::SliceInfo::new_unchecked(
[$($stack)* $crate::s!(@convert r)],
in_dim,
out_dim,
)
}
(
[$($stack)* $crate::s!(@convert r)],
in_dim,
out_dim,
)
}
}
};
Expand Down Expand Up @@ -844,16 +838,11 @@ macro_rules! s(
};
// empty call, i.e. `s![]`
(@parse ::core::marker::PhantomData::<$crate::Ix0>, ::core::marker::PhantomData::<$crate::Ix0>, []) => {
{
#[allow(unsafe_code)]
unsafe {
$crate::SliceInfo::new_unchecked(
[],
::core::marker::PhantomData::<$crate::Ix0>,
::core::marker::PhantomData::<$crate::Ix0>,
)
}
}
(
[],
::core::marker::PhantomData::<$crate::Ix0>,
::core::marker::PhantomData::<$crate::Ix0>,
)
};
// Catch-all clause for syntax errors
(@parse $($t:tt)*) => { compile_error!("Invalid syntax in s![] call.") };
Expand All @@ -868,12 +857,20 @@ macro_rules! s(
)
};
($($t:tt)*) => {
$crate::s![@parse
::core::marker::PhantomData::<$crate::Ix0>,
::core::marker::PhantomData::<$crate::Ix0>,
[]
$($t)*
]
{
let (indices, in_dim, out_dim) = $crate::s![@parse
::core::marker::PhantomData::<$crate::Ix0>,
::core::marker::PhantomData::<$crate::Ix0>,
[]
$($t)*
];
// Safety: The `s![@parse ...]` above always constructs the correct
// values to meet the constraints of `SliceInfo::new_unchecked`.
#[allow(unsafe_code)]
unsafe {
$crate::SliceInfo::new_unchecked(indices, in_dim, out_dim)
}
}
};
);

Expand Down

0 comments on commit fa195d8

Please sign in to comment.