Skip to content

Commit bcb8565

Browse files
pnkfelixcelinval
authored andcommitted
Contracts core intrinsics.
These are hooks to: 1. control whether contract checks are run 2. allow 3rd party tools to intercept and reintepret the results of running contracts.
1 parent 534d79a commit bcb8565

File tree

30 files changed

+183
-6
lines changed

30 files changed

+183
-6
lines changed

compiler/rustc_borrowck/src/type_check/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1650,6 +1650,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
16501650
ConstraintCategory::SizedBound,
16511651
);
16521652
}
1653+
&Rvalue::NullaryOp(NullOp::ContractChecks, _) => {}
16531654
&Rvalue::NullaryOp(NullOp::UbChecks, _) => {}
16541655

16551656
Rvalue::ShallowInitBox(operand, ty) => {

compiler/rustc_codegen_cranelift/src/base.rs

+9
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,15 @@ fn codegen_stmt<'tcx>(
874874
lval.write_cvalue(fx, val);
875875
return;
876876
}
877+
NullOp::ContractChecks => {
878+
let val = fx.tcx.sess.contract_checks();
879+
let val = CValue::by_val(
880+
fx.bcx.ins().iconst(types::I8, i64::try_from(val).unwrap()),
881+
fx.layout_of(fx.tcx.types.bool),
882+
);
883+
lval.write_cvalue(fx, val);
884+
return;
885+
}
877886
};
878887
let val = CValue::by_val(
879888
fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(val).unwrap()),

compiler/rustc_codegen_ssa/src/mir/rvalue.rs

+4
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
741741
let val = bx.tcx().sess.ub_checks();
742742
bx.cx().const_bool(val)
743743
}
744+
mir::NullOp::ContractChecks => {
745+
let val = bx.tcx().sess.contract_checks();
746+
bx.cx().const_bool(val)
747+
}
744748
};
745749
let tcx = self.cx.tcx();
746750
OperandRef {

compiler/rustc_const_eval/src/check_consts/check.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -675,7 +675,11 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
675675
Rvalue::Cast(_, _, _) => {}
676676

677677
Rvalue::NullaryOp(
678-
NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(_) | NullOp::UbChecks,
678+
NullOp::SizeOf
679+
| NullOp::AlignOf
680+
| NullOp::OffsetOf(_)
681+
| NullOp::UbChecks
682+
| NullOp::ContractChecks,
679683
_,
680684
) => {}
681685
Rvalue::ShallowInitBox(_, _) => {}

compiler/rustc_const_eval/src/interpret/machine.rs

+10
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,9 @@ pub trait Machine<'tcx>: Sized {
293293
/// Determines the result of a `NullaryOp::UbChecks` invocation.
294294
fn ub_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>;
295295

296+
/// Determines the result of a `NullaryOp::ContractChecks` invocation.
297+
fn contract_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>;
298+
296299
/// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
297300
/// You can use this to detect long or endlessly running programs.
298301
#[inline]
@@ -679,6 +682,13 @@ pub macro compile_time_machine(<$tcx: lifetime>) {
679682
interp_ok(true)
680683
}
681684

685+
#[inline(always)]
686+
fn contract_checks(_ecx: &InterpCx<$tcx, Self>) -> InterpResult<$tcx, bool> {
687+
// We can't look at `tcx.sess` here as that can differ across crates, which can lead to
688+
// unsound differences in evaluating the same constant at different instantiation sites.
689+
interp_ok(true)
690+
}
691+
682692
#[inline(always)]
683693
fn adjust_global_allocation<'b>(
684694
_ecx: &InterpCx<$tcx, Self>,

compiler/rustc_const_eval/src/interpret/operator.rs

+1
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
537537
ImmTy::from_uint(val, usize_layout())
538538
}
539539
UbChecks => ImmTy::from_bool(M::ub_checks(self)?, *self.tcx),
540+
ContractChecks => ImmTy::from_bool(M::contract_checks(self)?, *self.tcx),
540541
})
541542
}
542543
}

compiler/rustc_feature/src/builtin_attrs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const GATED_CFGS: &[GatedCfg] = &[
1919
// (name in cfg, feature, function to check if the feature is enabled)
2020
(sym::overflow_checks, sym::cfg_overflow_checks, Features::cfg_overflow_checks),
2121
(sym::ub_checks, sym::cfg_ub_checks, Features::cfg_ub_checks),
22+
(sym::contract_checks, sym::cfg_contract_checks, Features::cfg_contract_checks),
2223
(sym::target_thread_local, sym::cfg_target_thread_local, Features::cfg_target_thread_local),
2324
(
2425
sym::target_has_atomic_equal_alignment,

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,8 @@ declare_features! (
403403
(unstable, c_variadic, "1.34.0", Some(44930)),
404404
/// Allows the use of `#[cfg(<true/false>)]`.
405405
(unstable, cfg_boolean_literals, "1.83.0", Some(131204)),
406+
/// Allows the use of `#[cfg(contract_checks)` to check if contract checks are enabled.
407+
(unstable, cfg_contract_checks, "CURRENT_RUSTC_VERSION", Some(133866)),
406408
/// Allows the use of `#[cfg(overflow_checks)` to check if integer overflow behaviour.
407409
(unstable, cfg_overflow_checks, "1.71.0", Some(111466)),
408410
/// Provides the relocation model information as cfg entry

compiler/rustc_hir_analysis/src/check/intrinsic.rs

+20
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,9 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
132132
| sym::aggregate_raw_ptr
133133
| sym::ptr_metadata
134134
| sym::ub_checks
135+
| sym::contract_checks
136+
| sym::contract_check_requires
137+
| sym::contract_check_ensures
135138
| sym::fadd_algebraic
136139
| sym::fsub_algebraic
137140
| sym::fmul_algebraic
@@ -219,6 +222,18 @@ pub fn check_intrinsic_type(
219222
}
220223
};
221224
(n_tps, 0, 0, inputs, output, hir::Safety::Unsafe)
225+
} else if intrinsic_name == sym::contract_check_ensures {
226+
// contract_check_ensures::<'a, Ret, C>(&'a Ret, C) -> bool
227+
// where C: impl Fn(&'a Ret) -> bool,
228+
//
229+
// so: two type params, one lifetime param, 0 const params, two inputs, returns boolean
230+
231+
let p = generics.param_at(0, tcx);
232+
let r = ty::Region::new_early_param(tcx, p.to_early_bound_region_data());
233+
let ref_ret = Ty::new_imm_ref(tcx, r, param(1));
234+
// let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BrAnon };
235+
// let ref_ret = Ty::new_imm_ref(tcx, ty::Region::new_bound(tcx, ty::INNERMOST, br), param(0));
236+
(2, 1, 0, vec![ref_ret, param(2)], tcx.types.bool, hir::Safety::Safe)
222237
} else {
223238
let safety = intrinsic_operation_unsafety(tcx, intrinsic_id);
224239
let (n_tps, n_cts, inputs, output) = match intrinsic_name {
@@ -610,6 +625,11 @@ pub fn check_intrinsic_type(
610625

611626
sym::box_new => (1, 0, vec![param(0)], Ty::new_box(tcx, param(0))),
612627

628+
// contract_checks() -> bool
629+
sym::contract_checks => (0, 0, Vec::new(), tcx.types.bool),
630+
// contract_check_requires::<C>(C) -> bool, where C: impl Fn() -> bool
631+
sym::contract_check_requires => (1, 0, vec![param(0)], tcx.types.bool),
632+
613633
sym::simd_eq
614634
| sym::simd_ne
615635
| sym::simd_lt

compiler/rustc_middle/src/mir/pretty.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1103,6 +1103,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
11031103
NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
11041104
NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
11051105
NullOp::UbChecks => write!(fmt, "UbChecks()"),
1106+
NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
11061107
}
11071108
}
11081109
ThreadLocalRef(did) => ty::tls::with(|tcx| {

compiler/rustc_middle/src/mir/syntax.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1591,6 +1591,9 @@ pub enum NullOp<'tcx> {
15911591
/// Returns whether we should perform some UB-checking at runtime.
15921592
/// See the `ub_checks` intrinsic docs for details.
15931593
UbChecks,
1594+
/// Returns whether we should perform contract-checking at runtime.
1595+
/// See the `contract_checks` intrinsic docs for details.
1596+
ContractChecks,
15941597
}
15951598

15961599
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]

compiler/rustc_middle/src/mir/tcx.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,8 @@ impl<'tcx> Rvalue<'tcx> {
230230
Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(..), _) => {
231231
tcx.types.usize
232232
}
233-
Rvalue::NullaryOp(NullOp::UbChecks, _) => tcx.types.bool,
233+
Rvalue::NullaryOp(NullOp::ContractChecks, _)
234+
| Rvalue::NullaryOp(NullOp::UbChecks, _) => tcx.types.bool,
234235
Rvalue::Aggregate(ref ak, ref ops) => match **ak {
235236
AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
236237
AggregateKind::Tuple => {

compiler/rustc_mir_dataflow/src/move_paths/builder.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,11 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> {
417417
| Rvalue::Discriminant(..)
418418
| Rvalue::Len(..)
419419
| Rvalue::NullaryOp(
420-
NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(..) | NullOp::UbChecks,
420+
NullOp::SizeOf
421+
| NullOp::AlignOf
422+
| NullOp::OffsetOf(..)
423+
| NullOp::UbChecks
424+
| NullOp::ContractChecks,
421425
_,
422426
) => {}
423427
}

compiler/rustc_mir_transform/src/gvn.rs

+1
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> {
545545
.offset_of_subfield(self.typing_env(), layout, fields.iter())
546546
.bytes(),
547547
NullOp::UbChecks => return None,
548+
NullOp::ContractChecks => return None,
548549
};
549550
let usize_layout = self.ecx.layout_of(self.tcx.types.usize).unwrap();
550551
let imm = ImmTy::from_uint(val, usize_layout);

compiler/rustc_mir_transform/src/known_panics_lint.rs

+1
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
629629
.offset_of_subfield(self.typing_env, op_layout, fields.iter())
630630
.bytes(),
631631
NullOp::UbChecks => return None,
632+
NullOp::ContractChecks => return None,
632633
};
633634
ImmTy::from_scalar(Scalar::from_target_usize(val, self), layout).into()
634635
}

compiler/rustc_mir_transform/src/lower_intrinsics.rs

+11
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics {
3434
});
3535
terminator.kind = TerminatorKind::Goto { target };
3636
}
37+
sym::contract_checks => {
38+
let target = target.unwrap();
39+
block.statements.push(Statement {
40+
source_info: terminator.source_info,
41+
kind: StatementKind::Assign(Box::new((
42+
*destination,
43+
Rvalue::NullaryOp(NullOp::ContractChecks, tcx.types.bool),
44+
))),
45+
});
46+
terminator.kind = TerminatorKind::Goto { target };
47+
}
3748
sym::forget => {
3849
let target = target.unwrap();
3950
block.statements.push(Statement {

compiler/rustc_mir_transform/src/promote_consts.rs

+1
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,7 @@ impl<'tcx> Validator<'_, 'tcx> {
457457
NullOp::AlignOf => {}
458458
NullOp::OffsetOf(_) => {}
459459
NullOp::UbChecks => {}
460+
NullOp::ContractChecks => {}
460461
},
461462

462463
Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),

compiler/rustc_mir_transform/src/validate.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1379,7 +1379,10 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
13791379
Rvalue::Repeat(_, _)
13801380
| Rvalue::ThreadLocalRef(_)
13811381
| Rvalue::RawPtr(_, _)
1382-
| Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::UbChecks, _)
1382+
| Rvalue::NullaryOp(
1383+
NullOp::SizeOf | NullOp::AlignOf | NullOp::UbChecks | NullOp::ContractChecks,
1384+
_,
1385+
)
13831386
| Rvalue::Discriminant(_) => {}
13841387

13851388
Rvalue::WrapUnsafeBinder(op, ty) => {

compiler/rustc_session/src/config/cfg.rs

+7
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ pub(crate) fn disallow_cfgs(sess: &Session, user_cfgs: &Cfg) {
119119
(sym::overflow_checks, None) => disallow(cfg, "-C overflow-checks"),
120120
(sym::debug_assertions, None) => disallow(cfg, "-C debug-assertions"),
121121
(sym::ub_checks, None) => disallow(cfg, "-Z ub-checks"),
122+
(sym::contract_checks, None) => disallow(cfg, "-Z contract-checks"),
122123
(sym::sanitize, None | Some(_)) => disallow(cfg, "-Z sanitizer"),
123124
(
124125
sym::sanitizer_cfi_generalize_pointers | sym::sanitizer_cfi_normalize_integers,
@@ -300,6 +301,11 @@ pub(crate) fn default_configuration(sess: &Session) -> Cfg {
300301
if sess.is_nightly_build() && sess.opts.unstable_opts.emscripten_wasm_eh {
301302
ins_none!(sym::emscripten_wasm_eh);
302303
}
304+
305+
if sess.contract_checks() {
306+
ins_none!(sym::contract_checks);
307+
}
308+
303309
ret
304310
}
305311

@@ -464,6 +470,7 @@ impl CheckCfg {
464470
ins!(sym::target_thread_local, no_values);
465471

466472
ins!(sym::ub_checks, no_values);
473+
ins!(sym::contract_checks, no_values);
467474

468475
ins!(sym::unix, no_values);
469476
ins!(sym::windows, no_values);

compiler/rustc_session/src/options.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2114,6 +2114,8 @@ options! {
21142114
"the backend to use"),
21152115
combine_cgu: bool = (false, parse_bool, [TRACKED],
21162116
"combine CGUs into a single one"),
2117+
contract_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
2118+
"emit runtime checks for contract pre- and post-conditions (default: no)"),
21172119
coverage_options: CoverageOptions = (CoverageOptions::default(), parse_coverage_options, [TRACKED],
21182120
"control details of coverage instrumentation"),
21192121
crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],

compiler/rustc_session/src/session.rs

+4
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,10 @@ impl Session {
709709
self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
710710
}
711711

712+
pub fn contract_checks(&self) -> bool {
713+
self.opts.unstable_opts.contract_checks.unwrap_or(false)
714+
}
715+
712716
pub fn relocation_model(&self) -> RelocModel {
713717
self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
714718
}

compiler/rustc_smir/src/rustc_smir/convert/mir.rs

+1
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ impl<'tcx> Stable<'tcx> for mir::NullOp<'tcx> {
291291
indices.iter().map(|idx| idx.stable(tables)).collect(),
292292
),
293293
UbChecks => stable_mir::mir::NullOp::UbChecks,
294+
ContractChecks => stable_mir::mir::NullOp::ContractChecks,
294295
}
295296
}
296297
}

compiler/rustc_span/src/symbol.rs

+4
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,7 @@ symbols! {
566566
cfg_attr,
567567
cfg_attr_multi,
568568
cfg_boolean_literals,
569+
cfg_contract_checks,
569570
cfg_doctest,
570571
cfg_emscripten_wasm_eh,
571572
cfg_eval,
@@ -675,6 +676,9 @@ symbols! {
675676
const_ty_placeholder: "<const_ty>",
676677
constant,
677678
constructor,
679+
contract_check_ensures,
680+
contract_check_requires,
681+
contract_checks,
678682
convert_identity,
679683
copy,
680684
copy_closures,

compiler/stable_mir/src/mir/body.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,8 @@ impl Rvalue {
608608
Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(..), _) => {
609609
Ok(Ty::usize_ty())
610610
}
611-
Rvalue::NullaryOp(NullOp::UbChecks, _) => Ok(Ty::bool_ty()),
611+
Rvalue::NullaryOp(NullOp::ContractChecks, _)
612+
| Rvalue::NullaryOp(NullOp::UbChecks, _) => Ok(Ty::bool_ty()),
612613
Rvalue::Aggregate(ak, ops) => match *ak {
613614
AggregateKind::Array(ty) => Ty::try_new_array(ty, ops.len() as u64),
614615
AggregateKind::Tuple => Ok(Ty::new_tuple(
@@ -1007,6 +1008,8 @@ pub enum NullOp {
10071008
OffsetOf(Vec<(VariantIdx, FieldIdx)>),
10081009
/// cfg!(ub_checks), but at codegen time
10091010
UbChecks,
1011+
/// cfg!(contract_checks), but at codegen time
1012+
ContractChecks,
10101013
}
10111014

10121015
impl Operand {

library/core/src/intrinsics/mod.rs

+32
Original file line numberDiff line numberDiff line change
@@ -4044,6 +4044,38 @@ pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize)
40444044
// Runtime NOP
40454045
}
40464046

4047+
/// Returns whether we should perform contract-checking at runtime.
4048+
///
4049+
/// This is meant to be similar to the ub_checks intrinsic, in terms
4050+
/// of not prematurely commiting at compile-time to whether contract
4051+
/// checking is turned on, so that we can specify contracts in libstd
4052+
/// and let an end user opt into turning them on.
4053+
#[cfg(not(bootstrap))]
4054+
#[rustc_const_unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
4055+
#[unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
4056+
#[inline(always)]
4057+
#[rustc_intrinsic]
4058+
pub const fn contract_checks() -> bool {
4059+
// FIXME: should this be `false` or `cfg!(contract_checks)`?
4060+
4061+
// cfg!(contract_checks)
4062+
false
4063+
}
4064+
4065+
#[cfg(not(bootstrap))]
4066+
#[unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
4067+
#[rustc_intrinsic]
4068+
pub fn contract_check_requires<C: FnOnce() -> bool>(c: C) -> bool {
4069+
c()
4070+
}
4071+
4072+
#[cfg(not(bootstrap))]
4073+
#[unstable(feature = "rustc_contracts", issue = "none" /* compiler-team#759 */)]
4074+
#[rustc_intrinsic]
4075+
pub fn contract_check_ensures<'a, Ret, C: FnOnce(&'a Ret) -> bool>(ret: &'a Ret, c: C) -> bool {
4076+
c(ret)
4077+
}
4078+
40474079
/// The intrinsic will return the size stored in that vtable.
40484080
///
40494081
/// # Safety

src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ fn check_rvalue<'tcx>(
179179
))
180180
}
181181
},
182-
Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(_) | NullOp::UbChecks, _)
182+
Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(_) | NullOp::UbChecks | NullOp::ContractChecks, _)
183183
| Rvalue::ShallowInitBox(_, _) => Ok(()),
184184
Rvalue::UnaryOp(_, operand) => {
185185
let ty = operand.ty(body, tcx);

src/tools/miri/src/machine.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1150,6 +1150,11 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
11501150
interp_ok(ecx.tcx.sess.ub_checks())
11511151
}
11521152

1153+
#[inline(always)]
1154+
fn contract_checks(ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool> {
1155+
interp_ok(ecx.tcx.sess.contract_checks())
1156+
}
1157+
11531158
#[inline(always)]
11541159
fn thread_local_static_pointer(
11551160
ecx: &mut MiriInterpCx<'tcx>,

0 commit comments

Comments
 (0)