11//! Provides the [`assert_unsafe_precondition`] macro as well as some utility functions that cover
22//! common preconditions.
33
4- use crate :: intrinsics:: const_eval_select;
4+ use crate :: intrinsics:: { self , const_eval_select} ;
55
66/// Check that the preconditions of an unsafe function are followed. The check is enabled at
77/// runtime if debug assertions are enabled when the caller is monomorphized. In const-eval/Miri
@@ -45,7 +45,7 @@ use crate::intrinsics::const_eval_select;
4545/// order to call it. Since the precompiled standard library is built with full debuginfo and these
4646/// variables cannot be optimized out in MIR, an innocent-looking `let` can produce enough
4747/// debuginfo to have a measurable compile-time impact on debug builds.
48- #[ allow_internal_unstable( ub_checks ) ] // permit this to be called in stably-const fn
48+ #[ allow_internal_unstable( const_ub_checks ) ] // permit this to be called in stably-const fn
4949macro_rules! assert_unsafe_precondition {
5050 ( $kind: ident, $message: expr, ( $( $name: ident: $ty: ty = $arg: expr) ,* $( , ) ?) => $e: expr $( , ) ?) => {
5151 {
@@ -60,7 +60,7 @@ macro_rules! assert_unsafe_precondition {
6060 #[ rustc_no_mir_inline]
6161 #[ inline]
6262 #[ rustc_nounwind]
63- #[ rustc_const_unstable( feature = "ub_checks " , issue = "none" ) ]
63+ #[ rustc_const_unstable( feature = "const_ub_checks " , issue = "none" ) ]
6464 const fn precondition_check( $( $name: $ty) ,* ) {
6565 if !$e {
6666 :: core:: panicking:: panic_nounwind(
@@ -69,14 +69,41 @@ macro_rules! assert_unsafe_precondition {
6969 }
7070 }
7171
72- if :: core:: intrinsics :: $kind( ) {
72+ if :: core:: ub_checks :: $kind( ) {
7373 precondition_check( $( $arg, ) * ) ;
7474 }
7575 }
7676 } ;
7777}
7878pub ( crate ) use assert_unsafe_precondition;
7979
80+ /// Checking library UB is always enabled when UB-checking is done
81+ /// (and we use a reexport so that there is no unnecessary wrapper function).
82+ pub ( crate ) use intrinsics:: ub_checks as check_library_ub;
83+
84+ /// Determines whether we should check for language UB.
85+ ///
86+ /// The intention is to not do that when running in the interpreter, as that one has its own
87+ /// language UB checks which generally produce better errors.
88+ #[ rustc_const_unstable( feature = "const_ub_checks" , issue = "none" ) ]
89+ #[ inline]
90+ pub ( crate ) const fn check_language_ub ( ) -> bool {
91+ #[ inline]
92+ fn runtime ( ) -> bool {
93+ // Disable UB checks in Miri.
94+ !cfg ! ( miri)
95+ }
96+
97+ #[ inline]
98+ const fn comptime ( ) -> bool {
99+ // Always disable UB checks.
100+ false
101+ }
102+
103+ // Only used for UB checks so we may const_eval_select.
104+ intrinsics:: ub_checks ( ) && const_eval_select ( ( ) , comptime, runtime)
105+ }
106+
80107/// Checks whether `ptr` is properly aligned with respect to
81108/// `align_of::<T>()`.
82109///
0 commit comments