]> git.lizzy.rs Git - rust.git/commitdiff
Implement static_assert attribute
authorCorey Richardson <corey@octayn.net>
Wed, 22 May 2013 00:26:45 +0000 (20:26 -0400)
committerCorey Richardson <corey@octayn.net>
Wed, 22 May 2013 17:13:24 +0000 (13:13 -0400)
This verifies that a static item evaluates to true, at compile time.

src/librustc/middle/trans/base.rs
src/test/compile-fail/static-assert.rs [new file with mode: 0644]
src/test/compile-fail/static-assert2.rs [new file with mode: 0644]
src/test/run-pass/static-assert.rs [new file with mode: 0644]

index 94ca02b22554b41f15279be9b70e464fc3617da8..17d3e2c4dfefe8ceacd04f6a796e4f74d7ad7d39 100644 (file)
@@ -2147,7 +2147,26 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::item) {
             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
         }
       }
-      ast::item_const(_, expr) => consts::trans_const(ccx, expr, item.id),
+      ast::item_const(_, expr) => {
+          consts::trans_const(ccx, expr, item.id);
+          // Do static_assert checking. It can't really be done much earlier because we need to get
+          // the value of the bool out of LLVM
+          for item.attrs.each |attr| {
+              match attr.node.value.node {
+                  ast::meta_word(x) => {
+                      if x.slice(0, x.len()) == "static_assert" {
+                          let v = ccx.const_values.get_copy(&item.id);
+                          unsafe {
+                              if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
+                                  ccx.sess.span_fatal(expr.span, "static assertion failed");
+                              }
+                          }
+                      }
+                  },
+                  _ => ()
+              }
+          }
+      },
       ast::item_foreign_mod(ref foreign_mod) => {
         foreign::trans_foreign_mod(ccx, path, foreign_mod);
       }
diff --git a/src/test/compile-fail/static-assert.rs b/src/test/compile-fail/static-assert.rs
new file mode 100644 (file)
index 0000000..06f8c9f
--- /dev/null
@@ -0,0 +1,5 @@
+#[static_assert]
+static a: bool = false; //~ ERROR static assertion failed
+
+fn main() {
+}
diff --git a/src/test/compile-fail/static-assert2.rs b/src/test/compile-fail/static-assert2.rs
new file mode 100644 (file)
index 0000000..de1c642
--- /dev/null
@@ -0,0 +1,4 @@
+#[static_assert]
+static e: bool = 1 == 2; //~ ERROR static assertion failed
+
+fn main() {}
diff --git a/src/test/run-pass/static-assert.rs b/src/test/run-pass/static-assert.rs
new file mode 100644 (file)
index 0000000..81b0c9f
--- /dev/null
@@ -0,0 +1,14 @@
+#[static_assert]
+static b: bool = true;
+
+#[static_assert]
+static c: bool = 1 == 1;
+
+#[static_assert]
+static d: bool = 1 != 2;
+
+#[static_assert]
+static f: bool = (4/2) == 2;
+
+fn main() {
+}