Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a macro for static (compile-time) assertions #54958

Merged
merged 1 commit into from
Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/librustc/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ macro_rules! span_bug {
})
}

#[macro_export]
macro_rules! static_assert {
($name:ident: $test:expr) => {
// Use the bool to access an array such that if the bool is false, the access
// is out-of-bounds.
#[allow(dead_code)]
static $name: () = [()][!$test as usize];
}
}

#[macro_export]
macro_rules! __impl_stable_hash_field {
($field:ident, $ctx:expr, $hasher:expr) => ($field.hash_stable($ctx, $hasher));
Expand Down
3 changes: 1 addition & 2 deletions src/librustc/middle/region.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ newtype_index! {
impl_stable_hash_for!(struct ::middle::region::FirstStatementIndex { private });

// compilation error if size of `ScopeData` is not the same as a `u32`
#[allow(dead_code)]
static ASSERT: () = [()][!(mem::size_of::<ScopeData>() == 4) as usize];
static_assert!(ASSERT_SCOPE_DATA: mem::size_of::<ScopeData>() == 4);

impl Scope {
/// Returns a item-local id associated with this scope.
Expand Down
7 changes: 2 additions & 5 deletions src/librustc/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -827,12 +827,9 @@ impl<'tcx> CommonTypes<'tcx> {
fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
// Ensure our type representation does not grow
#[cfg(target_pointer_width = "64")]
#[allow(dead_code)]
static ASSERT_TY_KIND: () =
[()][!(::std::mem::size_of::<ty::TyKind<'_>>() <= 24) as usize];
static_assert!(ASSERT_TY_KIND: ::std::mem::size_of::<ty::TyKind<'_>>() <= 24);
#[cfg(target_pointer_width = "64")]
#[allow(dead_code)]
static ASSERT_TYS: () = [()][!(::std::mem::size_of::<ty::TyS<'_>>() <= 32) as usize];
static_assert!(ASSERT_TYS: ::std::mem::size_of::<ty::TyS<'_>>() <= 32);

let mk = |sty| CtxtInterners::intern_ty(interners, interners, sty);
let mk_region = |r| {
Expand Down