Skip to content

Commit

Permalink
contracts: added lang items that act as hooks for rustc-injected code…
Browse files Browse the repository at this point in the history
… to invoke.

see test for an example of the kind of injected code that is anticipated here.
  • Loading branch information
pnkfelix authored and gitbot committed Feb 20, 2025
1 parent 2cb9f38 commit 1d461d0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
33 changes: 33 additions & 0 deletions core/src/contracts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//! Unstable module containing the unstable contracts lang items and attribute macros.
/// Emitted by rustc as a desugaring of `#[requires(PRED)] fn foo(x: X) { ... }`
/// into: `fn foo(x: X) { check_requires(|| PRED) ... }`
#[cfg(not(bootstrap))]
#[unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
#[lang = "contract_check_requires"]
#[track_caller]
pub fn check_requires<C: FnOnce() -> bool>(c: C) {
if core::intrinsics::contract_checks() {
assert!(core::intrinsics::contract_check_requires(c), "failed requires check");
}
}

/// Emitted by rustc as a desugaring of `#[ensures(PRED)] fn foo() -> R { ... [return R;] ... }`
/// into: `fn foo() { let _check = build_check_ensures(|ret| PRED) ... [return _check(R);] ... }`
/// (including the implicit return of the tail expression, if any).
#[cfg(not(bootstrap))]
#[unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
#[lang = "contract_build_check_ensures"]
#[track_caller]
pub fn build_check_ensures<Ret, C>(c: C) -> impl (FnOnce(Ret) -> Ret) + Copy
where
C: for<'a> FnOnce(&'a Ret) -> bool + Copy + 'static,
{
#[track_caller]
move |ret| {
if core::intrinsics::contract_checks() {
assert!(core::intrinsics::contract_check_ensures(&ret, c), "failed ensures check");
}
ret
}
}
5 changes: 5 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
#![feature(bstr)]
#![feature(bstr_internals)]
#![feature(const_carrying_mul_add)]
#![feature(closure_track_caller)]
#![feature(const_eval_select)]
#![feature(core_intrinsics)]
#![feature(coverage_attribute)]
Expand Down Expand Up @@ -247,6 +248,10 @@ pub mod autodiff {
pub use crate::macros::builtin::autodiff;
}

#[cfg(not(bootstrap))]
#[unstable(feature = "rustc_contracts", issue = "none")]
pub mod contracts;

#[unstable(feature = "cfg_match", issue = "115585")]
pub use crate::macros::cfg_match;

Expand Down

0 comments on commit 1d461d0

Please sign in to comment.