Skip to content

Contract cannot be applied to const functions #136925

Closed
@tautschnig

Description

@tautschnig

I tried this code (minimal reproducer extracted from #136578):

#![feature(contracts)]
//~^ WARN the feature `contracts` is incomplete and may not be safe to use and/or cause compiler crashes [incomplete_features]

#[core::contracts::ensures(move |ret: &u32| *ret > x)]
const fn broken_sum(x: u32, y: u32) -> u32 {
    x + y
}

fn main() {
    assert_eq!(broken_sum(0, 1), 1);
}

I expected to see this happen: compilation would succeed

Instead, this happened: compiler rejected the code with the following errors:

error[E0015]: cannot call non-const function `build_check_ensures::<u32, {closure@contracts-const.rs:4:28: 4:44}>` in constant functions
 --> contracts-const.rs:4:1
  |
4 | #[core::contracts::ensures(move |ret: &u32| *ret > x)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants

error[E0015]: cannot call non-const closure in constant functions
 --> contracts-const.rs:4:1
  |
4 | #[core::contracts::ensures(move |ret: &u32| *ret > x)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants

error: aborting due to 2 previous errors; 1 warning emitted

For more information about this error, try `rustc --explain E0015`.

Meta

rustc --version --verbose:

$ build/x86_64-unknown-linux-gnu/stage2/bin/rustc --version --verbose
rustc 1.86.0-nightly (69482e8e5 2025-02-11)
binary: rustc
commit-hash: 69482e8e5a5fa1441615b015ac2f59178d944696
commit-date: 2025-02-11
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly
LLVM version: 19.1.7

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.F-contracts`#![feature(contracts)]`S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.requires-incomplete-featuresThis issue requires the use of incomplete features.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions