Skip to content

Commit 3b76994

Browse files
committed
Prevent comptime fns from being called at runtime
1 parent 47a255d commit 3b76994

File tree

3 files changed

+39
-11
lines changed

3 files changed

+39
-11
lines changed

compiler/rustc_hir_typeck/src/callee.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -904,6 +904,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
904904
callee_did: DefId,
905905
callee_args: GenericArgsRef<'tcx>,
906906
) {
907+
let const_context = self.tcx.hir_body_const_context(self.body_id);
908+
909+
if let hir::Constness::Comptime = self.tcx.constness(callee_did) {
910+
match const_context {
911+
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {}
912+
Some(hir::ConstContext::ConstFn) | None => {
913+
self.dcx().span_err(span, "comptime fns can only be called at compile time");
914+
}
915+
}
916+
}
917+
907918
// FIXME(const_trait_impl): We should be enforcing these effects unconditionally.
908919
// This can be done as soon as we convert the standard library back to
909920
// using const traits, since if we were to enforce these conditions now,
@@ -917,7 +928,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
917928
return;
918929
}
919930

920-
let host = match self.tcx.hir_body_const_context(self.body_id) {
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: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
1-
#![feature(rustc_attrs)]
2-
3-
//TODO: should fail
4-
//@check-pass
1+
#![feature(rustc_attrs, const_trait_impl)]
52

63
#[rustc_comptime]
74
fn foo() {}
85

96
fn main() {
107
// Ok
118
const { foo() };
12-
// TODO: Not ok
13-
foo();
9+
// Not Ok
10+
foo(); //~ ERROR: comptime fns can only be called at compile time
1411
}
1512

1613
const fn bar() {
17-
// TODO: Not ok
18-
foo();
14+
// Not Ok
15+
foo(); //~ ERROR: comptime fns can only be called at compile time
1916
}
2017

2118
#[rustc_comptime]
2219
fn baz() {
23-
// Should be allowed
24-
foo();
20+
// TODO: Should be allowed
21+
foo(); //~ ERROR: comptime fns can only be called at compile time
2522
}
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:15:5
9+
|
10+
LL | foo();
11+
| ^^^^^
12+
13+
error: comptime fns can only be called at compile time
14+
--> $DIR/not_callable.rs:21:5
15+
|
16+
LL | foo();
17+
| ^^^^^
18+
19+
error: aborting due to 3 previous errors
20+

0 commit comments

Comments
 (0)