diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index 1d7e6ad89a469..2c69b40eb5394 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -140,7 +140,6 @@ //! } //! ``` -#![allow(missing_docs)] #![stable(feature = "rust1", since = "1.0.0")] use core::alloc::Allocator; @@ -1797,6 +1796,7 @@ unsafe impl AsVecIntoIter for IntoIter { } } +/// Iterator which retrieves elements in heap order. #[must_use = "iterators are lazy and do nothing unless consumed"] #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] #[derive(Clone, Debug)] diff --git a/library/alloc/src/io/buffered/bufreader.rs b/library/alloc/src/io/buffered/bufreader.rs index c911746c2a611..a6f264bf29646 100644 --- a/library/alloc/src/io/buffered/bufreader.rs +++ b/library/alloc/src/io/buffered/bufreader.rs @@ -299,7 +299,6 @@ impl BufReader { impl BufReader { #[doc(hidden)] #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")] - #[allow(missing_docs)] pub fn initialized(&self) -> bool { self.buf.initialized() } diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index bd7d5312ee03a..1e2577077ae91 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -666,6 +666,7 @@ impl Layout { note = "Name does not follow std convention, use LayoutError", suggestion = "LayoutError" )] +/// Old name of [`LayoutError`]. pub type LayoutErr = LayoutError; /// The `LayoutError` is returned when the parameters given diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 0cea74244a20e..16e8c6e92d249 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -244,6 +244,10 @@ pub const unsafe trait Allocator { /// returned excess. Implementors are free to e.g. provide an alternate method to query /// available excess if doing so is expensive and should be left to the caller. /// + /// The returned block may be uninitialized, so it is unsound to read it + /// before it is written. Use [`allocate_zeroed`](Self::allocate_zeroed) if + /// zero-initialized memory is needed. + /// /// Note that the returned block of memory is considered [*currently allocated*] /// with this allocator (and equivalent allocators). /// Therefore, it is the responsibility of implementors of `Allocator` to make sure that @@ -265,6 +269,28 @@ pub const unsafe trait Allocator { /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use std::alloc::{Allocator, Layout, System}; + /// + /// let s = "Hello, world!"; + /// let layout = Layout::array::(s.len()).unwrap(); + // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable + /// let ptr = System.allocate(layout).expect("allocation failed").cast::(); + /// + /// // SAFETY: the block is at least `s.len()` bytes long and was just allocated, + /// // so it cannot overlap `s`. + /// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s.as_ptr(), s.len()) }; + /// + /// // SAFETY: the first `s.len()` bytes were initialized by the copy above. + /// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), s.len()) }; + /// assert_eq!(bytes, s.as_bytes()); + /// + /// // SAFETY: `ptr` was allocated by `System` with `layout`. + /// unsafe { System.deallocate(ptr, layout) }; + /// ``` #[stable(feature = "allocator_api", since = "1.100.0")] fn allocate(&self, layout: Layout) -> Result, AllocError>; @@ -283,6 +309,24 @@ pub const unsafe trait Allocator { /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use std::alloc::{Allocator, Layout, System}; + /// + /// let layout = Layout::new::(); + /// let ptr = System.allocate_zeroed(layout).expect("allocation failed"); + /// + /// // N.B. the below would be unsound with `allocate` rather than `allocate_zeroed`. + /// // SAFETY: `allocate_zeroed` returns a valid, initialized block. + /// let bytes = unsafe { ptr.as_ref() }; + /// assert!(bytes.iter().all(|&b| b == 0)); + /// + /// // SAFETY: `ptr` was allocated by `System` with `layout`. + // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable + /// unsafe { System.deallocate(ptr.cast(), layout) }; + /// ``` #[stable(feature = "allocator_api", since = "1.100.0")] fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { let ptr = self.allocate(layout)?; @@ -319,7 +363,9 @@ pub const unsafe trait Allocator { /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*]. /// The old `ptr` must not be used to access the memory, even if the allocation was grown in-place. /// The newly returned pointer is the only valid pointer for accessing this memory now. - /// All bytes past `old_layout.size()` should be assumed to be uninitialised. + /// All bytes past `old_layout.size()` should be assumed to be uninitialised, so it is + /// unsound to read them before they are written. Use [`grow_zeroed`](Self::grow_zeroed) + /// if the new bytes should be zero-initialized. /// /// If this method returns `Err`, then the memory block has not been *invalidated*, /// and the contents of the memory block are unaltered. @@ -349,6 +395,45 @@ pub const unsafe trait Allocator { /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use std::alloc::{Allocator, Layout, System}; + /// + /// let s1 = "Hello"; + /// let s2 = ", world!"; + /// + /// let old_layout = Layout::array::(s1.len()).unwrap(); + // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable + /// let ptr = System.allocate(old_layout).expect("allocation failed").cast::(); + /// + /// // SAFETY: the block is at least `s1.len()` bytes long and was just allocated, + /// // so it cannot overlap `s1`. + /// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s1.as_ptr(), s1.len()) }; + /// + /// let new_layout = Layout::array::(s1.len() + s2.len()).unwrap(); + /// + /// // N.B. the original `ptr` is invalidated by this operation + /// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`, + /// // and `new_layout` is at least as large as `old_layout`. + // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable + /// let ptr = unsafe { System.grow(ptr, old_layout, new_layout) } + /// .expect("grow failed").cast::(); + /// + /// // SAFETY: the block is at least `s1.len() + s2.len()` bytes long, so writing + /// // `s2.len()` bytes at offset `s1.len()` stays in bounds; it cannot overlap `s2`. + /// unsafe { + /// ptr.as_ptr().add(s1.len()).copy_from_nonoverlapping(s2.as_ptr(), s2.len()); + /// } + /// + /// // SAFETY: all bytes within `new_layout.size()` are now initialized. + /// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), new_layout.size()) }; + /// assert_eq!(bytes, b"Hello, world!"); + /// + /// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`. + /// unsafe { System.deallocate(ptr, new_layout) }; + /// ``` #[stable(feature = "allocator_api", since = "1.100.0")] unsafe fn grow( &self, @@ -477,6 +562,33 @@ pub const unsafe trait Allocator { /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html + /// + /// # Examples + /// + /// ``` + /// use std::alloc::{Allocator, Layout, System}; + /// + /// let old_layout = Layout::array::(4).unwrap(); + /// let ptr = System.allocate(old_layout).expect("allocation failed"); + /// + /// // SAFETY: the block holds at least 4 `u32`s and is aligned for `u32`. + /// unsafe { ptr.cast::<[u32; 4]>().write([7, 8, 9, 10]) }; + /// + /// let new_layout = Layout::array::(2).unwrap(); + /// + /// // N.B. the original `ptr` is invalidated by this operation + /// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`, + /// // and `new_layout` is no larger than `old_layout`. + /// let ptr = unsafe { System.shrink(ptr.cast(), old_layout, new_layout) } + /// .expect("shrink failed"); + /// + /// // The contents that fit in the new layout are preserved. + /// // SAFETY: the first two `u32`s were written above and `shrink` kept them. + /// assert_eq!(unsafe { ptr.cast::<[u32; 2]>().read() }, [7, 8]); + /// + /// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`. + /// unsafe { System.deallocate(ptr.cast(), new_layout) }; + /// ``` #[stable(feature = "allocator_api", since = "1.100.0")] unsafe fn shrink( &self, diff --git a/library/core/src/any.rs b/library/core/src/any.rs index c6cb5b0f50c56..88364538146c2 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -819,7 +819,7 @@ impl TypeId { return None; } - if matches!(trait_represented_by_type_id.info().kind, TypeKind::DynTrait(_)) + if matches!(trait_represented_by_type_id.info(), TypeKind::DynTrait) && let Some(vtable) = type_id_vtable(self, trait_represented_by_type_id) { Some(TraitImpl { vtable }) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 83a2925678e19..f75690d8b2f5f 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -240,7 +240,7 @@ use crate::ops::ControlFlow; /// /// [`eq`]: PartialEq::eq /// [`ne`]: PartialEq::ne -#[lang = "eq"] +#[lang = "partial_eq"] #[stable(feature = "rust1", since = "1.0.0")] #[doc(alias = "==")] #[doc(alias = "!=")] @@ -348,6 +348,7 @@ pub macro PartialEq($item:item) { #[doc(alias = "==")] #[doc(alias = "!=")] #[stable(feature = "rust1", since = "1.0.0")] +#[lang = "eq"] #[rustc_diagnostic_item = "Eq"] #[rustc_const_unstable(feature = "const_cmp", issue = "143800")] pub const trait Eq: [const] PartialEq + PointeeSized { diff --git a/library/core/src/error.rs b/library/core/src/error.rs index b6de3eb1b44e5..9504236cad2dc 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -143,7 +143,7 @@ pub trait Error: Debug + Display { since = "1.33.0", note = "replaced by Error::source, which can support downcasting" )] - #[allow(missing_docs)] + /// Replaced by [`Error::source`]. fn cause(&self) -> Option<&dyn Error> { self.source() } diff --git a/library/core/src/field.rs b/library/core/src/field.rs index b17a78846ce2a..295a1a1db14d8 100644 --- a/library/core/src/field.rs +++ b/library/core/src/field.rs @@ -32,9 +32,9 @@ impl fmt::Debug } } let (variant, field) = const { - use crate::mem::type_info::{self, Type, TypeKind}; + use crate::mem::type_info::{self, TypeKind}; let type_id = type_info::of::(); - match Type::of::().kind { + match TypeKind::of::() { TypeKind::Struct => (None, Member::Name(type_id.field(0, FIELD as usize).name())), TypeKind::Tuple => (None, Member::Index(FIELD)), TypeKind::Enum => { diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 96dde7a11891b..eb122c3a4294d 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -1048,6 +1048,7 @@ impl Display for Arguments<'_> { message = "`{Self}` doesn't implement `{this}`" )] #[doc(alias = "{:?}")] +#[lang = "debug"] #[rustc_diagnostic_item = "Debug"] pub trait Debug: PointeeSized { #[doc = include_str!("fmt_trait_method_doc.md")] diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index c69e706b9c0ec..f0cd83cc8b9f4 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -109,15 +109,19 @@ use crate::sync::atomic::{ /// A type for atomic ordering parameters for intrinsics. This is a separate type from /// `atomic::Ordering` so that we can make it `ConstParamTy` and fix the values used here without a /// risk of leaking that to stable code. -#[allow(missing_docs)] #[derive(Debug, ConstParamTy, PartialEq, Eq)] pub enum AtomicOrdering { // These values must match the compiler's `AtomicOrdering` defined in // `rustc_middle/src/ty/consts/int.rs`! + /// [`Ordering::Relaxed`][`crate::sync::atomic::Ordering::Relaxed`] Relaxed = 0, + /// [`Ordering::Release`][`crate::sync::atomic::Ordering::Release`] Release = 1, + /// [`Ordering::Acquire`][`crate::sync::atomic::Ordering::Acquire`] Acquire = 2, + /// [`Ordering::AcqRel`][`crate::sync::atomic::Ordering::AcqRel`] AcqRel = 3, + /// [`Ordering::SeqCst`][`crate::sync::atomic::Ordering::SeqCst`] SeqCst = 4, } @@ -3934,8 +3938,10 @@ mod verify { //The follow are harnesses that check our function contract (specifically the weakness/strength //of our generic validity precondition) //In particular, should_succeed harnesses check that type-specific validity preconditions imply our generic precondition - //should_fail harnesses check that when we assume the negation of a type-specific validity - //precondition, the harness should trigger at least one failure + // The `should_fail_*` harnesses show that `transmute_unchecked_wrapper`'s precondition + // rejects every input whose bytes aren't a valid value of the output type. They assert that + // the precondition is false rather than calling the wrapper under `should_panic`: Kani + // doesn't count a failed contract condition as a panic. #[kani::proof] #[kani::stub_verified(transmute_unchecked_wrapper)] @@ -3945,11 +3951,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_u32_to_char() { let src: u32 = kani::any_where(|x| !core::char::from_u32(*x).is_some()); - let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const u32 as *const char)); } #[kani::proof] @@ -3962,13 +3966,11 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_f32_to_char() { let src: f32 = kani::any_where(|x| { !char::from_u32(unsafe { *(x as *const f32 as *const u32) }).is_some() }); - let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const f32 as *const char)); } #[kani::proof] @@ -3979,11 +3981,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_i32_to_char() { let src: i32 = kani::any_where(|x| !char::from_u32(*x as u32).is_some()); - let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const i32 as *const char)); } #[kani::proof] @@ -3994,11 +3994,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_u8_to_bool() { let src: u8 = kani::any_where(|x| *x > 1); - let dst: bool = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const u8 as *const bool)); } #[kani::proof] @@ -4009,11 +4007,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_i8_to_bool() { let src: u8 = kani::any_where(|x| *x as u8 > 1); - let dst: bool = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const u8 as *const bool)); } //The following harnesses do the same as above, but for compound types @@ -4039,11 +4035,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_tuple_to_struct() { let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x > 1)); - let dst: struct_A = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const struct_A)); } #[kani::proof] @@ -4054,11 +4048,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_tuple_to_tuple() { let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x > 1)); - let dst: (u8, bool) = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const (u8, bool))); } #[kani::proof] @@ -4069,11 +4061,9 @@ mod verify { } #[kani::proof] - #[kani::stub_verified(transmute_unchecked_wrapper)] - #[kani::should_panic] fn should_fail_tuple_to_array() { let src: (u8, u8) = (kani::any_where(|x| *x > 1), kani::any_where(|x| *x > 1)); - let dst: [bool; 2] = unsafe { transmute_unchecked_wrapper(src) }; + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const [bool; 2])); } //generates should_succeed harnesses when the output type has no possible invalid values, like ints diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index 0054cd32cdc03..0e071b2df3faa 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -25,7 +25,7 @@ pub fn type_id() -> crate::any::TypeId; /// not implement it. #[rustc_intrinsic] #[rustc_comptime] -pub fn type_id_type_of(_id: crate::any::TypeId) -> crate::mem::type_info::Type; +pub fn type_id_type_of(_id: crate::any::TypeId) -> crate::mem::type_info::TypeKind; /// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the /// same type. This is necessary because at const-eval time the actual discriminating @@ -118,6 +118,19 @@ pub fn type_id_variant_reflected_attrs( _variant_index: usize, ) -> &'static [&'static str]; +/// Gets the raw documentation attributes of the variant represented by the base `TypeId` and variant_idx. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::docs`]. +/// +/// [`TypeId`]: crate::any::TypeId +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_variant_docs( + _base: crate::any::TypeId, + _variant_index: usize, +) -> &'static [&'static str]; + /// Returns true when the variant represented by the base `TypeId` and variant_idx is non /// exhaustive. /// @@ -176,6 +189,14 @@ pub fn type_id_points_to(_id: crate::any::TypeId) -> Option; #[rustc_comptime] pub fn type_id_points_mutably(_id: crate::any::TypeId) -> bool; +/// Given a `TypeId` that represents a dyn trait returns an [`core::mem::type_info::DynTrait`]. When called on +/// something else this returns `None`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::dyn_trait`]. +#[rustc_intrinsic] +#[rustc_comptime] +pub fn type_id_dyn_trait(_type_id: crate::any::TypeId) -> Option; + /// Given a `TypeId` that represents a function pointer returns an [`core::mem::type_info::FnPtr`]. /// When called on something else this returns `None`. /// @@ -190,3 +211,11 @@ pub fn type_id_function_ptr(_type_id: crate::any::TypeId) -> Option &'static [&'static str]; + +/// Returns the raw documentation attributes given a `TypeId` which represents a structure, enumeration, union or `FieldId`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::docs`]. +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_docs(_type_id: crate::any::TypeId) -> &'static [&'static str]; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index c122e71115cbb..d568f465c26d8 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -348,7 +348,6 @@ pub mod future; pub mod task; /* Heap memory allocator trait */ -#[allow(missing_docs)] pub mod alloc; // note: does not need to be public diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 15a808609e0c8..bc498f2ae9ee1 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -84,6 +84,7 @@ macro marker_impls { /// [arc]: ../../std/sync/struct.Arc.html /// [ub]: ../../reference/behavior-considered-undefined.html #[stable(feature = "rust1", since = "1.0.0")] +#[lang = "send"] #[rustc_diagnostic_item = "Send"] #[diagnostic::on_unimplemented( message = "`{Self}` cannot be sent between threads safely", diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 1ad39e3c2f3ac..9082128990a04 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -9,11 +9,44 @@ use crate::{fmt, intrinsics}; /// Compile-time type information. #[derive(Debug)] #[non_exhaustive] -#[lang = "type_info"] +#[lang = "type_kind"] #[unstable(feature = "type_info", issue = "146922")] -pub struct Type { - /// Per-type information - pub kind: TypeKind, +pub enum TypeKind { + /// Tuples. + Tuple, + /// Arrays. + Array, + /// Slices. + Slice, + /// Dynamic Traits. + DynTrait, + /// Structs. + Struct, + /// Enums. + Enum, + /// Unions. + Union, + /// Primitive boolean type. + Bool, + /// Primitive character type. + Char, + /// Primitive signed and unsigned integer type. + Int, + /// Primitive floating-point type. + Float, + /// String slice type. + Str, + /// References. + Reference, + /// Pointers. + Pointer, + /// Function pointers. + FnPtr, + /// Never type. + Never, + /// FIXME(#146922): add all the common types + /// non exhaustive list + Other, } /// Info of a trait implementation, you can retrieve the vtable with [Self::get_vtable] @@ -36,12 +69,12 @@ impl TypeId { #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] #[rustc_comptime] - pub fn info(self) -> Type { + pub fn info(self) -> TypeKind { intrinsics::reflection::type_id_type_of(self) } } -impl Type { +impl TypeKind { /// Returns the type information of the generic type parameter. /// /// Note: Unlike `TypeId`s obtained via `TypeId::of`, the `Type` @@ -69,51 +102,11 @@ pub const fn of() -> TypeId { const { intrinsics::reflection::type_id::() } } -/// Compile-time type information. -#[derive(Debug)] -#[non_exhaustive] -#[unstable(feature = "type_info", issue = "146922")] -pub enum TypeKind { - /// Tuples. - Tuple, - /// Arrays. - Array, - /// Slices. - Slice, - /// Dynamic Traits. - DynTrait(DynTrait), - /// Structs. - Struct, - /// Enums. - Enum, - /// Unions. - Union, - /// Primitive boolean type. - Bool, - /// Primitive character type. - Char, - /// Primitive signed and unsigned integer type. - Int, - /// Primitive floating-point type. - Float, - /// String slice type. - Str(Str), - /// References. - Reference, - /// Pointers. - Pointer, - /// Function pointers. - FnPtr, - /// FIXME(#146922): add all the common types - /// non exhaustive list: - /// - Never - Other, -} - /// Compile-time type information about dynamic traits. /// FIXME(#146922): Add super traits and generics #[derive(Debug)] #[non_exhaustive] +#[lang = "DynTrait"] #[unstable(feature = "type_info", issue = "146922")] pub struct DynTrait { /// The predicates of a dynamic trait. @@ -293,6 +286,39 @@ impl TypeId { intrinsics::reflection::type_id_element_ty(self) } + /// Given a `TypeId` that represents a dyn trait returns an + /// [`DynTrait`]. When called on something else this returns `None`. + /// + /// # Examples + /// + /// + /// ``` + /// #![feature(type_info)] + /// use std::any::TypeId; + /// use std::fmt::Debug; + /// + /// #[derive(Debug)] + /// struct A; + /// + /// const { + /// let dyn_id = TypeId::of::(); + /// let predicates = dyn_id.dyn_trait().unwrap().predicates; + /// + /// let debug_ty = predicates[0].trait_ty.ty; + /// let send_ty = predicates[1].trait_ty.ty; + /// + /// let type_id = TypeId::of::(); + /// + /// assert!(type_id.trait_info_of_trait_type_id(debug_ty).is_some()); + /// assert!(type_id.trait_info_of_trait_type_id(send_ty).is_none()); + /// } + /// ``` + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn dyn_trait(self) -> Option { + intrinsics::reflection::type_id_dyn_trait(self) + } + /// When called on a `TypeId` representing an array this returns the length of the array in /// all other cases this returns zero. /// @@ -679,6 +705,26 @@ impl TypeId { pub fn reflected_attrs(self) -> &'static [&'static str] { intrinsics::reflection::type_id_reflected_attrs(self) } + + /// Returns the raw documentation attributes when given a `TypeId` which represents a structure, enumeration or union. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// #[doc = "first"] + /// /** second + /// * third + /// */ + /// struct A; + /// + /// assert_eq!(const { TypeId::of::().docs() }, ["first", " second\n* third\n"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self) + } } /// Variant representing type ID. Representing a variant of an enum. @@ -721,6 +767,28 @@ impl VariantId { intrinsics::reflection::type_id_variant_name(self.base, self.variant) } + /// Returns the raw documentation attributes when given a `VariantId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// enum A { + /// #[doc = "first"] + /// /** second + /// * third*/ + /// B, + /// C, + /// } + /// + /// assert_eq!(const { TypeId::of::().variant(0).docs() }, ["first", " second\n * third"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_variant_docs(self.base, self.variant) + } + /// Returns whether this variant is marked with `#[non_exhaustive]`. #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -815,6 +883,27 @@ impl FieldId { pub fn name(self) -> &'static str { intrinsics::field_representing_type_name(self.frt_type_id) } + + /// Returns the raw documentation attributes when given a `FieldId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// struct A { + /// #[doc = "first"] + /// /// second + /// first: u8, + /// } + /// + /// assert_eq!(const { TypeId::of::().field(0, 0).docs() }, ["first", " second"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self.frt_type_id) + } + /// Returns the offset of the field wrt to its containing type. /// /// ``` diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 8a5e0f035d775..767707458d6a9 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -21,7 +21,7 @@ //! necessary lang items for the compiler. All panics are funneled through this //! one function. The actual symbol is declared through the `#[panic_handler]` attribute. -#![allow(dead_code, missing_docs)] +#![allow(dead_code)] #![unstable( feature = "panic_internals", reason = "internal details of the implementation of the `panic!` and related macros", @@ -182,6 +182,7 @@ macro_rules! panic_const { // slightly different forms. It's not clear if there's a good way to deduplicate without adding // special cases to the compiler (e.g., a const generic function wouldn't have a single definition // shared across crates, which is exactly what we want here). +#[allow(missing_docs)] pub mod panic_const { use super::*; panic_const! { @@ -233,9 +234,10 @@ pub fn panic_nounwind_nobacktrace(expr: &'static str) -> ! { panic_nounwind_fmt(fmt::Arguments::from_str(expr), /* force_no_backtrace */ true); } +/// Needed by `non-fmt-panics` lint. #[inline] #[track_caller] -#[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint +#[rustc_diagnostic_item = "unreachable_display"] pub fn unreachable_display(x: &T) -> ! { panic_fmt(format_args!("internal error: entered unreachable code: {}", *x)); } @@ -250,9 +252,10 @@ pub const fn panic_str_2015(expr: &str) -> ! { panic_display(&expr); } +/// Needed for const-evaluated panics. #[inline] #[track_caller] -#[lang = "panic_display"] // needed for const-evaluated panics +#[lang = "panic_display"] #[rustc_do_not_const_check] // hooked by const-eval #[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable pub const fn panic_display(x: &T) -> ! { @@ -457,7 +460,7 @@ fn assert_failed_inner( } } -// panic!() without args expands to this, to generate slightly less code +/// `panic!()` without args expands to this, to generate slightly less code. #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)] #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] @@ -465,7 +468,7 @@ pub const fn panic_default_msg() -> ! { panic("explicit panic") } -// unreachable!() without args expands to this, to generate slightly less code +/// `unreachable!()` without args expands to this, to generate slightly less code. #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)] #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] @@ -473,7 +476,7 @@ pub const fn unreachable_default_msg() -> ! { panic("internal error: entered unreachable code") } -// unimplemented!() without args expands to this, to generate slightly less code +/// `unimplemented!()` without args expands to this, to generate slightly less code. #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)] #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] @@ -481,7 +484,7 @@ pub const fn unimplemented_default_msg() -> ! { panic("not implemented") } -// todo!() without args expands to this, to generate slightly less code +/// `todo!()` without args expands to this, to generate slightly less code. #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)] #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index 2e05943aafc82..4b786db94b9e1 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -102,9 +102,9 @@ pub(crate) const fn check_language_ub() -> bool { false } else { // Disable UB checks in Miri. - !cfg!(miri) + !cfg!(miri) && intrinsics::ub_checks() } - ) && intrinsics::ub_checks() + ) } /// Checks whether `ptr` is properly aligned with respect to the given alignment, and diff --git a/library/coretests/tests/mem/fn_ptr.rs b/library/coretests/tests/mem/fn_ptr.rs index 862048e4090d4..a4313ac744e43 100644 --- a/library/coretests/tests/mem/fn_ptr.rs +++ b/library/coretests/tests/mem/fn_ptr.rs @@ -1,5 +1,5 @@ use std::any::TypeId; -use std::mem::type_info::{Abi, FnPtr, Type, TypeKind}; +use std::mem::type_info::{Abi, FnPtr, TypeKind}; const STRING_TY: TypeId = const { TypeId::of::() }; const U8_TY: TypeId = const { TypeId::of::() }; @@ -18,15 +18,12 @@ fn test_fn_ptrs() { } #[test] -fn test_typekind() { - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!(const { Type::of::().kind }, TypeKind::FnPtr)); - assert!(matches!( - const { Type::of::().kind }, - TypeKind::FnPtr - )); +fn test_type() { + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); + assert!(matches!(const { TypeKind::of::() }, TypeKind::FnPtr)); } #[test] diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 76e2adad18f1c..f119b0c97a9d7 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -2,12 +2,12 @@ use std::any::{Any, TypeId}; use std::mem::offset_of; -use std::mem::type_info::{Const, Generic, GenericType, Type, TypeKind}; +use std::mem::type_info::{Const, Generic, GenericType, TypeKind}; #[test] fn test_arrays() { // Normal array. - assert!(matches!(Type::of::<[u16; 4]>().kind, TypeKind::Array)); + assert!(matches!(TypeKind::of::<[u16; 4]>(), TypeKind::Array)); const { let ty_id = TypeId::of::<[u16; 4]>(); assert!(ty_id.element_ty() == Some(TypeId::of::())); @@ -15,7 +15,7 @@ fn test_arrays() { } // Zero-length array. - assert!(matches!(Type::of::<[bool; 0]>().kind, TypeKind::Array)); + assert!(matches!(TypeKind::of::<[bool; 0]>(), TypeKind::Array)); const { let ty_id = TypeId::of::<[bool; 0]>(); assert!(ty_id.element_ty() == Some(TypeId::of::())); @@ -25,12 +25,17 @@ fn test_arrays() { #[test] fn test_slices() { - assert!(matches!(Type::of::<[usize]>().kind, TypeKind::Slice)); + assert!(matches!(TypeKind::of::<[usize]>(), TypeKind::Slice)); const { assert!(TypeId::of::<[usize]>().element_ty() == Some(TypeId::of::())); } } +#[test] +fn test_never() { + assert!(matches!(TypeKind::of::(), TypeKind::Never)); +} + #[test] fn test_tuples() { const { @@ -58,11 +63,15 @@ fn test_tuples() { fn test_structs() { const { #[reflective_tool::TestStruct] + ///test-doc struct TestStruct { #[reflective_tool::first(1)] #[reflective_tool::first(2)] + #[doc = "first-doc 1"] + ///first-doc 2 first: u8, #[reflective_tool::second] + /// second-doc second: u16, reference: &'static u16, } @@ -71,6 +80,7 @@ fn test_structs() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::TestStruct]"]); + assert!(ty_id.docs() == &["test-doc"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); @@ -80,13 +90,16 @@ fn test_structs() { ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first(1)]", "#[reflective_tool::first(2)]"] ); + assert!(ty_id.field(0, 0).docs() == &["first-doc 1", "first-doc 2"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); + assert!(ty_id.field(0, 1).docs() == &[" second-doc"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); + assert!(ty_id.field(0, 2).docs() == &[""; 0]); } const { @@ -107,17 +120,21 @@ fn test_structs() { assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).name() == "0"); + assert!(ty_id.field(0, 0).docs() == &[""; 0]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).name() == "1"); + assert!(ty_id.field(0, 1).docs() == &[""; 0]); } const { #[reflective_tool::a] + ///doc struct Generics<'a, T, const C: u64> { a: &'a T, } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); @@ -136,34 +153,43 @@ fn test_structs() { fn test_unions() { const { #[reflective_tool::a] + ///test-doc 1 + ///test-doc 2 union TestUnion { #[reflective_tool::first] + #[doc = "first-doc"] first: i16, #[reflective_tool::second] + ///second-doc second: u16, } let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["test-doc 1", "test-doc 2"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 0).name() == "first"); + assert!(ty_id.field(0, 0).docs() == &["first-doc"]); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first]"]); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).docs() == &["second-doc"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); } const { #[reflective_tool::a] + ///doc union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); @@ -184,16 +210,21 @@ fn test_unions() { fn test_enums() { const { #[reflective_tool::a] + ///doc enum E { #[reflective_tool::some] + ///somedoc Some(u32), #[reflective_tool::none] + ///nonedoc None, #[reflective_tool::foomp] #[non_exhaustive] + ///foompdoc Foomp { a: (), #[reflective_tool::b] + ///bdoc b: &'static str, }, } @@ -202,27 +233,32 @@ fn test_enums() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); assert!(ty_id.variant(0).reflected_attrs() == &["#[reflective_tool::some]"]); + assert!(ty_id.variant(0).docs() == &["somedoc"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); assert!(ty_id.variant(1).reflected_attrs() == &["#[reflective_tool::none]"]); + assert!(ty_id.variant(1).docs() == &["nonedoc"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); assert!(ty_id.variant(2).reflected_attrs() == &["#[reflective_tool::foomp]"]); + assert!(ty_id.variant(2).docs() == &["foompdoc"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflective_tool::b]"]); + assert!(ty_id.field(2, 1).docs() == &["bdoc"]); assert!(ty_id.generics().is_empty()); } @@ -251,56 +287,64 @@ fn test_primitives() { use TypeKind::*; const { - let Type { kind: Bool, .. } = (const { Type::of::() }) else { panic!() }; + let Bool = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; + let Char = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; + let Int = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; + let Float = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); - let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; + let Str = (const { TypeKind::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); } } @@ -310,7 +354,7 @@ fn test_references() { use TypeKind::Reference; // Immutable reference. - let Type { kind: Reference, .. } = Type::of::<&u8>() else { panic!() }; + let Reference = TypeKind::of::<&u8>() else { panic!() }; const { let ty = TypeId::of::<&u8>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -318,7 +362,7 @@ fn test_references() { } // Mutable references. - let Type { kind: Reference, .. } = Type::of::<&mut u64>() else { panic!() }; + let Reference = TypeKind::of::<&mut u64>() else { panic!() }; const { let ty = TypeId::of::<&mut u64>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -326,7 +370,7 @@ fn test_references() { } // Wide references. - let Type { kind: Reference, .. } = Type::of::<&dyn Any>() else { panic!() }; + let Reference = TypeKind::of::<&dyn Any>() else { panic!() }; const { let ty = TypeId::of::<&dyn Any>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -339,7 +383,7 @@ fn test_pointers() { use TypeKind::Pointer; // Immutable pointer. - let Type { kind: Pointer, .. } = Type::of::<*const u8>() else { panic!() }; + let Pointer = TypeKind::of::<*const u8>() else { panic!() }; const { let ty = TypeId::of::<*const u8>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -347,7 +391,7 @@ fn test_pointers() { } // Mutable pointer. - let Type { kind: Pointer, .. } = Type::of::<*mut u64>() else { panic!() }; + let Pointer = TypeKind::of::<*mut u64>() else { panic!() }; const { let ty = TypeId::of::<*mut u64>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -355,7 +399,7 @@ fn test_pointers() { } // Wide pointer. - let Type { kind: Pointer, .. } = Type::of::<*const dyn Any>() else { panic!() }; + let Pointer = TypeKind::of::<*const dyn Any>() else { panic!() }; const { let ty = TypeId::of::<*const dyn Any>(); assert!(ty.points_to() == Some(TypeId::of::())); @@ -378,10 +422,7 @@ fn test_dynamic_traits() { trait ProjectorTrait<'a, 'b> {} fn preds_of() -> &'static [DynTraitPredicate] { - match const { Type::of::() }.kind { - TypeKind::DynTrait(d) => d.predicates, - _ => unreachable!(), - } + const { TypeId::of::().dyn_trait() }.unwrap().predicates } fn pred<'a>(preds: &'a [DynTraitPredicate], want: TypeId) -> &'a DynTraitPredicate { diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 3e7634092132b..596aec04a6277 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -75,7 +75,7 @@ pub fn current_dir() -> io::Result { /// assert!(env::set_current_dir(&root).is_ok()); /// println!("Successfully changed working directory to {}!", root.display()); /// ``` -#[doc(alias = "chdir", alias = "SetCurrentDirectory", alias = "SetCurrentDirectoryW")] +#[doc(alias = "cd", alias = "chdir", alias = "SetCurrentDirectory", alias = "SetCurrentDirectoryW")] #[stable(feature = "env", since = "1.0.0")] pub fn set_current_dir>(path: P) -> io::Result<()> { paths_imp::chdir(path.as_ref()) diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index f72a55366bfdd..0e630fc976e8a 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -97,15 +97,15 @@ const fn stderr_raw() -> StderrRaw { impl Read for StdinRaw { fn read(&mut self, buf: &mut [u8]) -> io::Result { - handle_ebadf(self.0.read(buf), || Ok(0)) + self.0.read(buf) } fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { - handle_ebadf(self.0.read_buf(buf), || Ok(())) + self.0.read_buf(buf) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { - handle_ebadf(self.0.read_vectored(bufs), || Ok(0)) + self.0.read_vectored(bufs) } #[inline] @@ -117,33 +117,32 @@ impl Read for StdinRaw { if buf.is_empty() { return Ok(()); } - handle_ebadf(self.0.read_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_exact(buf) } fn read_buf_exact(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { if buf.capacity() == 0 { return Ok(()); } - handle_ebadf(self.0.read_buf_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_buf_exact(buf) } fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { - handle_ebadf(self.0.read_to_end(buf), || Ok(0)) + self.0.read_to_end(buf) } fn read_to_string(&mut self, buf: &mut String) -> io::Result { - handle_ebadf(self.0.read_to_string(buf), || Ok(0)) + self.0.read_to_string(buf) } } impl Write for StdoutRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -152,30 +151,29 @@ impl Write for StdoutRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) + self.0.write_fmt(fmt) } } impl Write for StderrRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -184,26 +182,19 @@ impl Write for StderrRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) - } -} - -fn handle_ebadf(r: io::Result, default: impl FnOnce() -> io::Result) -> io::Result { - match r { - Err(ref e) if stdio::is_ebadf(e) => default(), - r => r, + self.0.write_fmt(fmt) } } @@ -1158,7 +1149,9 @@ where return; } - if let Err(e) = global_s().write_fmt(args) { + if let Err(e) = global_s().write_fmt(args) + && !stdio::is_ebadf(&e) + { panic!("failed printing to {label}: {e}"); } } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index eddcb8f5c96a6..320a114963110 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -270,6 +270,7 @@ // // Language features: // tidy-alphabetical-start +#![feature(abort_immediate)] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -280,6 +281,7 @@ #![feature(cfg_target_has_threads)] #![feature(cfg_target_thread_local)] #![feature(cfi_encoding)] +#![feature(const_eval_select)] #![feature(const_trait_impl)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index 7f3b00a315862..ae1bf03eb28b5 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -1110,16 +1110,20 @@ impl TcpListener { self.0.hop_limit_v6() } + /// Only allow v6 for this socket. + /// + /// ⚠️: This option can only be set before the socket is bound. #[stable(feature = "net2_mutators", since = "1.9.0")] #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")] - #[allow(missing_docs)] pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { self.0.set_only_v6(only_v6) } + /// Checks if this socket only allow v6. + /// + /// ⚠️: This option can only be set before the socket is bound. #[stable(feature = "net2_mutators", since = "1.9.0")] #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")] - #[allow(missing_docs)] pub fn only_v6(&self) -> io::Result { self.0.only_v6() } diff --git a/library/std/src/num/f32.rs b/library/std/src/num/f32.rs index 67d72e8ecd638..738b6e1964cdd 100644 --- a/library/std/src/num/f32.rs +++ b/library/std/src/num/f32.rs @@ -10,7 +10,6 @@ //! defined directly on the `f32` type. #![stable(feature = "rust1", since = "1.0.0")] -#![allow(missing_docs)] #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, clippy::legacy_numeric_constants)] diff --git a/library/std/src/num/f64.rs b/library/std/src/num/f64.rs index dcab1615780b2..2b586321235c4 100644 --- a/library/std/src/num/f64.rs +++ b/library/std/src/num/f64.rs @@ -10,7 +10,6 @@ //! defined directly on the `f64` type. #![stable(feature = "rust1", since = "1.0.0")] -#![allow(missing_docs)] #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, clippy::legacy_numeric_constants)] diff --git a/library/std/src/num/mod.rs b/library/std/src/num/mod.rs index 2feaae34135fe..3d9e26569d40f 100644 --- a/library/std/src/num/mod.rs +++ b/library/std/src/num/mod.rs @@ -4,7 +4,6 @@ //! work. See the individual documentation for each piece for more information. #![stable(feature = "rust1", since = "1.0.0")] -#![allow(missing_docs)] #[unstable(feature = "complex_numbers", issue = "154023")] pub use core::num::Complex; diff --git a/library/std/src/os/windows/fs.rs b/library/std/src/os/windows/fs.rs index a955567b57465..b7b2ad6e403d7 100644 --- a/library/std/src/os/windows/fs.rs +++ b/library/std/src/os/windows/fs.rs @@ -219,6 +219,9 @@ pub trait FileExt { /// from the current cursor. The current cursor **is** affected by this /// function, it is set to the end of the write. /// + /// If the file was opened for appending (via [`OpenOptions::append`]), this is equivalent + /// to `write`: the `offset` is ignored, and `buf` is appended at the end of the file. + /// /// When writing beyond the end of the file, the file is appropriately /// extended and the intermediate bytes are set to zero. /// diff --git a/library/std/src/process.rs b/library/std/src/process.rs index cc7fab7aba9d1..fb3b72607e4d8 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -174,6 +174,8 @@ ))] mod tests; +use core::intrinsics; + use crate::ffi::OsStr; use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; @@ -2642,11 +2644,15 @@ pub fn exit(code: i32) -> ! { /// /// [panic hook]: crate::panic::set_hook #[stable(feature = "process_abort", since = "1.17.0")] +#[rustc_const_unstable(feature = "const_abort", issue = "166193")] #[cold] #[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -pub fn abort() -> ! { - crate::sys::abort_internal(); +pub const fn abort() -> ! { + // Some code uses `abort` as a non-unwinding alternative to `panic`. That + // should work in const, but `sys` code invokes native host functions. So we + // invoke `intrinsics::crash` instead to safely hard-abort execution. + intrinsics::const_eval_select((), crash, crate::sys::abort_internal) } #[doc(inline)] diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 4b0bbdaf073ca..9b6eec8e322b8 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -1,4 +1,4 @@ -#![allow(missing_docs, nonstandard_style)] +#![allow(nonstandard_style)] use crate::io; diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs index 3289efe05b068..80cd34e9a8576 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs @@ -71,10 +71,8 @@ pub unsafe fn init() { reserve_stack(); } -pub fn make_handler(main_thread: bool) -> super::Handler { - if !main_thread { - reserve_stack(); - } +pub fn make_handler() -> super::Handler { + reserve_stack(); super::Handler::null() } diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs index a0e2dfa941867..fd9d5fc7fa281 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs @@ -1,6 +1,6 @@ pub unsafe fn init() {} -pub fn make_handler(_main_thread: bool) -> super::Handler { +pub fn make_handler() -> super::Handler { super::Handler::null() } diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs index ba81ca1e15bf9..fa8c588254fc2 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs @@ -126,7 +126,7 @@ pub unsafe fn init() { if !NEED_ALTSTACK.load(Ordering::Relaxed) { // haven't set up our sigaltstack yet NEED_ALTSTACK.store(true, Ordering::Release); - let handler = make_handler(true); + let handler = install_sigaltstack(); MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); mem::forget(handler); @@ -147,6 +147,18 @@ pub unsafe fn init() { } } +pub fn make_handler() -> Handler { + if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Acquire) { + return Handler::null(); + } + + if let Some(guard_page_range) = current_guard() { + set_current_info(guard_page_range); + } + + install_sigaltstack() +} + fn get_stack() -> libc::stack_t { // OpenBSD requires this flag for stack mapping // otherwise the said mapping will fail as a no-op on most systems @@ -189,17 +201,7 @@ fn get_stack() -> libc::stack_t { libc::stack_t { ss_sp: stackp, ss_flags: 0, ss_size: sigstack_size } } -pub fn make_handler(main_thread: bool) -> Handler { - if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Acquire) { - return Handler::null(); - } - - if !main_thread { - if let Some(guard_page_range) = current_guard() { - set_current_info(guard_page_range); - } - } - +fn install_sigaltstack() -> Handler { // Load the current alternate signal stack to see if we need to install // our own. // @@ -235,6 +237,12 @@ pub fn make_handler(main_thread: bool) -> Handler { /// Must only be called with a pointer returned by `make_handler`, and only /// once per `Handler`. pub unsafe fn drop_handler(data: *mut libc::c_void) { + if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Relaxed) { + debug_assert!(data.is_null()); + // Skip the thread-info-store access below. + return; + } + if !data.is_null() { let sigstack_size = sigstack_size(); let page_size = PAGE_SIZE.load(Ordering::Relaxed); @@ -266,6 +274,9 @@ pub unsafe fn drop_handler(data: *mut libc::c_void) { unsafe { munmap(data.sub(page_size), sigstack_size + page_size) }; } + // `make_handler` inserts the current thread's info into the store even if + // there is already a signal stack in place, so this cannot be conditional + // on `data`. delete_current_info(); } diff --git a/library/std/src/sys/pal/unix/stack_overflow/mod.rs b/library/std/src/sys/pal/unix/stack_overflow/mod.rs index dfd9e006353d2..50d6b7df4be2c 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/mod.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/mod.rs @@ -60,7 +60,7 @@ impl Handler { return Handler::null(); } - imp::make_handler(false) + imp::make_handler() } fn null() -> Handler { diff --git a/library/std/src/sys/process/windows.rs b/library/std/src/sys/process/windows.rs index db2e2373adf95..1a520b76cdbd4 100644 --- a/library/std/src/sys/process/windows.rs +++ b/library/std/src/sys/process/windows.rs @@ -618,14 +618,14 @@ fn program_exists(path: &Path) -> Option> { impl Stdio { fn to_handle(&self, stdio_id: u32, pipe: &mut Option) -> io::Result { let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) { - Ok(io) => unsafe { + Some(io) => unsafe { let io = Handle::from_raw_handle(io); let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); let _ = io.into_raw_handle(); // Don't close the handle ret }, // If no stdio handle is available, then propagate the null value. - Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, + None => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, }; match *self { Stdio::Inherit => use_stdio_id(stdio_id), diff --git a/library/std/src/sys/stdio/windows.rs b/library/std/src/sys/stdio/windows.rs index f669527352246..c7c7a1ea3817f 100644 --- a/library/std/src/sys/stdio/windows.rs +++ b/library/std/src/sys/stdio/windows.rs @@ -70,15 +70,9 @@ pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3; #[cfg(not(target_vendor = "win7"))] const MAX_WRITE_HEAP_LEN: usize = 64 * 1024; // In u16 -> 128KiB -pub fn get_handle(handle_id: u32) -> io::Result { +pub fn get_handle(handle_id: u32) -> Option { let handle = unsafe { c::GetStdHandle(handle_id) }; - if handle == c::INVALID_HANDLE_VALUE { - Err(io::Error::last_os_error()) - } else if handle.is_null() { - Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32)) - } else { - Ok(handle) - } + if handle.is_null() || handle == c::INVALID_HANDLE_VALUE { None } else { Some(handle) } } /// Returns true if `handle` refers to a proper console (aka conhost). @@ -115,7 +109,8 @@ fn write(handle_id: u32, data: &[u8], incomplete_utf8: &mut IncompleteUtf8) -> i return Ok(0); } - let handle = get_handle(handle_id)?; + // If no handle is available, treat it like writing to NUL + let Some(handle) = get_handle(handle_id) else { return Ok(data.len()) }; // At the time of writing, console IO on Windows is high latency: // Windows has no TTY buffers, making every call a fully synchronous RPC. @@ -267,7 +262,8 @@ impl Stdin { impl io::Read for Stdin { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let handle = get_handle(c::STD_INPUT_HANDLE)?; + // If no handle is available then treat it as if reading from NUL + let Some(handle) = get_handle(c::STD_INPUT_HANDLE) else { return Ok(0) }; if !is_console(handle) { unsafe { let handle = Handle::from_raw_handle(handle); diff --git a/library/stdarch/crates/simd-test-macro/src/lib.rs b/library/stdarch/crates/simd-test-macro/src/lib.rs index 286b36d3dd249..7b903723664fe 100644 --- a/library/stdarch/crates/simd-test-macro/src/lib.rs +++ b/library/stdarch/crates/simd-test-macro/src/lib.rs @@ -142,7 +142,7 @@ pub fn simd_test( } any( target_arch = "mips", - target_arch = "mips32r6" + target_arch = "mips32r6", target_arch = "mips64", target_arch = "mips64r6", ) => { diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 5a1c0fb8753ba..59f50028c9d5e 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -2,5 +2,5 @@ # standard library we currently track. [toolchain] -channel = "nightly-2026-11-19" +channel = "nightly-2026-11-21" components = ["llvm-tools-preview", "rustc-dev", "rust-src", "rustfmt"] diff --git a/tool_config/kani-version.toml b/tool_config/kani-version.toml index c864abe9aa242..8045bbdc5f0f0 100644 --- a/tool_config/kani-version.toml +++ b/tool_config/kani-version.toml @@ -2,4 +2,4 @@ # incompatible with the verify-std repo. [kani] -commit = "9834c96ce90ff57d8495416530b080dc3d52ce25" +commit = "87c87010eda7797d7fa14033ca68bcbe17184a63"