Rollup merge of #144478 - joshtriplett:doc-code-formatting-prep, r=Amanieu

Improve formatting of doc code blocks

We don't currently apply automatic formatting to doc comment code blocks. As a
result, it has built up various idiosyncracies, which make such automatic
formatting difficult. Some of those idiosyncracies also make things harder for
human readers or other tools.

This PR makes a few improvements to doc code formatting, in the hopes of making
future automatic formatting easier, as well as in many cases providing net
readability improvements.

I would suggest reading each commit separately, as each commit contains one
class of changes.
This commit is contained in:
Samuel Tardieu 2025-08-02 11:24:24 +02:00 committed by GitHub
commit d082ff4c04
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 67 additions and 52 deletions

View file

@ -417,7 +417,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
/// minimum values.
///
/// For example:
/// ```
/// ```ignore (illustrative)
/// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
/// ```
/// would initialize two variables like so:

View file

@ -360,7 +360,7 @@ impl DefKind {
/// For example, everything prefixed with `/* Res */` in this example has
/// an associated `Res`:
///
/// ```
/// ```ignore (illustrative)
/// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
/// /* Res */ String::from(/* Res */ s)
/// }
@ -421,7 +421,7 @@ pub enum Res<Id = hir::HirId> {
/// }
///
/// impl Foo for Bar {
/// fn foo() -> Box<Self> { // SelfTyAlias
/// fn foo() -> Box<Self /* SelfTyAlias */> {
/// let _: Self; // SelfTyAlias
///
/// todo!()

View file

@ -425,7 +425,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'tcx> {
///
/// trait Foo {
/// fn bar() -> impl Deref<Target = impl Sized>;
/// // ^- RPITIT #1 ^- RPITIT #2
/// // ^- RPITIT #1 ^- RPITIT #2
/// }
///
/// impl Foo for () {

View file

@ -2391,13 +2391,11 @@ fn migration_suggestion_for_2229(
/// let mut p = Point { x: 10, y: 10 };
///
/// let c = || {
/// p.x += 10;
/// // ^ E1 ^
/// p.x += 10; // E1
/// // ...
/// // More code
/// // ...
/// p.x += 10; // E2
/// // ^ E2 ^
/// };
/// ```
/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),

View file

@ -36,7 +36,7 @@
//! fn bar<T>(a: T, b: impl for<'a> Fn(&'a T)) {}
//! fn foo<T>(x: T) {
//! bar(x, |y| { /* ... */})
//! // ^ closure arg
//! // ^ closure arg
//! }
//! ```
//!

View file

@ -533,8 +533,10 @@ impl<'tcx> TyCtxt<'tcx> {
/// ```
/// fn foo(x: usize) -> bool {
/// if x == 1 {
/// true // If `get_fn_id_for_return_block` gets passed the `id` corresponding
/// } else { // to this, it will return `foo`'s `HirId`.
/// // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it
/// // will return `foo`'s `HirId`.
/// true
/// } else {
/// false
/// }
/// }
@ -543,8 +545,10 @@ impl<'tcx> TyCtxt<'tcx> {
/// ```compile_fail,E0308
/// fn foo(x: usize) -> bool {
/// loop {
/// true // If `get_fn_id_for_return_block` gets passed the `id` corresponding
/// } // to this, it will return `None`.
/// // If `get_fn_id_for_return_block` gets passed the `id` corresponding to this, it
/// // will return `None`.
/// true
/// }
/// false
/// }
/// ```

View file

@ -1017,7 +1017,8 @@ pub struct LocalDecl<'tcx> {
/// ```
/// fn foo(x: &str) {
/// #[allow(unused_mut)]
/// let mut x: u32 = { // <- one unused mut
/// let mut x: u32 = {
/// //^ one unused mut
/// let mut y: u32 = x.parse().unwrap();
/// y + 2
/// };

View file

@ -57,7 +57,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
/// ```
/// #![feature(unsized_fn_params)]
/// # use core::fmt::Debug;
/// fn foo(_p: dyn Debug) { /* ... */ }
/// fn foo(_p: dyn Debug) {
/// /* ... */
/// }
///
/// fn bar(box_p: Box<dyn Debug>) { foo(*box_p); }
/// ```

View file

@ -108,6 +108,7 @@ impl<'tcx> MaybePlacesSwitchIntData<'tcx> {
///
/// ```rust
/// struct S;
/// #[rustfmt::skip]
/// fn foo(pred: bool) { // maybe-init:
/// // {}
/// let a = S; let mut b = S; let c; let d; // {a, b}
@ -197,6 +198,7 @@ impl<'a, 'tcx> HasMoveData<'tcx> for MaybeInitializedPlaces<'a, 'tcx> {
///
/// ```rust
/// struct S;
/// #[rustfmt::skip]
/// fn foo(pred: bool) { // maybe-uninit:
/// // {a, b, c, d}
/// let a = S; let mut b = S; let c; let d; // { c, d}
@ -289,6 +291,7 @@ impl<'tcx> HasMoveData<'tcx> for MaybeUninitializedPlaces<'_, 'tcx> {
///
/// ```rust
/// struct S;
/// #[rustfmt::skip]
/// fn foo(pred: bool) { // ever-init:
/// // { }
/// let a = S; let mut b = S; let c; let d; // {a, b }

View file

@ -768,7 +768,9 @@ impl SyntaxContext {
///
/// ```rust
/// #![feature(decl_macro)]
/// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
/// mod foo {
/// pub fn f() {} // `f`'s `SyntaxContext` is empty.
/// }
/// m!(f);
/// macro m($f:ident) {
/// mod bar {

View file

@ -501,9 +501,9 @@ impl<'scope> Scope<'scope> {
/// let mut value_c = None;
/// rayon::scope(|s| {
/// s.spawn(|s1| {
/// // ^ this is the same scope as `s`; this handle `s1`
/// // is intended for use by the spawned task,
/// // since scope handles cannot cross thread boundaries.
/// // ^ this is the same scope as `s`; this handle `s1`
/// // is intended for use by the spawned task,
/// // since scope handles cannot cross thread boundaries.
///
/// value_a = Some(22);
///

View file

@ -265,12 +265,12 @@ use crate::vec::{self, Vec};
/// You can look at these with the [`as_ptr`], [`len`], and [`capacity`]
/// methods:
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// use std::mem;
///
/// let story = String::from("Once upon a time...");
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent automatically dropping the String's data
/// let mut story = mem::ManuallyDrop::new(story);
///
@ -970,13 +970,13 @@ impl String {
///
/// # Examples
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// use std::mem;
///
/// unsafe {
/// let s = String::from("hello");
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent automatically dropping the String's data
/// let mut s = mem::ManuallyDrop::new(s);
///

View file

@ -566,13 +566,13 @@ impl<T> Vec<T> {
///
/// # Examples
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// use std::ptr;
/// use std::mem;
///
/// let v = vec![1, 2, 3];
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent running `v`'s destructor so we are in complete control
/// // of the allocation.
/// let mut v = mem::ManuallyDrop::new(v);
@ -674,6 +674,7 @@ impl<T> Vec<T> {
///
/// # Examples
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// #![feature(box_vec_non_null)]
///
@ -682,7 +683,6 @@ impl<T> Vec<T> {
///
/// let v = vec![1, 2, 3];
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent running `v`'s destructor so we are in complete control
/// // of the allocation.
/// let mut v = mem::ManuallyDrop::new(v);
@ -994,6 +994,7 @@ impl<T, A: Allocator> Vec<T, A> {
///
/// # Examples
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// #![feature(allocator_api)]
///
@ -1007,7 +1008,6 @@ impl<T, A: Allocator> Vec<T, A> {
/// v.push(2);
/// v.push(3);
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent running `v`'s destructor so we are in complete control
/// // of the allocation.
/// let mut v = mem::ManuallyDrop::new(v);
@ -1114,6 +1114,7 @@ impl<T, A: Allocator> Vec<T, A> {
///
/// # Examples
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// ```
/// #![feature(allocator_api, box_vec_non_null)]
///
@ -1127,7 +1128,6 @@ impl<T, A: Allocator> Vec<T, A> {
/// v.push(2);
/// v.push(3);
///
// FIXME Update this when vec_into_raw_parts is stabilized
/// // Prevent running `v`'s destructor so we are in complete control
/// // of the allocation.
/// let mut v = mem::ManuallyDrop::new(v);
@ -3872,8 +3872,8 @@ impl<T, A: Allocator> Vec<T, A> {
/// while i < vec.len() - end_items {
/// if some_predicate(&mut vec[i]) {
/// let val = vec.remove(i);
/// # extracted.push(val);
/// // your code here
/// # extracted.push(val);
/// } else {
/// i += 1;
/// }

View file

@ -2068,9 +2068,9 @@ impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
/// implies exclusive access to its `T`:
///
/// ```rust
/// #![forbid(unsafe_code)] // with exclusive accesses,
/// // `UnsafeCell` is a transparent no-op wrapper,
/// // so no need for `unsafe` here.
/// #![forbid(unsafe_code)]
/// // with exclusive accesses, `UnsafeCell` is a transparent no-op wrapper, so no need for
/// // `unsafe` here.
/// use std::cell::UnsafeCell;
///
/// let mut x: UnsafeCell<i32> = 42.into();

View file

@ -649,8 +649,6 @@ pub const fn must_use<T>(value: T) -> T {
/// }
/// }
/// ```
///
///
#[unstable(feature = "likely_unlikely", issue = "136873")]
#[inline(always)]
pub const fn likely(b: bool) -> bool {

View file

@ -233,10 +233,12 @@
//!
//! ```
//! let mut values = vec![41];
//! for x in &mut values { // same as `values.iter_mut()`
//! for x in &mut values {
//! // ^ same as `values.iter_mut()`
//! *x += 1;
//! }
//! for x in &values { // same as `values.iter()`
//! for x in &values {
//! // ^ same as `values.iter()`
//! assert_eq!(*x, 42);
//! }
//! assert_eq!(values.len(), 1);

View file

@ -807,7 +807,7 @@ pub trait Iterator {
/// might be preferable to keep a functional style with longer iterators:
///
/// ```
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// (0..5).flat_map(|x| (x * 100)..(x * 110))
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{i}:{x}"));

View file

@ -271,7 +271,10 @@ pub macro cfg_select($($tt:tt)*) {
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// fn some_expensive_computation() -> bool {
/// // Some expensive computation here
/// true
/// }
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
@ -1547,7 +1550,10 @@ pub(crate) mod builtin {
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
/// fn some_computation() -> bool {
/// // Some expensive computation here
/// true
/// }
///
/// assert!(some_computation());
///

View file

@ -138,8 +138,7 @@ unsafe impl<T: Sync + PointeeSized> Send for &T {}
/// impl Bar for Impl { }
///
/// let x: &dyn Foo = &Impl; // OK
/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot
/// // be made into an object
/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot be made into an object
/// ```
///
/// [trait object]: ../../book/ch17-02-trait-objects.html

View file

@ -773,8 +773,7 @@ impl<T> MaybeUninit<T> {
/// // Initialize the `MaybeUninit` using `Cell::set`:
/// unsafe {
/// b.assume_init_ref().set(true);
/// // ^^^^^^^^^^^^^^^
/// // Reference to an uninitialized `Cell<bool>`: UB!
/// //^^^^^^^^^^^^^^^ Reference to an uninitialized `Cell<bool>`: UB!
/// }
/// ```
#[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
@ -864,9 +863,9 @@ impl<T> MaybeUninit<T> {
/// {
/// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
/// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
/// // ^^^^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// // ^^^^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// Ok(unsafe { buffer.assume_init() })
/// }
/// ```
@ -884,13 +883,13 @@ impl<T> MaybeUninit<T> {
/// let foo: Foo = unsafe {
/// let mut foo = MaybeUninit::<Foo>::uninit();
/// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
/// // ^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// // ^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
/// // ^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// // ^^^^^^^^^^^^^^^^^^^^^
/// // (mutable) reference to uninitialized memory!
/// // This is undefined behavior.
/// foo.assume_init()
/// };
/// ```

View file

@ -271,6 +271,7 @@ mod prim_bool {}
/// When the compiler sees a value of type `!` in a [coercion site], it implicitly inserts a
/// coercion to allow the type checker to infer any type:
///
// FIXME: use `core::convert::absurd` here instead, once it's merged
/// ```rust,ignore (illustrative-and-has-placeholders)
/// // this
/// let x: u8 = panic!();
@ -281,7 +282,6 @@ mod prim_bool {}
/// // where absurd is a function with the following signature
/// // (it's sound, because `!` always marks unreachable code):
/// fn absurd<T>(_: !) -> T { ... }
// FIXME: use `core::convert::absurd` here instead, once it's merged
/// ```
///
/// This can lead to compilation errors if the type cannot be inferred:

View file

@ -1631,7 +1631,7 @@ impl<T, E> Result<T, E> {
///
/// ```no_run
/// let x: Result<u32, &str> = Err("emergency failure");
/// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
/// unsafe { x.unwrap_unchecked() }; // Undefined behavior!
/// ```
#[inline]
#[track_caller]

View file

@ -3259,8 +3259,8 @@ impl Path {
///
/// # Examples
///
#[cfg_attr(unix, doc = "```no_run")]
#[cfg_attr(not(unix), doc = "```ignore")]
/// ```rust,no_run
/// # #[cfg(unix)] {
/// use std::path::Path;
/// use std::os::unix::fs::symlink;
///
@ -3268,6 +3268,7 @@ impl Path {
/// symlink("/origin_does_not_exist/", link_path).unwrap();
/// assert_eq!(link_path.is_symlink(), true);
/// assert_eq!(link_path.exists(), false);
/// # }
/// ```
///
/// # See Also