Skip to main content

rustc_comptime

Attribute rustc_comptime 

Source
Expand description

Marks a function as only callable at compile time.

Unlike const fn, which can be called from a const context, comptime functions must be called from a const context. It is an error to call a comptime function outside a const context.

§Example

ⓘ
//@ dont-require-annotations: ERROR
//@ compile-flags: --crate-type lib -Z ui-testing=no

#![feature(rustc_attrs)]

#[rustc_comptime]
fn comptime() {}

fn from_runtime() {
    comptime(); // ERROR

    const { comptime() }; // OK
}

// comptime functions cannot be called from const
// functions, as these may be called at runtime
const fn const_or_runtime() {
    comptime();
}

produces:

error: comptime functions can only be called at compile time
 --> $DIR/rustc_comptime.rs:10:5
  |
10 |     comptime(); // ERROR
  |     ^^^^^^^^^^
  |
help: wrap the call in a const block to force compile time evaluation
  |
10 |     const { comptime() }; // ERROR
  |     +++++++            +

error: comptime functions can only be called at compile time
 --> $DIR/rustc_comptime.rs:18:5
  |
18 |     comptime();
  |     ^^^^^^^^^^
  |
help: wrap the call in a const block to force compile time evaluation
  |
18 |     const { comptime() };
  |     +++++++            +

error: aborting due to 2 previous errors

There are many things which only have meaning at compile time and can make use of such functions:

  • the type_info feature, for compile time type reflection.
  • the const heap intrinsics const_allocate and const_deallocate, at runtime, return a null pointer and do nothing respectively.
  • intrinsics such as size_of and friends cause an ICE when they are called at runtime. The stabilized versions of these functions forward to these intrinsics via associated constants on the SizedTypeProperties trait.

At this time, the primary motivation for comptime functions is the type_info feature. The constructs in mem::type_info only makes sense at compile time as during compile time we can simply ask the compiler for whatever information we need. At runtime, though, that cannot be done - to support runtime reflection we would have to create some global table with all the information we might possibly need. This is unfeasible and any (third party wrappers for) “runtime reflection” based on type_info would be limited to retrieving information queried in advance at compile time.

See the reflection and comptime project goal for more information about reflection and comptime.

See AttributeKind::RustcComptime for the internal representation of this attribute.