]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #98180 - notriddle:notriddle/rustdoc-fn, r=petrochenkov,GuillaumeGomez
authorbors <bors@rust-lang.org>
Tue, 19 Jul 2022 19:36:57 +0000 (19:36 +0000)
committerbors <bors@rust-lang.org>
Tue, 19 Jul 2022 19:36:57 +0000 (19:36 +0000)
Improve the function pointer docs

This is #97842 but for function pointers instead of tuples. The concept is basically the same.

* Reduce duplicate impls; show `fn (T₁, T₂, …, Tₙ)` and include a sentence saying that there exists up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.

https://notriddle.com/notriddle-rustdoc-test/std/primitive.fn.html

29 files changed:
compiler/rustc_ast_passes/src/feature_gate.rs
compiler/rustc_error_codes/src/error_codes/E0118.md
compiler/rustc_error_messages/locales/en-US/passes.ftl
compiler/rustc_passes/src/check_attr.rs
compiler/rustc_passes/src/errors.rs
compiler/rustc_span/src/symbol.rs
compiler/rustc_typeck/src/coherence/inherent_impls.rs
library/core/src/fmt/mod.rs
library/core/src/hash/mod.rs
library/core/src/primitive_docs.rs
library/core/src/ptr/mod.rs
library/core/src/tuple.rs
library/std/src/primitive_docs.rs
src/librustdoc/clean/inline.rs
src/librustdoc/clean/mod.rs
src/librustdoc/clean/types.rs
src/librustdoc/html/format.rs
src/librustdoc/json/conversions.rs
src/test/rustdoc-ui/tuple-variadic-check.rs
src/test/rustdoc-ui/tuple-variadic-check.stderr
src/test/rustdoc/primitive-tuple-auto-trait.rs
src/test/rustdoc/primitive-tuple-variadic.rs
src/test/ui/error-codes/E0118.rs
src/test/ui/error-codes/E0118.stderr
src/test/ui/error-codes/E0390.rs
src/test/ui/error-codes/E0390.stderr
src/test/ui/feature-gates/feature-gate-rustdoc_internals.rs
src/test/ui/feature-gates/feature-gate-rustdoc_internals.stderr
src/test/ui/issues/issue-59488.stderr

index 22cb27af4fbc51afed2d1782a7fce9f7cfb70687..ad9ed798e558bde002fc058adade9b854c903bf5 100644 (file)
@@ -404,8 +404,8 @@ macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
                     gate_feature_post!(self, rustdoc_internals, attr.span, msg);
                 }
 
-                if nested_meta.has_name(sym::tuple_variadic) {
-                    let msg = "`#[doc(tuple_variadic)]` is meant for internal use only";
+                if nested_meta.has_name(sym::fake_variadic) {
+                    let msg = "`#[doc(fake_variadic)]` is meant for internal use only";
                     gate_feature_post!(self, rustdoc_internals, attr.span, msg);
                 }
             }
index 8033aa8384c2e1276f742b8dd37070774da23ef8..cfabae1a6346d6a2d0217d4622efb5706d06ed2f 100644 (file)
@@ -4,7 +4,7 @@ enum, union, or trait object.
 Erroneous code example:
 
 ```compile_fail,E0118
-impl fn(u8) { // error: no nominal type found for inherent implementation
+impl<T> T { // error: no nominal type found for inherent implementation
     fn get_state(&self) -> String {
         // ...
     }
@@ -20,8 +20,8 @@ trait LiveLongAndProsper {
     fn get_state(&self) -> String;
 }
 
-// and now you can implement it on fn(u8)
-impl LiveLongAndProsper for fn(u8) {
+// and now you can implement it on T
+impl<T> LiveLongAndProsper for T {
     fn get_state(&self) -> String {
         "He's dead, Jim!".to_owned()
     }
@@ -33,9 +33,9 @@ For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
 Example:
 
 ```
-struct TypeWrapper(fn(u8));
+struct TypeWrapper<T>(T);
 
-impl TypeWrapper {
+impl<T> TypeWrapper<T> {
     fn get_state(&self) -> String {
         "Fascinating!".to_owned()
     }
index e4c9a4dad7b4815cf164781bcab0d7cc870d30b0..04c67cf8ff73ae3542c4ee5676c0876d9f5a555c 100644 (file)
@@ -81,8 +81,8 @@ passes-doc-keyword-not-mod = `#[doc(keyword = "...")]` should be used on modules
 
 passes-doc-keyword-invalid-ident = `{$doc_keyword}` is not a valid identifier
 
-passes-doc-tuple-variadic-not-first =
-    `#[doc(tuple_variadic)]` must be used on the first of a set of tuple trait impls with varying arity
+passes-doc-fake-variadic-not-valid =
+    `#[doc(fake_variadic)]` must be used on the first of a set of tuple or fn pointer trait impls with varying arity
 
 passes-doc-keyword-only-impl = `#[doc(keyword = "...")]` should be used on impl blocks
 
index d96e7d3efe83db095dc1e2180e8b60683d7cf5b9..f88997f884a4478bf5f5618fc14ab356e7631c9e 100644 (file)
@@ -706,14 +706,20 @@ fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
         true
     }
 
-    fn check_doc_tuple_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
+    fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
         match self.tcx.hir().find(hir_id).and_then(|node| match node {
             hir::Node::Item(item) => Some(&item.kind),
             _ => None,
         }) {
             Some(ItemKind::Impl(ref i)) => {
-                if !matches!(&i.self_ty.kind, hir::TyKind::Tup([_])) {
-                    self.tcx.sess.emit_err(errors::DocTupleVariadicNotFirst { span: meta.span() });
+                let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
+                    || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
+                        bare_fn_ty.decl.inputs.len() == 1
+                    } else {
+                        false
+                    };
+                if !is_valid {
+                    self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
                     return false;
                 }
             }
@@ -887,9 +893,9 @@ fn check_doc_attrs(
                             is_valid = false
                         }
 
-                        sym::tuple_variadic
-                            if !self.check_attr_not_crate_level(meta, hir_id, "tuple_variadic")
-                                || !self.check_doc_tuple_variadic(meta, hir_id) =>
+                        sym::fake_variadic
+                            if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
+                                || !self.check_doc_fake_variadic(meta, hir_id) =>
                         {
                             is_valid = false
                         }
@@ -939,7 +945,7 @@ fn check_doc_attrs(
                         | sym::notable_trait
                         | sym::passes
                         | sym::plugins
-                        | sym::tuple_variadic => {}
+                        | sym::fake_variadic => {}
 
                         sym::test => {
                             if !self.check_test_attr(meta, hir_id) {
index f8e8720ab5474231a487f2c7fd2d251e611fc62b..fcd1e9363b1bed01018495447afebf0d5e9fe647 100644 (file)
@@ -212,8 +212,8 @@ pub struct DocKeywordInvalidIdent {
 }
 
 #[derive(SessionDiagnostic)]
-#[error(passes::doc_tuple_variadic_not_first)]
-pub struct DocTupleVariadicNotFirst {
+#[error(passes::doc_fake_variadic_not_valid)]
+pub struct DocFakeVariadicNotValid {
     #[primary_span]
     pub span: Span,
 }
index 3ccd3fcbafa2bafb5c4db93540e3689f6176dc58..ec1d2c39b8092dbfa5aae6a5d39e9b7b694ace95 100644 (file)
         fabsf32,
         fabsf64,
         fadd_fast,
+        fake_variadic,
         fdiv_fast,
         feature,
         fence,
         tuple,
         tuple_from_req,
         tuple_indexing,
-        tuple_variadic,
         two_phase,
         ty,
         type_alias_enum_variants,
index 7a9b874b5e45643ae4e7992929cde3eea76e4b61..52aad636fd88ac887da8d5b229c7f94ae72c6d01 100644 (file)
@@ -219,8 +219,9 @@ fn check_item(&mut self, id: hir::ItemId) {
             | ty::RawPtr(_)
             | ty::Ref(..)
             | ty::Never
+            | ty::FnPtr(_)
             | ty::Tuple(..) => self.check_primitive_impl(item.def_id, self_ty, items, ty.span),
-            ty::FnPtr(_) | ty::Projection(..) | ty::Opaque(..) | ty::Param(_) => {
+            ty::Projection(..) | ty::Opaque(..) | ty::Param(_) => {
                 let mut err = struct_span_err!(
                     self.tcx.sess,
                     ty.span,
index 6c3bb7229e51f1008b84f3bbcf536dc33cbce506..372141e0933f560600fdcbe7ac79ec8400170513 100644 (file)
@@ -2562,7 +2562,7 @@ fn fmt(&self, f: &mut Formatter<'_>) -> Result {
 
 macro_rules! maybe_tuple_doc {
     ($a:ident @ #[$meta:meta] $item:item) => {
-        #[doc(tuple_variadic)]
+        #[cfg_attr(not(bootstrap), doc(fake_variadic))]
         #[doc = "This trait is implemented for tuples up to twelve items long."]
         #[$meta]
         $item
index cf428e0b1cf1d729e5d8b4a1f3d10b3ce23a465a..5974562aced4ebee6c2742545792598c60d2f0cb 100644 (file)
@@ -900,7 +900,7 @@ fn hash<S: Hasher>(&self, state: &mut S) {
 
     macro_rules! maybe_tuple_doc {
         ($a:ident @ #[$meta:meta] $item:item) => {
-            #[doc(tuple_variadic)]
+            #[cfg_attr(not(bootstrap), doc(fake_variadic))]
             #[doc = "This trait is implemented for tuples up to twelve items long."]
             #[$meta]
             $item
index 401c8159988bb7697c798106ea44f434ff5bb6d4..b8e5461640c0581ea4a242fb7724aea2140c01da 100644 (file)
@@ -996,7 +996,7 @@ impl<T> (T,) {}
 // Fake impl that's only really used for docs.
 #[cfg(doc)]
 #[stable(feature = "rust1", since = "1.0.0")]
-#[doc(tuple_variadic)]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
 /// This trait is implemented on arbitrary-length tuples.
 impl<T: Clone> Clone for (T,) {
     fn clone(&self) -> Self {
@@ -1007,7 +1007,7 @@ fn clone(&self) -> Self {
 // Fake impl that's only really used for docs.
 #[cfg(doc)]
 #[stable(feature = "rust1", since = "1.0.0")]
-#[doc(tuple_variadic)]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
 /// This trait is implemented on arbitrary-length tuples.
 impl<T: Copy> Copy for (T,) {
     // empty
@@ -1441,11 +1441,16 @@ mod prim_ref {}
 /// Note that all of this is not portable to platforms where function pointers and data pointers
 /// have different sizes.
 ///
-/// ### Traits
+/// ### Trait implementations
 ///
-/// Function pointers implement the following traits:
+/// In this documentation the shorthand `fn (T₁, T₂, …, Tₙ)` is used to represent non-variadic
+/// function pointers of varying length. Note that this is a convenience notation to avoid
+/// repetitive documentation, not valid Rust syntax.
+///
+/// Due to a temporary restriction in Rust's type system, these traits are only implemented on
+/// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
+/// may change:
 ///
-/// * [`Clone`]
 /// * [`PartialEq`]
 /// * [`Eq`]
 /// * [`PartialOrd`]
@@ -1454,15 +1459,50 @@ mod prim_ref {}
 /// * [`Pointer`]
 /// * [`Debug`]
 ///
+/// The following traits are implemented for function pointers with any number of arguments and
+/// any ABI. These traits have implementations that are automatically generated by the compiler,
+/// so are not limited by missing language features:
+///
+/// * [`Clone`]
+/// * [`Copy`]
+/// * [`Send`]
+/// * [`Sync`]
+/// * [`Unpin`]
+/// * [`UnwindSafe`]
+/// * [`RefUnwindSafe`]
+///
 /// [`Hash`]: hash::Hash
 /// [`Pointer`]: fmt::Pointer
+/// [`UnwindSafe`]: panic::UnwindSafe
+/// [`RefUnwindSafe`]: panic::RefUnwindSafe
 ///
-/// Due to a temporary restriction in Rust's type system, these traits are only implemented on
-/// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
-/// may change.
-///
-/// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
-/// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
-/// are specially known to the compiler.
+/// In addition, all *safe* function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`], because
+/// these traits are specially known to the compiler.
 #[stable(feature = "rust1", since = "1.0.0")]
 mod prim_fn {}
+
+// Required to make auto trait impls render.
+// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
+#[doc(hidden)]
+#[cfg(not(bootstrap))]
+impl<Ret, T> fn(T) -> Ret {}
+
+// Fake impl that's only really used for docs.
+#[cfg(doc)]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
+/// This trait is implemented on function pointers with any number of arguments.
+impl<Ret, T> Clone for fn(T) -> Ret {
+    fn clone(&self) -> Self {
+        loop {}
+    }
+}
+
+// Fake impl that's only really used for docs.
+#[cfg(doc)]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
+/// This trait is implemented on function pointers with any number of arguments.
+impl<Ret, T> Copy for fn(T) -> Ret {
+    // empty
+}
index 509854225c4f3e5be294702a5ebe6dcf75821478..62548b5fadd2eab0813622d1e03799765890e349 100644 (file)
@@ -1819,6 +1819,27 @@ pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
     hashee.hash(into);
 }
 
+// If this is a unary fn pointer, it adds a doc comment.
+// Otherwise, it hides the docs entirely.
+macro_rules! maybe_fnptr_doc {
+    (@ #[$meta:meta] $item:item) => {
+        #[doc(hidden)]
+        #[$meta]
+        $item
+    };
+    ($a:ident @ #[$meta:meta] $item:item) => {
+        #[cfg_attr(not(bootstrap), doc(fake_variadic))]
+        #[doc = "This trait is implemented for function pointers with up to twelve arguments."]
+        #[$meta]
+        $item
+    };
+    ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
+        #[doc(hidden)]
+        #[$meta]
+        $item
+    };
+}
+
 // FIXME(strict_provenance_magic): function pointers have buggy codegen that
 // necessitates casting to a usize to get the backend to do the right thing.
 // for now I will break AVR to silence *a billion* lints. We should probably
@@ -1827,51 +1848,72 @@ pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
 // Impls for function pointers
 macro_rules! fnptr_impls_safety_abi {
     ($FnTy: ty, $($Arg: ident),*) => {
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> PartialEq for $FnTy {
-            #[inline]
-            fn eq(&self, other: &Self) -> bool {
-                *self as usize == *other as usize
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> PartialEq for $FnTy {
+                #[inline]
+                fn eq(&self, other: &Self) -> bool {
+                    *self as usize == *other as usize
+                }
             }
         }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> Eq for $FnTy {}
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> Eq for $FnTy {}
+        }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> PartialOrd for $FnTy {
-            #[inline]
-            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
-                (*self as usize).partial_cmp(&(*other as usize))
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> PartialOrd for $FnTy {
+                #[inline]
+                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+                    (*self as usize).partial_cmp(&(*other as usize))
+                }
             }
         }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> Ord for $FnTy {
-            #[inline]
-            fn cmp(&self, other: &Self) -> Ordering {
-                (*self as usize).cmp(&(*other as usize))
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> Ord for $FnTy {
+                #[inline]
+                fn cmp(&self, other: &Self) -> Ordering {
+                    (*self as usize).cmp(&(*other as usize))
+                }
             }
         }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> hash::Hash for $FnTy {
-            fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
-                state.write_usize(*self as usize)
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> hash::Hash for $FnTy {
+                fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
+                    state.write_usize(*self as usize)
+                }
             }
         }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
-            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                fmt::pointer_fmt_inner(*self as usize, f)
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
+                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                    fmt::pointer_fmt_inner(*self as usize, f)
+                }
             }
         }
 
-        #[stable(feature = "fnptr_impls", since = "1.4.0")]
-        impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
-            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                fmt::pointer_fmt_inner(*self as usize, f)
+        maybe_fnptr_doc! {
+            $($Arg)* @
+            #[stable(feature = "fnptr_impls", since = "1.4.0")]
+            impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
+                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                    fmt::pointer_fmt_inner(*self as usize, f)
+                }
             }
         }
     }
@@ -1896,7 +1938,7 @@ macro_rules! fnptr_impls_args {
 }
 
 fnptr_impls_args! {}
-fnptr_impls_args! { A }
+fnptr_impls_args! { T }
 fnptr_impls_args! { A, B }
 fnptr_impls_args! { A, B, C }
 fnptr_impls_args! { A, B, C, D }
index b664b0bb866dbf0f4b1faa19681b8c470097aa56..d189e6400f1e87951c5ca8eb9166f192af9be3b1 100644 (file)
@@ -107,7 +107,7 @@ fn default() -> ($($T,)+) {
 // Otherwise, it hides the docs entirely.
 macro_rules! maybe_tuple_doc {
     ($a:ident @ #[$meta:meta] $item:item) => {
-        #[doc(tuple_variadic)]
+        #[cfg_attr(not(bootstrap), doc(fake_variadic))]
         #[doc = "This trait is implemented for tuples up to twelve items long."]
         #[$meta]
         $item
index 401c8159988bb7697c798106ea44f434ff5bb6d4..b8e5461640c0581ea4a242fb7724aea2140c01da 100644 (file)
@@ -996,7 +996,7 @@ impl<T> (T,) {}
 // Fake impl that's only really used for docs.
 #[cfg(doc)]
 #[stable(feature = "rust1", since = "1.0.0")]
-#[doc(tuple_variadic)]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
 /// This trait is implemented on arbitrary-length tuples.
 impl<T: Clone> Clone for (T,) {
     fn clone(&self) -> Self {
@@ -1007,7 +1007,7 @@ fn clone(&self) -> Self {
 // Fake impl that's only really used for docs.
 #[cfg(doc)]
 #[stable(feature = "rust1", since = "1.0.0")]
-#[doc(tuple_variadic)]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
 /// This trait is implemented on arbitrary-length tuples.
 impl<T: Copy> Copy for (T,) {
     // empty
@@ -1441,11 +1441,16 @@ mod prim_ref {}
 /// Note that all of this is not portable to platforms where function pointers and data pointers
 /// have different sizes.
 ///
-/// ### Traits
+/// ### Trait implementations
 ///
-/// Function pointers implement the following traits:
+/// In this documentation the shorthand `fn (T₁, T₂, …, Tₙ)` is used to represent non-variadic
+/// function pointers of varying length. Note that this is a convenience notation to avoid
+/// repetitive documentation, not valid Rust syntax.
+///
+/// Due to a temporary restriction in Rust's type system, these traits are only implemented on
+/// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
+/// may change:
 ///
-/// * [`Clone`]
 /// * [`PartialEq`]
 /// * [`Eq`]
 /// * [`PartialOrd`]
@@ -1454,15 +1459,50 @@ mod prim_ref {}
 /// * [`Pointer`]
 /// * [`Debug`]
 ///
+/// The following traits are implemented for function pointers with any number of arguments and
+/// any ABI. These traits have implementations that are automatically generated by the compiler,
+/// so are not limited by missing language features:
+///
+/// * [`Clone`]
+/// * [`Copy`]
+/// * [`Send`]
+/// * [`Sync`]
+/// * [`Unpin`]
+/// * [`UnwindSafe`]
+/// * [`RefUnwindSafe`]
+///
 /// [`Hash`]: hash::Hash
 /// [`Pointer`]: fmt::Pointer
+/// [`UnwindSafe`]: panic::UnwindSafe
+/// [`RefUnwindSafe`]: panic::RefUnwindSafe
 ///
-/// Due to a temporary restriction in Rust's type system, these traits are only implemented on
-/// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
-/// may change.
-///
-/// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
-/// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
-/// are specially known to the compiler.
+/// In addition, all *safe* function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`], because
+/// these traits are specially known to the compiler.
 #[stable(feature = "rust1", since = "1.0.0")]
 mod prim_fn {}
+
+// Required to make auto trait impls render.
+// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
+#[doc(hidden)]
+#[cfg(not(bootstrap))]
+impl<Ret, T> fn(T) -> Ret {}
+
+// Fake impl that's only really used for docs.
+#[cfg(doc)]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
+/// This trait is implemented on function pointers with any number of arguments.
+impl<Ret, T> Clone for fn(T) -> Ret {
+    fn clone(&self) -> Self {
+        loop {}
+    }
+}
+
+// Fake impl that's only really used for docs.
+#[cfg(doc)]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[cfg_attr(not(bootstrap), doc(fake_variadic))]
+/// This trait is implemented on function pointers with any number of arguments.
+impl<Ret, T> Copy for fn(T) -> Ret {
+    // empty
+}
index 23af7d2ef1e2494173da3bc657f0469784c12d5e..ce10ca9aa3df434e90a76ff035f440787bd41578 100644 (file)
@@ -506,8 +506,8 @@ pub(crate) fn build_impl(
             for_,
             items: trait_items,
             polarity,
-            kind: if utils::has_doc_flag(tcx, did, sym::tuple_variadic) {
-                ImplKind::TupleVaradic
+            kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
+                ImplKind::FakeVaradic
             } else {
                 ImplKind::Normal
             },
index 671b40dbfe66df3e34f30ecd597e5464ec6b3fa8..9865601da5fc7f5b9aca672a0accebe0549507d2 100644 (file)
@@ -2037,8 +2037,8 @@ fn clean_impl<'tcx>(
             for_,
             items,
             polarity: tcx.impl_polarity(def_id),
-            kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::tuple_variadic) {
-                ImplKind::TupleVaradic
+            kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
+                ImplKind::FakeVaradic
             } else {
                 ImplKind::Normal
             },
index d29ba2dedaf717260094c80e9b54c62e5df03d13..8c08f77667904769c4a855f9f7ae5cd06bccda90 100644 (file)
@@ -1841,7 +1841,7 @@ pub(crate) fn simplified_types() -> &'static SimplifiedTypes {
                 Reference => [RefSimplifiedType(Mutability::Not), RefSimplifiedType(Mutability::Mut)].into_iter().collect(),
                 // FIXME: This will be wrong if we ever add inherent impls
                 // for function pointers.
-                Fn => ArrayVec::new(),
+                Fn => single(FunctionSimplifiedType(1)),
                 Never => single(NeverSimplifiedType),
             }
         })
@@ -2394,7 +2394,7 @@ pub(crate) fn provided_trait_methods(&self, tcx: TyCtxt<'_>) -> FxHashSet<Symbol
 pub(crate) enum ImplKind {
     Normal,
     Auto,
-    TupleVaradic,
+    FakeVaradic,
     Blanket(Box<Type>),
 }
 
@@ -2407,8 +2407,8 @@ pub(crate) fn is_blanket(&self) -> bool {
         matches!(self, ImplKind::Blanket(_))
     }
 
-    pub(crate) fn is_tuple_variadic(&self) -> bool {
-        matches!(self, ImplKind::TupleVaradic)
+    pub(crate) fn is_fake_variadic(&self) -> bool {
+        matches!(self, ImplKind::FakeVaradic)
     }
 
     pub(crate) fn as_blanket_ty(&self) -> Option<&Type> {
index 9f46ab54d3ece10c27fad80c6e3e8df2763e3017..36a47b05cb9d674b0dadd2a817fac9e35bdf7c3b 100644 (file)
@@ -1165,10 +1165,43 @@ pub(crate) fn print<'a, 'tcx: 'a>(
 
             if let clean::Type::Tuple(types) = &self.for_ &&
                 let [clean::Type::Generic(name)] = &types[..] &&
-                (self.kind.is_tuple_variadic() || self.kind.is_auto()) {
+                (self.kind.is_fake_variadic() || self.kind.is_auto())
+            {
                 // Hardcoded anchor library/core/src/primitive_docs.rs
                 // Link should match `# Trait implementations`
                 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
+            } else if let clean::BareFunction(bare_fn) = &self.for_ &&
+                let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
+                (self.kind.is_fake_variadic() || self.kind.is_auto())
+            {
+                // Hardcoded anchor library/core/src/primitive_docs.rs
+                // Link should match `# Trait implementations`
+
+                let hrtb = bare_fn.print_hrtb_with_space(cx);
+                let unsafety = bare_fn.unsafety.print_with_space();
+                let abi = print_abi_with_space(bare_fn.abi);
+                if f.alternate() {
+                    write!(
+                        f,
+                        "{hrtb:#}{unsafety}{abi:#}",
+                    )?;
+                } else {
+                    write!(
+                        f,
+                        "{hrtb}{unsafety}{abi}",
+                    )?;
+                }
+                let ellipsis = if bare_fn.decl.c_variadic {
+                    ", ..."
+                } else {
+                    ""
+                };
+                primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
+                // Write output.
+                if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
+                    write!(f, " -> ")?;
+                    fmt_type(ty, f, use_absolute, cx)?;
+                }
             } else if let Some(ty) = self.kind.as_blanket_ty() {
                 fmt_type(ty, f, use_absolute, cx)?;
             } else {
index 2598b9b0b28c20e982287ac7ee0eca48d972d056..9000ab472d96e43983f70ae1743e8ac895b69317 100644 (file)
@@ -574,7 +574,7 @@ fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
         let trait_ = trait_.map(|path| clean::Type::Path { path }.into_tcx(tcx));
         // FIXME: use something like ImplKind in JSON?
         let (synthetic, blanket_impl) = match kind {
-            clean::ImplKind::Normal | clean::ImplKind::TupleVaradic => (false, None),
+            clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
             clean::ImplKind::Auto => (true, None),
             clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
         };
index 11ce2dbe280500f201178295801dda910d0f1668..505de53481f85c9c11453cf650cfd41b24428876 100644 (file)
@@ -3,13 +3,13 @@
 trait Mine {}
 
 // This one is fine
-#[doc(tuple_variadic)]
+#[doc(fake_variadic)]
 impl<T> Mine for (T,) {}
 
 trait Mine2 {}
 
 // This one is not
-#[doc(tuple_variadic)] //~ ERROR
+#[doc(fake_variadic)] //~ ERROR
 impl<T, U> Mine for (T,U) {}
 
 fn main() {}
index 358d06d6a42dd4a5028eea021d2c83a5e3b9b4f5..d127fb858d176d303adfd5677956c9278f58e625 100644 (file)
@@ -1,8 +1,8 @@
-error: `#[doc(tuple_variadic)]` must be used on the first of a set of tuple trait impls with varying arity
+error: `#[doc(fake_variadic)]` must be used on the first of a set of tuple or fn pointer trait impls with varying arity
   --> $DIR/tuple-variadic-check.rs:12:7
    |
-LL | #[doc(tuple_variadic)]
-   |       ^^^^^^^^^^^^^^
+LL | #[doc(fake_variadic)]
+   |       ^^^^^^^^^^^^^
 
 error: aborting due to previous error
 
index 71b0b07700958967dcec531d4233833c133260bb..a2fbbf078d5178468408174845ce1dfe99d1ea88 100644 (file)
@@ -16,7 +16,7 @@
 // @has - '//h2[@id="trait-implementations-1"]' 'Trait implementations'
 /// # Trait implementations
 ///
-/// This header is hard-coded in the HTML format linking for `#[doc(tuple_variadics)]`.
+/// This header is hard-coded in the HTML format linking for `#[doc(fake_variadics)]`.
 /// To make sure it gets linked correctly, we need to make sure the hardcoded anchor
 /// in the code matches what rustdoc generates for the header.
 mod tuple_prim {}
index 4fd6254f6740d0a2e8545445fb732b228023c2ee..db7cfd60c71a67e3dc8ab4d993d902fe21277700 100644 (file)
@@ -7,12 +7,12 @@ pub trait Foo {}
 
 // @has foo/trait.Foo.html
 // @has - '//section[@id="impl-Foo-for-(T%2C)"]/h3' 'impl<T> Foo for (T₁, T₂, …, Tₙ)'
-#[doc(tuple_variadic)]
+#[doc(fake_variadic)]
 impl<T> Foo for (T,) {}
 
 pub trait Bar {}
 
 // @has foo/trait.Bar.html
 // @has - '//section[@id="impl-Bar-for-(U%2C)"]/h3' 'impl<U: Foo> Bar for (U₁, U₂, …, Uₙ)'
-#[doc(tuple_variadic)]
+#[doc(fake_variadic)]
 impl<U: Foo> Bar for (U,) {}
index aaef8113b8ae243bd7ea3a78be5aafe005faf4fa..a61ba7bbf328cee6aaaa5efde5e4e9125ec9f048 100644 (file)
@@ -1,4 +1,4 @@
-impl fn(u8) { //~ ERROR E0118
+impl<T> T { //~ ERROR E0118
     fn get_state(&self) -> String {
        String::new()
     }
index 296fb5d664a227308b5341cc8df579997e971328..8c6fa7947a8537746be07f1c35f7d2eaf8881367 100644 (file)
@@ -1,8 +1,8 @@
 error[E0118]: no nominal type found for inherent implementation
-  --> $DIR/E0118.rs:1:6
+  --> $DIR/E0118.rs:1:9
    |
-LL | impl fn(u8) {
-   |      ^^^^^^ impl requires a nominal type
+LL | impl<T> T {
+   |         ^ impl requires a nominal type
    |
    = note: either implement a trait on it or create a newtype to wrap it instead
 
index 4eb59a053b45b50f289b871ab8da398d54135f0b..507483dec2ee263c1b99c3ecda0946131774b5b4 100644 (file)
@@ -4,5 +4,7 @@ struct Foo {
 
 impl *mut Foo {} //~ ERROR E0390
 
+impl fn(Foo) {} //~ ERROR E0390
+
 fn main() {
 }
index e635d4ec196a271351a9dd1d8b52c68f2dc4077d..0e5a9ca762b768ff2bde803695dfcac6697a9108 100644 (file)
@@ -6,6 +6,14 @@ LL | impl *mut Foo {}
    |
    = help: consider using an extension trait instead
 
-error: aborting due to previous error
+error[E0390]: cannot define inherent `impl` for primitive types
+  --> $DIR/E0390.rs:7:6
+   |
+LL | impl fn(Foo) {}
+   |      ^^^^^^^
+   |
+   = help: consider using an extension trait instead
+
+error: aborting due to 2 previous errors
 
 For more information about this error, try `rustc --explain E0390`.
index 6a144412d0751541c914963d464d2bd25a6330dd..58306a4cfc9c9d03e342167e0d044c3cef27029f 100644 (file)
@@ -4,7 +4,7 @@ mod foo {}
 
 trait Mine {}
 
-#[doc(tuple_variadic)]  //~ ERROR: `#[doc(tuple_variadic)]` is meant for internal use only
+#[doc(fake_variadic)]  //~ ERROR: `#[doc(fake_variadic)]` is meant for internal use only
 impl<T> Mine for (T,) {}
 
 fn main() {}
index 9fe08afd4f05e116501cecad567b092e2fd109c6..c4272a2c04c2ae5d46e7cea98de233bda0cab7e0 100644 (file)
@@ -7,11 +7,11 @@ LL | #[doc(keyword = "match")]
    = note: see issue #90418 <https://github.com/rust-lang/rust/issues/90418> for more information
    = help: add `#![feature(rustdoc_internals)]` to the crate attributes to enable
 
-error[E0658]: `#[doc(tuple_variadic)]` is meant for internal use only
+error[E0658]: `#[doc(fake_variadic)]` is meant for internal use only
   --> $DIR/feature-gate-rustdoc_internals.rs:7:1
    |
-LL | #[doc(tuple_variadic)]
-   | ^^^^^^^^^^^^^^^^^^^^^^
+LL | #[doc(fake_variadic)]
+   | ^^^^^^^^^^^^^^^^^^^^^
    |
    = note: see issue #90418 <https://github.com/rust-lang/rust/issues/90418> for more information
    = help: add `#![feature(rustdoc_internals)]` to the crate attributes to enable
index 76a47c49bbafb40be760823fffec771f98d4fc3d..7ce3dedaa887bf7f6a777d0444967c2f1412eff8 100644 (file)
@@ -96,13 +96,13 @@ LL |     assert_eq!(Foo::Bar, i);
    = help: the trait `Debug` is not implemented for `fn(usize) -> Foo {Foo::Bar}`
    = help: the following other types implement trait `Debug`:
              extern "C" fn() -> Ret
-             extern "C" fn(A) -> Ret
-             extern "C" fn(A, ...) -> Ret
              extern "C" fn(A, B) -> Ret
              extern "C" fn(A, B, ...) -> Ret
              extern "C" fn(A, B, C) -> Ret
              extern "C" fn(A, B, C, ...) -> Ret
              extern "C" fn(A, B, C, D) -> Ret
+             extern "C" fn(A, B, C, D, ...) -> Ret
+             extern "C" fn(A, B, C, D, E) -> Ret
            and 68 others
    = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)