Skip to content

Commit e643396

Browse files
committed
Implement static_assert attribute
This verifies that a static item evaluates to true, at compile time.
1 parent b6a0d40 commit e643396

File tree

4 files changed

+43
-1
lines changed

4 files changed

+43
-1
lines changed

src/librustc/middle/trans/base.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2147,7 +2147,26 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::item) {
21472147
trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
21482148
}
21492149
}
2150-
ast::item_const(_, expr) => consts::trans_const(ccx, expr, item.id),
2150+
ast::item_const(_, expr) => {
2151+
consts::trans_const(ccx, expr, item.id);
2152+
// Do static_assert checking. It can't really be done much earlier because we need to get
2153+
// the value of the bool out of LLVM
2154+
for item.attrs.each |attr| {
2155+
match attr.node.value.node {
2156+
ast::meta_word(x) => {
2157+
if x.slice(0, x.len()) == "static_assert" {
2158+
let v = ccx.const_values.get_copy(&item.id);
2159+
unsafe {
2160+
if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2161+
ccx.sess.span_fatal(expr.span, "static assertion failed");
2162+
}
2163+
}
2164+
}
2165+
},
2166+
_ => ()
2167+
}
2168+
}
2169+
},
21512170
ast::item_foreign_mod(ref foreign_mod) => {
21522171
foreign::trans_foreign_mod(ccx, path, foreign_mod);
21532172
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#[static_assert]
2+
static a: bool = false; //~ ERROR static assertion failed
3+
4+
fn main() {
5+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#[static_assert]
2+
static e: bool = 1 == 2; //~ ERROR static assertion failed
3+
4+
fn main() {}

src/test/run-pass/static-assert.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#[static_assert]
2+
static b: bool = true;
3+
4+
#[static_assert]
5+
static c: bool = 1 == 1;
6+
7+
#[static_assert]
8+
static d: bool = 1 != 2;
9+
10+
#[static_assert]
11+
static f: bool = (4/2) == 2;
12+
13+
fn main() {
14+
}

0 commit comments

Comments
 (0)