Skip to content

Commit a765cef

Browse files
committed
Prevent comptime fns from being called at runtime
1 parent cca9228 commit a765cef

File tree

3 files changed

+47
-5
lines changed

3 files changed

+47
-5
lines changed

compiler/rustc_hir_typeck/src/callee.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -917,7 +917,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
917917
return;
918918
}
919919

920-
let host = match self.tcx.hir_body_const_context(self.body_id) {
920+
let const_context = self.tcx.hir_body_const_context(self.body_id);
921+
922+
if let hir::Constness::Comptime = self.tcx.constness(callee_did) {
923+
match const_context {
924+
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
925+
Some(hir::ConstContext::ConstFn) | None => {
926+
self.dcx().span_err(span, "comptime fns can only be called at compile time");
927+
}
928+
}
929+
}
930+
931+
let host = match const_context {
921932
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
922933
ty::BoundConstness::Const
923934
}

tests/ui/comptime/not_callable.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
#![feature(rustc_attrs)]
2-
3-
// TODO: this test should fail
4-
//@check-pass
1+
#![feature(rustc_attrs, const_trait_impl)]
52

63
#[rustc_comptime]
74
fn foo() {}
@@ -11,4 +8,18 @@ fn main() {
118
const { foo() };
129
// Not ok
1310
foo();
11+
//~^ ERROR: comptime fns can only be called at compile time
12+
}
13+
14+
const fn bar() {
15+
// Not ok
16+
foo();
17+
//~^ ERROR: comptime fns can only be called at compile time
18+
}
19+
20+
#[rustc_comptime]
21+
fn baz() {
22+
// Should be allowed
23+
foo();
24+
//~^ ERROR: comptime fns can only be called at compile time
1425
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: comptime fns can only be called at compile time
2+
--> $DIR/not_callable.rs:10:5
3+
|
4+
LL | foo();
5+
| ^^^^^
6+
7+
error: comptime fns can only be called at compile time
8+
--> $DIR/not_callable.rs:16:5
9+
|
10+
LL | foo();
11+
| ^^^^^
12+
13+
error: comptime fns can only be called at compile time
14+
--> $DIR/not_callable.rs:23:5
15+
|
16+
LL | foo();
17+
| ^^^^^
18+
19+
error: aborting due to 3 previous errors
20+

0 commit comments

Comments
 (0)