From 6a4cced10cf963ecc9382082ba92d5838151cf8a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 8 Mar 2019 20:12:17 +0100 Subject: [PATCH 01/19] Fix moving text in search tabs headers --- src/librustdoc/html/static/rustdoc.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css index 787f3c7f48004..5314255ac322b 100644 --- a/src/librustdoc/html/static/rustdoc.css +++ b/src/librustdoc/html/static/rustdoc.css @@ -1195,7 +1195,7 @@ pre.rust { border-top: 2px solid; } -#titles > div:not(:last-child):not(.selected) { +#titles > div:not(:last-child) { margin-right: 1px; width: calc(33.3% - 1px); } From 8b5a748d507a30c8d97dca55bd2c3f0f0455e34e Mon Sep 17 00:00:00 2001 From: Kornel Date: Thu, 14 Mar 2019 22:52:56 +0000 Subject: [PATCH 02/19] Exclude old book redirect stubs from search engines --- src/bootstrap/doc.rs | 4 ++-- src/doc/redirect.inc | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 src/doc/redirect.inc diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index e0ad0422a6ce3..a70fb1f342389 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -331,7 +331,7 @@ fn invoke_rustdoc( let path = builder.src.join("src/doc").join(markdown); - let favicon = builder.src.join("src/doc/favicon.inc"); + let header = builder.src.join("src/doc/redirect.inc"); let footer = builder.src.join("src/doc/footer.inc"); let version_info = out.join("version_info.html"); @@ -341,7 +341,7 @@ fn invoke_rustdoc( cmd.arg("--html-after-content").arg(&footer) .arg("--html-before-content").arg(&version_info) - .arg("--html-in-header").arg(&favicon) + .arg("--html-in-header").arg(&header) .arg("--markdown-no-toc") .arg("--markdown-playground-url") .arg("https://play.rust-lang.org/") diff --git a/src/doc/redirect.inc b/src/doc/redirect.inc new file mode 100644 index 0000000000000..33e3860c2a434 --- /dev/null +++ b/src/doc/redirect.inc @@ -0,0 +1,2 @@ + + From 71bdeb022a9403707a17a62f51d9b35e5f76ff85 Mon Sep 17 00:00:00 2001 From: Christian Date: Wed, 20 Mar 2019 23:15:41 +0100 Subject: [PATCH 03/19] Initial version of the documentation change of std::convert. --- src/libcore/convert.rs | 170 ++++++++++++++++++++--------------------- 1 file changed, 85 insertions(+), 85 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 774d648558b48..ca166abebdf2a 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -1,26 +1,24 @@ -//! Traits for conversions between types. //! -//! The traits in this module provide a general way to talk about conversions -//! from one type to another. They follow the standard Rust conventions of -//! `as`/`into`/`from`. +//! The traits in this module provide a way to convert from one type to another type. //! -//! Like many traits, these are often used as bounds for generic functions, to -//! support arguments of multiple types. +//! Each trait serves a different purpose: //! -//! - Implement the `As*` traits for reference-to-reference conversions -//! - Implement the [`Into`] trait when you want to consume the value in the conversion -//! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions -//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the -//! conversion to fail +//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions +//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions +//! - Implement the [`From`] trait for consuming value-to-value conversions +//! - Implement the [`Into`] trait for consuming value-to-value conversions to types outside the current crate +//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but should be implemented when +//! the conversion can fail. //! -//! As a library author, you should prefer implementing [`From`][`From`] or +//! The traits in this module are often used as trait bounds for generic functions such that to +//! arguments of multiple types are supported. See the documentation of each trait for examples. +//! +//! As a library author, you should always prefer implementing [`From`][`From`] or //! [`TryFrom`][`TryFrom`] rather than [`Into`][`Into`] or [`TryInto`][`TryInto`], //! as [`From`] and [`TryFrom`] provide greater flexibility and offer //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a -//! blanket implementation in the standard library. However, there are some cases -//! where this is not possible, such as creating conversions into a type defined -//! outside your library, so implementing [`Into`] instead of [`From`] is -//! sometimes necessary. +//! blanket implementation in the standard library. Only implement [`Into`] or [`TryInto`] +//! when a conversion to a type outside the current crate is required. //! //! # Generic Implementations //! @@ -99,28 +97,20 @@ use fmt; #[inline] pub const fn identity(x: T) -> T { x } -/// A cheap reference-to-reference conversion. Used to convert a value to a -/// reference value within generic code. -/// -/// `AsRef` is very similar to, but serves a slightly different purpose than, -/// [`Borrow`]. +/// Used to do a cheap reference-to-reference conversion. +/// This trait is similar to [`AsMut`] which is used for converting between mutable references. +/// If you need to do a costly conversion it is better to implement [`From`] with type +/// ```&T``` or write a custom function. /// -/// `AsRef` is to be used when wishing to convert to a reference of another -/// type. -/// `Borrow` is more related to the notion of taking the reference. It is -/// useful when wishing to abstract over the type of reference -/// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated -/// in the same manner. -/// -/// The key difference between the two traits is the intention: /// +/// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`]: /// - Use `AsRef` when the goal is to simply convert into a reference /// - Use `Borrow` when the goal is related to writing code that is agnostic to /// the type of borrow and whether it is a reference or value /// /// [`Borrow`]: ../../std/borrow/trait.Borrow.html /// -/// **Note: this trait must not fail**. If the conversion can fail, use a +/// **Note: This trait must not fail**. If the conversion can fail, use a /// dedicated method which returns an [`Option`] or a [`Result`]. /// /// [`Option`]: ../../std/option/enum.Option.html @@ -134,7 +124,11 @@ pub const fn identity(x: T) -> T { x } /// /// # Examples /// -/// Both [`String`] and `&str` implement `AsRef`: +/// By using trait bounds we can accept arguments of different types as long as they can be +/// converted a the specified type ```T```. +/// For example: By creating a generic function that takes an ```AsRef``` we express that we +/// want to accept all references that can be converted to &str as an argument. +/// Since both [`String`] and `&str` implement `AsRef` we can accept both as input argument. /// /// [`String`]: ../../std/string/struct.String.html /// @@ -157,12 +151,12 @@ pub trait AsRef { fn as_ref(&self) -> &T; } -/// A cheap, mutable reference-to-mutable reference conversion. -/// -/// This trait is similar to `AsRef` but used for converting between mutable -/// references. +/// Used to do a cheap mutable-to-mutable reference conversion. +/// This trait is similar to [`AsRef`] but used for converting between mutable +/// references. If you need to do a costly conversion it is better to +/// implement [`From`] with type ```&mut T``` or write a custom function. /// -/// **Note: this trait must not fail**. If the conversion can fail, use a +/// **Note: This trait must not fail**. If the conversion can fail, use a /// dedicated method which returns an [`Option`] or a [`Result`]. /// /// [`Option`]: ../../std/option/enum.Option.html @@ -176,10 +170,11 @@ pub trait AsRef { /// /// # Examples /// -/// [`Box`] implements `AsMut`: -/// -/// [`Box`]: ../../std/boxed/struct.Box.html -/// +/// Using ```AsMut``` as trait bound for a generic function we can accept all mutable references +/// that can be converted to type ```&mut T```. Because [`Box`] implements ```AsMut``` we can +/// write a function ```add_one```that takes all arguments that can be converted to ```&mut u64```. +/// Because [`Box`] implements ```AsMut``` ```add_one``` accepts arguments of type +/// ```&mut Box``` as well: /// ``` /// fn add_one>(num: &mut T) { /// *num.as_mut() += 1; @@ -189,7 +184,7 @@ pub trait AsRef { /// add_one(&mut boxed_num); /// assert_eq!(*boxed_num, 1); /// ``` -/// +/// [`Box`]: ../../std/boxed/struct.Box.html /// #[stable(feature = "rust1", since = "1.0.0")] pub trait AsMut { @@ -198,29 +193,24 @@ pub trait AsMut { fn as_mut(&mut self) -> &mut T; } -/// A conversion that consumes `self`, which may or may not be expensive. The -/// reciprocal of [`From`][From]. +/// A value-to-value conversion that consumes the input value. The +/// opposite of [`From`]. /// -/// **Note: this trait must not fail**. If the conversion can fail, use -/// [`TryInto`] or a dedicated method which returns an [`Option`] or a -/// [`Result`]. +/// One should only implement [`Into`] if a conversion to a type outside the current crate is required. +/// Otherwise one should always prefer implementing [`From`] over [`Into`] because implementing [`From`] automatically +/// provides one with a implementation of [`Into`] thanks to the blanket implementation in the standard library. +/// [`From`] cannot do these type of conversions because of Rust's orphaning rules. /// -/// Library authors should not directly implement this trait, but should prefer -/// implementing the [`From`][From] trait, which offers greater flexibility and -/// provides an equivalent `Into` implementation for free, thanks to a blanket -/// implementation in the standard library. +/// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. /// /// # Generic Implementations /// -/// - [`From`][From]` for U` implies `Into for T` -/// - [`into`] is reflexive, which means that `Into for T` is implemented -/// -/// # Implementing `Into` +/// - [`From`]` for U` implies `Into for T` +/// - [`Into`]` is reflexive, which means that `Into for T` is implemented /// -/// There is one exception to implementing `Into`, and it's kind of esoteric. -/// If the destination type is not part of the current crate, and it uses a -/// generic variable, then you can't implement `From` directly. For example, -/// take this crate: +/// # Implementing `Into` for conversions to external types +/// If the destination type is not part of the current crate then you can't implement [`From`] directly. +/// For example, take this code: /// /// ```compile_fail /// struct Wrapper(Vec); @@ -230,8 +220,9 @@ pub trait AsMut { /// } /// } /// ``` -/// -/// To fix this, you can implement `Into` directly: +/// This will fail to compile because we cannot implement a trait for a type +/// if both the trait and the type are not defined by the current crate. +/// This is due to Rust's orphaning rules. To bypass this, you can implement `Into` directly: /// /// ``` /// struct Wrapper(Vec); @@ -242,17 +233,21 @@ pub trait AsMut { /// } /// ``` /// -/// This won't always allow the conversion: for example, `try!` and `?` -/// always use `From`. However, in most cases, people use `Into` to do the -/// conversions, and this will allow that. +/// It is important to understand that ```Into``` does not provide a [`From`] implementation (as [`From`] does with ```Into```). +/// Therefore, you should always try to implement [`From`] and then fall back to `Into` if [`From`] can't be implemented. +/// Prefer using ```Into``` over ```From``` when specifying trait bounds on a generic function +/// to ensure that types that only implement ```Into``` can be used as well. /// -/// In almost all cases, you should try to implement `From`, then fall back -/// to `Into` if `From` can't be implemented. /// /// # Examples /// /// [`String`] implements `Into>`: /// +/// In order to express that we want a generic function to take all arguments that can be +/// converted to a specified type ```T```, we can use a trait bound of ```Into```. +/// For example: The function ```is_hello``` takes all arguments that can be converted into a +/// ```Vec```. +/// /// ``` /// fn is_hello>>(s: T) { /// let bytes = b"hello".to_vec(); @@ -276,36 +271,36 @@ pub trait Into: Sized { fn into(self) -> T; } -/// Simple and safe type conversions in to `Self`. It is the reciprocal of -/// `Into`. +/// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of +/// [`Into`]. /// -/// This trait is useful when performing error handling as described by -/// [the book][book] and is closely related to the `?` operator. +/// One should always prefer implementing [`From`] over [`Into`] because implementing [`From`] automatically +/// provides one with a implementation of [`Into`] thanks to the blanket implementation in the standard library. +/// Only implement [`Into`] if a conversion to a type outside the current crate is required. +/// [`From`] cannot do these type of conversions because of Rust's orphaning rules. +/// See [`Into`] for more details. /// -/// When constructing a function that is capable of failing the return type -/// will generally be of the form `Result`. -/// -/// The `From` trait allows for simplification of error handling by providing a -/// means of returning a single error type that encapsulates numerous possible -/// erroneous situations. +/// Prefer using [`Into`] over using [`From`] when specifying trait bounds on a generic function. +/// This way, types that directly implement [`Into`] can be used as arguments as well. /// -/// This trait is not limited to error handling, rather the general case for -/// this trait would be in any type conversions to have an explicit definition -/// of how they are performed. +/// The [`From`] is also very useful when performing error handling. +/// When constructing a function that is capable of failing, the return type +/// will generally be of the form `Result`. +/// The `From` trait simplifies error handling by allowing a function to return a single error type +/// that encapsulate multiple error types. See the "Examples" section for more details. /// -/// **Note: this trait must not fail**. If the conversion can fail, use -/// [`TryFrom`] or a dedicated method which returns an [`Option`] or a -/// [`Result`]. +/// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. /// /// # Generic Implementations /// -/// - `From for U` implies [`Into`]` for T` -/// - [`from`] is reflexive, which means that `From for T` is implemented +/// - [`From`]` for U` implies [`Into`]` for T` +/// - [`From`] is reflexive, which means that `From for T` is implemented /// /// # Examples /// /// [`String`] implements `From<&str>`: /// +/// An explicit conversion from a &str to a String is done as follows: /// ``` /// let string = "hello".to_string(); /// let other_string = String::from("hello"); @@ -313,7 +308,12 @@ pub trait Into: Sized { /// assert_eq!(string, other_string); /// ``` /// -/// An example usage for error handling: +/// While performing error handling it is often useful to implement ```From``` for your own error type. +/// By converting underlying error types to our own custom error type that encapsulates the underlying +/// error type, we can return a single error type without losing information on the underlying cause. +/// The '?' operator automatically converts the underlying error type to our custom error type by +/// calling ```Into::into``` which is automatically provided when implementing ```From```. +/// The compiler then infers which implementation of ```Into``` should be used. /// /// ``` /// use std::fs; @@ -350,7 +350,7 @@ pub trait Into: Sized { /// [`String`]: ../../std/string/struct.String.html /// [`Into`]: trait.Into.html /// [`from`]: trait.From.html#tymethod.from -/// [book]: ../../book/ch09-00-error-handling.html +/// [book]: ../../book/first-edition/error-handling.html #[stable(feature = "rust1", since = "1.0.0")] pub trait From: Sized { /// Performs the conversion. From 49a9b349acda7bbf8d555cda4218351472534173 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 21 Mar 2019 15:06:16 +0100 Subject: [PATCH 04/19] Reformatted the text such that the line length does not exceed 100. --- src/libcore/convert.rs | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index ca166abebdf2a..30c3823e0b4bc 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -6,8 +6,10 @@ //! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions //! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions //! - Implement the [`From`] trait for consuming value-to-value conversions -//! - Implement the [`Into`] trait for consuming value-to-value conversions to types outside the current crate -//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but should be implemented when +//! - Implement the [`Into`] trait for consuming value-to-value conversions to types +//! outside the current crate +//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], +//! but should be implemented when //! the conversion can fail. //! //! The traits in this module are often used as trait bounds for generic functions such that to @@ -196,9 +198,10 @@ pub trait AsMut { /// A value-to-value conversion that consumes the input value. The /// opposite of [`From`]. /// -/// One should only implement [`Into`] if a conversion to a type outside the current crate is required. -/// Otherwise one should always prefer implementing [`From`] over [`Into`] because implementing [`From`] automatically -/// provides one with a implementation of [`Into`] thanks to the blanket implementation in the standard library. +/// One should only implement [`Into`] if a conversion to a type outside the current crate is +/// required. Otherwise one should always prefer implementing [`From`] over [`Into`] because +/// implementing [`From`] automatically provides one with a implementation of [`Into`] +/// thanks to the blanket implementation in the standard library. /// [`From`] cannot do these type of conversions because of Rust's orphaning rules. /// /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. @@ -209,7 +212,8 @@ pub trait AsMut { /// - [`Into`]` is reflexive, which means that `Into for T` is implemented /// /// # Implementing `Into` for conversions to external types -/// If the destination type is not part of the current crate then you can't implement [`From`] directly. +/// If the destination type is not part of the current crate +/// then you can't implement [`From`] directly. /// For example, take this code: /// /// ```compile_fail @@ -233,8 +237,9 @@ pub trait AsMut { /// } /// ``` /// -/// It is important to understand that ```Into``` does not provide a [`From`] implementation (as [`From`] does with ```Into```). -/// Therefore, you should always try to implement [`From`] and then fall back to `Into` if [`From`] can't be implemented. +/// It is important to understand that ```Into``` does not provide a [`From`] implementation +/// (as [`From`] does with ```Into```). Therefore, you should always try to implement [`From`] +/// and then fall back to `Into` if [`From`] can't be implemented. /// Prefer using ```Into``` over ```From``` when specifying trait bounds on a generic function /// to ensure that types that only implement ```Into``` can be used as well. /// @@ -274,8 +279,9 @@ pub trait Into: Sized { /// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of /// [`Into`]. /// -/// One should always prefer implementing [`From`] over [`Into`] because implementing [`From`] automatically -/// provides one with a implementation of [`Into`] thanks to the blanket implementation in the standard library. +/// One should always prefer implementing [`From`] over [`Into`] +/// because implementing [`From`] automatically provides one with a implementation of [`Into`] +/// thanks to the blanket implementation in the standard library. /// Only implement [`Into`] if a conversion to a type outside the current crate is required. /// [`From`] cannot do these type of conversions because of Rust's orphaning rules. /// See [`Into`] for more details. @@ -308,11 +314,12 @@ pub trait Into: Sized { /// assert_eq!(string, other_string); /// ``` /// -/// While performing error handling it is often useful to implement ```From``` for your own error type. -/// By converting underlying error types to our own custom error type that encapsulates the underlying -/// error type, we can return a single error type without losing information on the underlying cause. -/// The '?' operator automatically converts the underlying error type to our custom error type by -/// calling ```Into::into``` which is automatically provided when implementing ```From```. +/// While performing error handling it is often useful to implement ```From``` +/// for your own error type. By converting underlying error types to our own custom error type +/// that encapsulates the underlying error type, we can return a single error type +/// without losing information on the underlying cause. The '?' operator automatically converts +/// the underlying error type to our custom error type by calling ```Into::into``` +/// which is automatically provided when implementing ```From```. /// The compiler then infers which implementation of ```Into``` should be used. /// /// ``` From d657d180835cee1e4b4ad4400d1f33f62ecd37b6 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 21 Mar 2019 15:26:07 +0100 Subject: [PATCH 05/19] Fixed indentation of list items. --- src/libcore/convert.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 30c3823e0b4bc..ec15a7f68fb07 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -7,10 +7,9 @@ //! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions //! - Implement the [`From`] trait for consuming value-to-value conversions //! - Implement the [`Into`] trait for consuming value-to-value conversions to types -//! outside the current crate +//! outside the current crate //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], -//! but should be implemented when -//! the conversion can fail. +//! but should be implemented when the conversion can fail. //! //! The traits in this module are often used as trait bounds for generic functions such that to //! arguments of multiple types are supported. See the documentation of each trait for examples. @@ -243,7 +242,6 @@ pub trait AsMut { /// Prefer using ```Into``` over ```From``` when specifying trait bounds on a generic function /// to ensure that types that only implement ```Into``` can be used as well. /// -/// /// # Examples /// /// [`String`] implements `Into>`: From a66fca459aeead957e0160b3bbe842c5d9951dfb Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 21 Mar 2019 18:42:15 +0100 Subject: [PATCH 06/19] Added back a reference to "the book" --- src/libcore/convert.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index ec15a7f68fb07..ce7472f33292a 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -291,7 +291,7 @@ pub trait Into: Sized { /// When constructing a function that is capable of failing, the return type /// will generally be of the form `Result`. /// The `From` trait simplifies error handling by allowing a function to return a single error type -/// that encapsulate multiple error types. See the "Examples" section for more details. +/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more details. /// /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. /// @@ -355,7 +355,7 @@ pub trait Into: Sized { /// [`String`]: ../../std/string/struct.String.html /// [`Into`]: trait.Into.html /// [`from`]: trait.From.html#tymethod.from -/// [book]: ../../book/first-edition/error-handling.html +/// [book]: ../../book/ch09-00-error-handling.html #[stable(feature = "rust1", since = "1.0.0")] pub trait From: Sized { /// Performs the conversion. From d7fcd219c5cc79af1d8f24d7f41d12466d349bdd Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 21 Mar 2019 18:49:12 +0100 Subject: [PATCH 07/19] Changed inline code by using a single quote. --- src/libcore/convert.rs | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index ce7472f33292a..4402dc2fa415d 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -101,7 +101,7 @@ pub const fn identity(x: T) -> T { x } /// Used to do a cheap reference-to-reference conversion. /// This trait is similar to [`AsMut`] which is used for converting between mutable references. /// If you need to do a costly conversion it is better to implement [`From`] with type -/// ```&T``` or write a custom function. +/// `&T` or write a custom function. /// /// /// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`]: @@ -126,8 +126,8 @@ pub const fn identity(x: T) -> T { x } /// # Examples /// /// By using trait bounds we can accept arguments of different types as long as they can be -/// converted a the specified type ```T```. -/// For example: By creating a generic function that takes an ```AsRef``` we express that we +/// converted a the specified type `T`. +/// For example: By creating a generic function that takes an `AsRef` we express that we /// want to accept all references that can be converted to &str as an argument. /// Since both [`String`] and `&str` implement `AsRef` we can accept both as input argument. /// @@ -155,7 +155,7 @@ pub trait AsRef { /// Used to do a cheap mutable-to-mutable reference conversion. /// This trait is similar to [`AsRef`] but used for converting between mutable /// references. If you need to do a costly conversion it is better to -/// implement [`From`] with type ```&mut T``` or write a custom function. +/// implement [`From`] with type `&mut T` or write a custom function. /// /// **Note: This trait must not fail**. If the conversion can fail, use a /// dedicated method which returns an [`Option`] or a [`Result`]. @@ -171,11 +171,11 @@ pub trait AsRef { /// /// # Examples /// -/// Using ```AsMut``` as trait bound for a generic function we can accept all mutable references -/// that can be converted to type ```&mut T```. Because [`Box`] implements ```AsMut``` we can -/// write a function ```add_one```that takes all arguments that can be converted to ```&mut u64```. -/// Because [`Box`] implements ```AsMut``` ```add_one``` accepts arguments of type -/// ```&mut Box``` as well: +/// Using `AsMut` as trait bound for a generic function we can accept all mutable references +/// that can be converted to type `&mut T`. Because [`Box`] implements `AsMut` we can +/// write a function `add_one`that takes all arguments that can be converted to `&mut u64`. +/// Because [`Box`] implements `AsMut` `add_one` accepts arguments of type +/// `&mut Box` as well: /// ``` /// fn add_one>(num: &mut T) { /// *num.as_mut() += 1; @@ -236,20 +236,20 @@ pub trait AsMut { /// } /// ``` /// -/// It is important to understand that ```Into``` does not provide a [`From`] implementation -/// (as [`From`] does with ```Into```). Therefore, you should always try to implement [`From`] +/// It is important to understand that `Into` does not provide a [`From`] implementation +/// (as [`From`] does with `Into`). Therefore, you should always try to implement [`From`] /// and then fall back to `Into` if [`From`] can't be implemented. -/// Prefer using ```Into``` over ```From``` when specifying trait bounds on a generic function -/// to ensure that types that only implement ```Into``` can be used as well. +/// Prefer using `Into` over [`From`] when specifying trait bounds on a generic function +/// to ensure that types that only implement `Into` can be used as well. /// /// # Examples /// /// [`String`] implements `Into>`: /// /// In order to express that we want a generic function to take all arguments that can be -/// converted to a specified type ```T```, we can use a trait bound of ```Into```. -/// For example: The function ```is_hello``` takes all arguments that can be converted into a -/// ```Vec```. +/// converted to a specified type `T`, we can use a trait bound of `Into`. +/// For example: The function `is_hello` takes all arguments that can be converted into a +/// `Vec`. /// /// ``` /// fn is_hello>>(s: T) { @@ -312,13 +312,13 @@ pub trait Into: Sized { /// assert_eq!(string, other_string); /// ``` /// -/// While performing error handling it is often useful to implement ```From``` +/// While performing error handling it is often useful to implement `From` /// for your own error type. By converting underlying error types to our own custom error type /// that encapsulates the underlying error type, we can return a single error type /// without losing information on the underlying cause. The '?' operator automatically converts -/// the underlying error type to our custom error type by calling ```Into::into``` -/// which is automatically provided when implementing ```From```. -/// The compiler then infers which implementation of ```Into``` should be used. +/// the underlying error type to our custom error type by calling `Into::into` +/// which is automatically provided when implementing `From`. +/// The compiler then infers which implementation of `Into` should be used. /// /// ``` /// use std::fs; From 70ce4b168d697a55a5aaaebf39e4bda5c4b9db58 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 21 Mar 2019 19:36:51 +0100 Subject: [PATCH 08/19] Wrapped a line such that it does not exceed 100 characters. --- src/libcore/convert.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 4402dc2fa415d..9f72d02d865d3 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -291,7 +291,8 @@ pub trait Into: Sized { /// When constructing a function that is capable of failing, the return type /// will generally be of the form `Result`. /// The `From` trait simplifies error handling by allowing a function to return a single error type -/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more details. +/// that encapsulate multiple error types. See the "Examples" section +/// and [the book][book] for more details. /// /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. /// From 64382f4b78bdca6bea1dd06e4a1039646b04ae93 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 02:44:28 +0100 Subject: [PATCH 09/19] Greatly improve generics handling in rustdoc search --- src/librustc_typeck/collect.rs | 60 ++++++++-- src/librustc_typeck/lib.rs | 2 + src/librustdoc/clean/inline.rs | 10 +- src/librustdoc/clean/mod.rs | 210 +++++++++++++++++++++++++++++++-- src/librustdoc/html/render.rs | 13 +- 5 files changed, 273 insertions(+), 22 deletions(-) diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 10e9613bf21a2..e723ee1d10adc 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1130,13 +1130,29 @@ fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: } fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { + checked_type_of(tcx, def_id, true).unwrap() +} + +pub fn checked_type_of<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + def_id: DefId, + fail: bool, +) -> Option> { use rustc::hir::*; - let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); + let hir_id = match tcx.hir().as_local_hir_id(def_id) { + Some(hir_id) => hir_id, + None => { + if !fail { + return None; + } + bug!("invalid node"); + } + }; let icx = ItemCtxt::new(tcx, def_id); - match tcx.hir().get_by_hir_id(hir_id) { + Some(match tcx.hir().get_by_hir_id(hir_id) { Node::TraitItem(item) => match item.node { TraitItemKind::Method(..) => { let substs = InternalSubsts::identity_for_item(tcx, def_id); @@ -1144,6 +1160,9 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { } TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty), TraitItemKind::Type(_, None) => { + if !fail { + return None; + } span_bug!(item.span, "associated type missing default"); } }, @@ -1225,6 +1244,9 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { | ItemKind::GlobalAsm(..) | ItemKind::ExternCrate(..) | ItemKind::Use(..) => { + if !fail { + return None; + } span_bug!( item.span, "compute_type_of_item: unexpected item type: {:?}", @@ -1264,7 +1286,7 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { .. }) => { if gen.is_some() { - return tcx.typeck_tables_of(def_id).node_type(hir_id); + return Some(tcx.typeck_tables_of(def_id).node_type(hir_id)); } let substs = ty::ClosureSubsts { @@ -1342,6 +1364,9 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { } // Sanity check to make sure everything is as expected. if !found_const { + if !fail { + return None; + } bug!("no arg matching AnonConst in path") } match path.def { @@ -1367,14 +1392,27 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { return tcx.types.err; } Def::Err => tcx.types.err, - x => bug!("unexpected const parent path def {:?}", x), + x => { + if !fail { + return None; + } + bug!("unexpected const parent path def {:?}", x); + } + } + } + x => { + if !fail { + return None; } + bug!("unexpected const parent path {:?}", x); } - x => bug!("unexpected const parent path {:?}", x), } } x => { + if !fail { + return None; + } bug!("unexpected const parent in type_of_def_id(): {:?}", x); } } @@ -1385,13 +1423,21 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { hir::GenericParamKind::Const { ref ty, .. } => { icx.to_ty(ty) } - x => bug!("unexpected non-type Node::GenericParam: {:?}", x), + x => { + if !fail { + return None; + } + bug!("unexpected non-type Node::GenericParam: {:?}", x) + }, }, x => { + if !fail { + return None; + } bug!("unexpected sort of node in type_of_def_id(): {:?}", x); } - } + }) } fn find_existential_constraints<'a, 'tcx>( diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index cbed7d26a9950..7bb381d92d836 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -115,6 +115,8 @@ use util::common::time; use std::iter; +pub use collect::checked_type_of; + pub struct TypeAndSubsts<'tcx> { substs: SubstsRef<'tcx>, ty: Ty<'tcx>, diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 880f67281b967..2b45831f224fb 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -212,15 +212,19 @@ fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function { }; let predicates = cx.tcx.predicates_of(did); + let generics = (cx.tcx.generics_of(did), &predicates).clean(cx); + let decl = (did, sig).clean(cx); + let all_types = clean::get_all_types(&generics, &decl, cx); clean::Function { - decl: (did, sig).clean(cx), - generics: (cx.tcx.generics_of(did), &predicates).clean(cx), + decl, + generics, header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness: hir::IsAsync::NotAsync, - } + }, + all_types, } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 4819256a54550..5d691b1873b70 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1084,9 +1084,10 @@ impl GenericBound { fn get_trait_type(&self) -> Option { if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { - return Some(trait_.clone()); + Some(trait_.clone()) + } else { + None } - None } } @@ -1319,6 +1320,16 @@ pub enum WherePredicate { EqPredicate { lhs: Type, rhs: Type }, } +impl WherePredicate { + pub fn get_bounds(&self) -> Option<&[GenericBound]> { + match *self { + WherePredicate::BoundPredicate { ref bounds, .. } => Some(bounds), + WherePredicate::RegionPredicate { ref bounds, .. } => Some(bounds), + _ => None, + } + } +} + impl Clean for hir::WherePredicate { fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { match *self { @@ -1455,6 +1466,25 @@ pub enum GenericParamDefKind { }, } +impl GenericParamDefKind { + pub fn is_type(&self) -> bool { + match *self { + GenericParamDefKind::Type { .. } => true, + _ => false, + } + } + + pub fn get_type(&self, cx: &DocContext<'_, '_, '_>) -> Option { + match *self { + GenericParamDefKind::Type { did, .. } => { + rustc_typeck::checked_type_of(cx.tcx, did, false).map(|t| t.clean(cx)) + } + GenericParamDefKind::Const { ref ty, .. } => Some(ty.clone()), + GenericParamDefKind::Lifetime => None, + } + } +} + #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct GenericParamDef { pub name: String, @@ -1466,12 +1496,25 @@ impl GenericParamDef { pub fn is_synthetic_type_param(&self) -> bool { match self.kind { GenericParamDefKind::Lifetime | - GenericParamDefKind::Const { .. } => { - false - } + GenericParamDefKind::Const { .. } => false, GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(), } } + + pub fn is_type(&self) -> bool { + self.kind.is_type() + } + + pub fn get_type(&self, cx: &DocContext<'_, '_, '_>) -> Option { + self.kind.get_type(cx) + } + + pub fn get_bounds(&self) -> Option<&[GenericBound]> { + match self.kind { + GenericParamDefKind::Type { ref bounds, .. } => Some(bounds), + _ => None, + } + } } impl<'tcx> Clean for ty::GenericParamDef { @@ -1707,12 +1750,145 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, } } +// The point is to replace bounds with types. +pub fn get_real_types( + generics: &Generics, + arg: &Type, + cx: &DocContext<'_, '_, '_>, + debug: bool, +) -> Option> { + let mut res = Vec::new(); + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("0. {:?}", arg); + } + if let Some(where_pred) = generics.where_predicates.iter().find(|g| { + match g { + &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), + _ => false, + } + }) { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("1. {:?} => {:?}", arg, where_pred); + } + let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]); + for bound in bounds.iter() { + match *bound { + GenericBound::TraitBound(ref poly_trait, _) => { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!(" {:?}", poly_trait.trait_); + } + for x in poly_trait.generic_params.iter() { + if !x.is_type() { + continue + } + if let Some(ty) = x.get_type(cx) { + if let Some(mut adds) = get_real_types(generics, &ty, cx, + arg.to_string() == "W" || arg.to_string() == "Z" || debug) { + res.append(&mut adds); + } else if !ty.is_full_generic() { + res.push(ty); + } + } + } + } + _ => {} + } + } + } else { + let arg_s = arg.to_string(); + if let Some(bound) = generics.params.iter().find(|g| { + g.is_type() && g.name == arg_s + }) { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("2. {:?} => {:?}", arg, bound); + } + for bound in bound.get_bounds().unwrap_or_else(|| &[]) { + if let Some(ty) = bound.get_trait_type() { + if let Some(mut adds) = get_real_types(generics, &ty, cx, + arg.to_string() == "W" || arg.to_string() == "Z" || debug) { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("3. {:?}", adds); + } + res.append(&mut adds); + } else { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("4. {:?}", ty); + } + if !ty.is_full_generic() { + res.push(ty.clone()); + } + } + } + } + /*if let Some(ty) = bound.get_type(cx) { + if let Some(mut adds) = get_real_types(generics, &ty, cx, level + 1) { + res.append(&mut adds); + } else { + res.push(ty); + } + } else { + res.push(arg.clone()); + }*/ + } else if let Some(gens) = arg.generics() { + res.push(arg.clone()); + for gen in gens.iter() { + if gen.is_full_generic() { + if let Some(mut adds) = get_real_types(generics, gen, cx, + arg.to_string() == "W" || arg.to_string() == "Z" || debug) { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("5. {:?}", adds); + } + res.append(&mut adds); + } + } else { + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("6. {:?}", gen); + } + res.push(gen.clone()); + } + } + } + } + if res.is_empty() && !arg.is_full_generic() { + res.push(arg.clone()); + } + if arg.to_string() == "W" || arg.to_string() == "Z" || debug { + println!("7. /!\\ {:?}", res); + } + Some(res) +} + +pub fn get_all_types( + generics: &Generics, + decl: &FnDecl, + cx: &DocContext<'_, '_, '_>, +) -> Vec { + let mut all_types = Vec::new(); + for arg in decl.inputs.values.iter() { + if arg.type_.is_self_type() { + continue; + } + if let Some(mut args) = get_real_types(generics, &arg.type_, cx, false) { + all_types.append(&mut args); + } else { + all_types.push(arg.type_.clone()); + } + } + all_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).expect("a") ); + all_types.dedup(); + if decl.inputs.values.iter().any(|s| s.type_.to_string() == "W" || s.type_.to_string() == "Z") { + println!("||||> {:?}", all_types); + } + all_types +} + #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Method { pub generics: Generics, pub decl: FnDecl, pub header: hir::FnHeader, pub defaultness: Option, + pub all_types: Vec, } impl<'a> Clean for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, @@ -1721,11 +1897,13 @@ impl<'a> Clean for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, let (generics, decl) = enter_impl_trait(cx, || { (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)) }); + let all_types = get_all_types(&generics, &decl, cx); Method { decl, generics, header: self.0.header, defaultness: self.3, + all_types, } } } @@ -1735,6 +1913,7 @@ pub struct TyMethod { pub header: hir::FnHeader, pub decl: FnDecl, pub generics: Generics, + pub all_types: Vec, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -1742,6 +1921,7 @@ pub struct Function { pub decl: FnDecl, pub generics: Generics, pub header: hir::FnHeader, + pub all_types: Vec, } impl Clean for doctree::Function { @@ -1756,6 +1936,7 @@ impl Clean for doctree::Function { } else { hir::Constness::NotConst }; + let all_types = get_all_types(&generics, &decl, cx); Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -1768,6 +1949,7 @@ impl Clean for doctree::Function { decl, generics, header: hir::FnHeader { constness, ..self.header }, + all_types, }), } } @@ -1855,7 +2037,7 @@ impl<'a, A: Copy> Clean for (&'a hir::FnDecl, A) FnDecl { inputs: (&self.0.inputs[..], self.1).clean(cx), output: self.0.output.clean(cx), - attrs: Attributes::default() + attrs: Attributes::default(), } } } @@ -2037,10 +2219,12 @@ impl Clean for hir::TraitItem { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) }); + let all_types = get_all_types(&generics, &decl, cx); TyMethodItem(TyMethod { header: sig.header, decl, generics, + all_types, }) } hir::TraitItemKind::Type(ref bounds, ref default) => { @@ -2138,6 +2322,7 @@ impl<'tcx> Clean for ty::AssociatedItem { ty::ImplContainer(_) => true, ty::TraitContainer(_) => self.defaultness.has_value() }; + let all_types = get_all_types(&generics, &decl, cx); if provided { let constness = if cx.tcx.is_min_const_fn(self.def_id) { hir::Constness::Const @@ -2154,6 +2339,7 @@ impl<'tcx> Clean for ty::AssociatedItem { asyncness: hir::IsAsync::NotAsync, }, defaultness: Some(self.defaultness), + all_types, }) } else { TyMethodItem(TyMethod { @@ -2164,7 +2350,8 @@ impl<'tcx> Clean for ty::AssociatedItem { abi: sig.abi(), constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, - } + }, + all_types, }) } } @@ -2410,6 +2597,13 @@ impl Type { _ => None } } + + pub fn is_full_generic(&self) -> bool { + match *self { + Type::Generic(_) => true, + _ => false, + } + } } impl GetDefId for Type { @@ -3824,6 +4018,7 @@ impl Clean for hir::ForeignItem { let (generics, decl) = enter_impl_trait(cx, || { (generics.clean(cx), (&**decl, &names[..]).clean(cx)) }); + let all_types = get_all_types(&generics, &decl, cx); ForeignFunctionItem(Function { decl, generics, @@ -3833,6 +4028,7 @@ impl Clean for hir::ForeignItem { constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, }, + all_types, }) } hir::ForeignItemKind::Static(ref ty, mutbl) => { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index a262a2f28853c..402eb1800829c 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -5025,14 +5025,17 @@ fn make_item_keywords(it: &clean::Item) -> String { } fn get_index_search_type(item: &clean::Item) -> Option { - let decl = match item.inner { - clean::FunctionItem(ref f) => &f.decl, - clean::MethodItem(ref m) => &m.decl, - clean::TyMethodItem(ref m) => &m.decl, + let (decl, all_types) = match item.inner { + clean::FunctionItem(ref f) => (&f.decl, &f.all_types), + clean::MethodItem(ref m) => (&m.decl, &m.all_types), + clean::TyMethodItem(ref m) => (&m.decl, &m.all_types), _ => return None }; - let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect(); + println!("====> {:?}", all_types); + let inputs = all_types.iter().map(|arg| { + get_index_type(&arg) + }).collect(); let output = match decl.output { clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)), _ => None From d611301e3e7e5800fe3267b7ad55ac8822adc89a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 15:33:18 +0100 Subject: [PATCH 10/19] Small generics search improvement --- src/librustdoc/html/static/main.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index fef6910f40a57..588d82748b390 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -714,7 +714,10 @@ if (!DOMTokenList.prototype.remove) { } lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance); if (lev_distance <= MAX_LEV_DISTANCE) { - lev_distance = Math.min(checkGenerics(obj, val), lev_distance); + // The generics didn't match but the name kinda did so we give it + // a levenshtein distance value that isn't *this* good so it goes + // into the search results but not too high. + lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2); } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) { // We can check if the type we're looking for is inside the generics! var olength = obj[GENERICS_DATA].length; From 6ae73e2ff607e6d7dc8b49ce223961f12471cc38 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 15:48:29 +0100 Subject: [PATCH 11/19] Improve bounds search --- src/librustdoc/clean/mod.rs | 54 ++++------------------------------- src/librustdoc/html/render.rs | 9 +++--- 2 files changed, 11 insertions(+), 52 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5d691b1873b70..f92f129d803f9 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1755,35 +1755,24 @@ pub fn get_real_types( generics: &Generics, arg: &Type, cx: &DocContext<'_, '_, '_>, - debug: bool, ) -> Option> { let mut res = Vec::new(); - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("0. {:?}", arg); - } if let Some(where_pred) = generics.where_predicates.iter().find(|g| { match g { &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), _ => false, } }) { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("1. {:?} => {:?}", arg, where_pred); - } let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]); for bound in bounds.iter() { match *bound { GenericBound::TraitBound(ref poly_trait, _) => { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!(" {:?}", poly_trait.trait_); - } for x in poly_trait.generic_params.iter() { if !x.is_type() { continue } if let Some(ty) = x.get_type(cx) { - if let Some(mut adds) = get_real_types(generics, &ty, cx, - arg.to_string() == "W" || arg.to_string() == "Z" || debug) { + if let Some(mut adds) = get_real_types(generics, &ty, cx) { res.append(&mut adds); } else if !ty.is_full_generic() { res.push(ty); @@ -1799,51 +1788,25 @@ pub fn get_real_types( if let Some(bound) = generics.params.iter().find(|g| { g.is_type() && g.name == arg_s }) { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("2. {:?} => {:?}", arg, bound); - } for bound in bound.get_bounds().unwrap_or_else(|| &[]) { if let Some(ty) = bound.get_trait_type() { - if let Some(mut adds) = get_real_types(generics, &ty, cx, - arg.to_string() == "W" || arg.to_string() == "Z" || debug) { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("3. {:?}", adds); - } + if let Some(mut adds) = get_real_types(generics, &ty, cx) { res.append(&mut adds); } else { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("4. {:?}", ty); - } if !ty.is_full_generic() { res.push(ty.clone()); } } } } - /*if let Some(ty) = bound.get_type(cx) { - if let Some(mut adds) = get_real_types(generics, &ty, cx, level + 1) { - res.append(&mut adds); - } else { - res.push(ty); - } - } else { - res.push(arg.clone()); - }*/ } else if let Some(gens) = arg.generics() { res.push(arg.clone()); for gen in gens.iter() { if gen.is_full_generic() { - if let Some(mut adds) = get_real_types(generics, gen, cx, - arg.to_string() == "W" || arg.to_string() == "Z" || debug) { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("5. {:?}", adds); - } + if let Some(mut adds) = get_real_types(generics, gen, cx) { res.append(&mut adds); } } else { - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("6. {:?}", gen); - } res.push(gen.clone()); } } @@ -1852,9 +1815,6 @@ pub fn get_real_types( if res.is_empty() && !arg.is_full_generic() { res.push(arg.clone()); } - if arg.to_string() == "W" || arg.to_string() == "Z" || debug { - println!("7. /!\\ {:?}", res); - } Some(res) } @@ -1868,17 +1828,15 @@ pub fn get_all_types( if arg.type_.is_self_type() { continue; } - if let Some(mut args) = get_real_types(generics, &arg.type_, cx, false) { + if let Some(mut args) = get_real_types(generics, &arg.type_, cx) { all_types.append(&mut args); } else { all_types.push(arg.type_.clone()); } } - all_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).expect("a") ); + // FIXME: use a HashSet instead? + all_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).unwrap()); all_types.dedup(); - if decl.inputs.values.iter().any(|s| s.type_.to_string() == "W" || s.type_.to_string() == "Z") { - println!("||||> {:?}", all_types); - } all_types } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 402eb1800829c..5c2051710f869 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -5029,16 +5029,17 @@ fn get_index_search_type(item: &clean::Item) -> Option { clean::FunctionItem(ref f) => (&f.decl, &f.all_types), clean::MethodItem(ref m) => (&m.decl, &m.all_types), clean::TyMethodItem(ref m) => (&m.decl, &m.all_types), - _ => return None + _ => return None, }; - println!("====> {:?}", all_types); let inputs = all_types.iter().map(|arg| { get_index_type(&arg) }).collect(); let output = match decl.output { - clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)), - _ => None + clean::FunctionRetTy::Return(ref return_type) => { + Some(get_index_type(return_type)) + }, + _ => None, }; Some(IndexItemFunctionType { inputs: inputs, output: output }) From aefe75095adf8a5c6714a5c89b3899d4f9570514 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 16:47:40 +0100 Subject: [PATCH 12/19] Add bounds for return types as well --- src/librustdoc/clean/inline.rs | 3 ++- src/librustdoc/clean/mod.rs | 41 ++++++++++++++++++++++++------ src/librustdoc/html/render.rs | 27 +++++++++----------- src/librustdoc/html/static/main.js | 18 ++++++++----- 4 files changed, 59 insertions(+), 30 deletions(-) diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 2b45831f224fb..af724a659cde4 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -214,7 +214,7 @@ fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function { let predicates = cx.tcx.predicates_of(did); let generics = (cx.tcx.generics_of(did), &predicates).clean(cx); let decl = (did, sig).clean(cx); - let all_types = clean::get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx); clean::Function { decl, generics, @@ -225,6 +225,7 @@ fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function { asyncness: hir::IsAsync::NotAsync, }, all_types, + ret_types, } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index f92f129d803f9..415d031840743 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1751,7 +1751,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, } // The point is to replace bounds with types. -pub fn get_real_types( +fn get_real_types( generics: &Generics, arg: &Type, cx: &DocContext<'_, '_, '_>, @@ -1822,7 +1822,7 @@ pub fn get_all_types( generics: &Generics, decl: &FnDecl, cx: &DocContext<'_, '_, '_>, -) -> Vec { +) -> (Vec, Vec) { let mut all_types = Vec::new(); for arg in decl.inputs.values.iter() { if arg.type_.is_self_type() { @@ -1837,7 +1837,23 @@ pub fn get_all_types( // FIXME: use a HashSet instead? all_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).unwrap()); all_types.dedup(); - all_types + + let mut ret_types = match decl.output { + FunctionRetTy::Return(ref return_type) => { + let mut ret = Vec::new(); + if let Some(mut args) = get_real_types(generics, &return_type, cx) { + ret.append(&mut args); + } else { + ret.push(return_type.clone()); + } + ret + } + _ => Vec::new(), + }; + // FIXME: use a HashSet instead? + ret_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).unwrap()); + ret_types.dedup(); + (all_types, ret_types) } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -1847,6 +1863,7 @@ pub struct Method { pub header: hir::FnHeader, pub defaultness: Option, pub all_types: Vec, + pub ret_types: Vec, } impl<'a> Clean for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, @@ -1855,13 +1872,14 @@ impl<'a> Clean for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, let (generics, decl) = enter_impl_trait(cx, || { (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)) }); - let all_types = get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = get_all_types(&generics, &decl, cx); Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, + ret_types, } } } @@ -1872,6 +1890,7 @@ pub struct TyMethod { pub decl: FnDecl, pub generics: Generics, pub all_types: Vec, + pub ret_types: Vec, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -1880,6 +1899,7 @@ pub struct Function { pub generics: Generics, pub header: hir::FnHeader, pub all_types: Vec, + pub ret_types: Vec, } impl Clean for doctree::Function { @@ -1894,7 +1914,7 @@ impl Clean for doctree::Function { } else { hir::Constness::NotConst }; - let all_types = get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = get_all_types(&generics, &decl, cx); Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -1908,6 +1928,7 @@ impl Clean for doctree::Function { generics, header: hir::FnHeader { constness, ..self.header }, all_types, + ret_types, }), } } @@ -2177,12 +2198,13 @@ impl Clean for hir::TraitItem { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) }); - let all_types = get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = get_all_types(&generics, &decl, cx); TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, + ret_types, }) } hir::TraitItemKind::Type(ref bounds, ref default) => { @@ -2280,7 +2302,7 @@ impl<'tcx> Clean for ty::AssociatedItem { ty::ImplContainer(_) => true, ty::TraitContainer(_) => self.defaultness.has_value() }; - let all_types = get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = get_all_types(&generics, &decl, cx); if provided { let constness = if cx.tcx.is_min_const_fn(self.def_id) { hir::Constness::Const @@ -2298,6 +2320,7 @@ impl<'tcx> Clean for ty::AssociatedItem { }, defaultness: Some(self.defaultness), all_types, + ret_types, }) } else { TyMethodItem(TyMethod { @@ -2310,6 +2333,7 @@ impl<'tcx> Clean for ty::AssociatedItem { asyncness: hir::IsAsync::NotAsync, }, all_types, + ret_types, }) } } @@ -3976,7 +4000,7 @@ impl Clean for hir::ForeignItem { let (generics, decl) = enter_impl_trait(cx, || { (generics.clean(cx), (&**decl, &names[..]).clean(cx)) }); - let all_types = get_all_types(&generics, &decl, cx); + let (all_types, ret_types) = get_all_types(&generics, &decl, cx); ForeignFunctionItem(Function { decl, generics, @@ -3987,6 +4011,7 @@ impl Clean for hir::ForeignItem { asyncness: hir::IsAsync::NotAsync, }, all_types, + ret_types, }) } hir::ForeignItemKind::Static(ref ty, mutbl) => { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 5c2051710f869..ec93bbbf9be69 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -446,7 +446,7 @@ impl ToJson for Type { } Json::Array(data) } - None => Json::Null + None => Json::Null, } } } @@ -455,7 +455,7 @@ impl ToJson for Type { #[derive(Debug)] struct IndexItemFunctionType { inputs: Vec, - output: Option, + output: Vec, } impl ToJson for IndexItemFunctionType { @@ -466,8 +466,8 @@ impl ToJson for IndexItemFunctionType { } else { let mut data = Vec::with_capacity(2); data.push(self.inputs.to_json()); - if let Some(ref output) = self.output { - data.push(output.to_json()); + if !self.output.is_empty() { + data.push(self.output.to_json()); } Json::Array(data) } @@ -5025,24 +5025,21 @@ fn make_item_keywords(it: &clean::Item) -> String { } fn get_index_search_type(item: &clean::Item) -> Option { - let (decl, all_types) = match item.inner { - clean::FunctionItem(ref f) => (&f.decl, &f.all_types), - clean::MethodItem(ref m) => (&m.decl, &m.all_types), - clean::TyMethodItem(ref m) => (&m.decl, &m.all_types), + let (all_types, ret_types) = match item.inner { + clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types), + clean::MethodItem(ref m) => (&m.all_types, &m.ret_types), + clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types), _ => return None, }; let inputs = all_types.iter().map(|arg| { get_index_type(&arg) }).collect(); - let output = match decl.output { - clean::FunctionRetTy::Return(ref return_type) => { - Some(get_index_type(return_type)) - }, - _ => None, - }; + let output = ret_types.iter().map(|arg| { + get_index_type(&arg) + }).collect(); - Some(IndexItemFunctionType { inputs: inputs, output: output }) + Some(IndexItemFunctionType { inputs, output }) } fn get_index_type(clean_type: &clean::Type) -> Type { diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 588d82748b390..c9880f4c41177 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -755,13 +755,19 @@ if (!DOMTokenList.prototype.remove) { var lev_distance = MAX_LEV_DISTANCE + 1; if (obj && obj.type && obj.type.length > OUTPUT_DATA) { - var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch); - if (literalSearch === true && tmp === true) { - return true; + var ret = obj.type[OUTPUT_DATA]; + if (!obj.type[OUTPUT_DATA].length) { + ret = [ret]; } - lev_distance = Math.min(tmp, lev_distance); - if (lev_distance === 0) { - return 0; + for (var x = 0; x < ret.length; ++x) { + var tmp = checkType(ret[x], val, literalSearch); + if (literalSearch === true && tmp === true) { + return true; + } + lev_distance = Math.min(tmp, lev_distance); + if (lev_distance === 0) { + return 0; + } } } return literalSearch === true ? false : lev_distance; From 6bce61cd4b20ae0661a1a7bd656cebc999b5a2ee Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 22:47:43 +0100 Subject: [PATCH 13/19] Fix invalid returned types generation --- src/librustdoc/clean/mod.rs | 80 +++++++++++++++--------------- src/librustdoc/html/render.rs | 26 +++++++--- src/librustdoc/html/static/main.js | 3 ++ 3 files changed, 63 insertions(+), 46 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 415d031840743..c41d02fbfbbc2 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1755,55 +1755,59 @@ fn get_real_types( generics: &Generics, arg: &Type, cx: &DocContext<'_, '_, '_>, -) -> Option> { +) -> Vec { + let arg_s = arg.to_string(); let mut res = Vec::new(); - if let Some(where_pred) = generics.where_predicates.iter().find(|g| { - match g { - &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), - _ => false, - } - }) { - let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]); - for bound in bounds.iter() { - match *bound { - GenericBound::TraitBound(ref poly_trait, _) => { - for x in poly_trait.generic_params.iter() { - if !x.is_type() { - continue - } - if let Some(ty) = x.get_type(cx) { - if let Some(mut adds) = get_real_types(generics, &ty, cx) { - res.append(&mut adds); - } else if !ty.is_full_generic() { - res.push(ty); + if arg.is_full_generic() { + if let Some(where_pred) = generics.where_predicates.iter().find(|g| { + match g { + &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), + _ => false, + } + }) { + let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]); + for bound in bounds.iter() { + match *bound { + GenericBound::TraitBound(ref poly_trait, _) => { + for x in poly_trait.generic_params.iter() { + if !x.is_type() { + continue + } + if let Some(ty) = x.get_type(cx) { + let mut adds = get_real_types(generics, &ty, cx); + if !adds.is_empty() { + res.append(&mut adds); + } else if !ty.is_full_generic() { + res.push(ty); + } } } } + _ => {} } - _ => {} } } - } else { - let arg_s = arg.to_string(); if let Some(bound) = generics.params.iter().find(|g| { g.is_type() && g.name == arg_s }) { for bound in bound.get_bounds().unwrap_or_else(|| &[]) { if let Some(ty) = bound.get_trait_type() { - if let Some(mut adds) = get_real_types(generics, &ty, cx) { + let mut adds = get_real_types(generics, &ty, cx); + if !adds.is_empty() { res.append(&mut adds); - } else { - if !ty.is_full_generic() { - res.push(ty.clone()); - } + } else if !ty.is_full_generic() { + res.push(ty.clone()); } } } - } else if let Some(gens) = arg.generics() { - res.push(arg.clone()); + } + } else { + res.push(arg.clone()); + if let Some(gens) = arg.generics() { for gen in gens.iter() { if gen.is_full_generic() { - if let Some(mut adds) = get_real_types(generics, gen, cx) { + let mut adds = get_real_types(generics, gen, cx); + if !adds.is_empty() { res.append(&mut adds); } } else { @@ -1812,10 +1816,7 @@ fn get_real_types( } } } - if res.is_empty() && !arg.is_full_generic() { - res.push(arg.clone()); - } - Some(res) + res } pub fn get_all_types( @@ -1828,7 +1829,8 @@ pub fn get_all_types( if arg.type_.is_self_type() { continue; } - if let Some(mut args) = get_real_types(generics, &arg.type_, cx) { + let mut args = get_real_types(generics, &arg.type_, cx); + if !args.is_empty() { all_types.append(&mut args); } else { all_types.push(arg.type_.clone()); @@ -1840,10 +1842,8 @@ pub fn get_all_types( let mut ret_types = match decl.output { FunctionRetTy::Return(ref return_type) => { - let mut ret = Vec::new(); - if let Some(mut args) = get_real_types(generics, &return_type, cx) { - ret.append(&mut args); - } else { + let mut ret = get_real_types(generics, &return_type, cx); + if ret.is_empty() { ret.push(return_type.clone()); } ret diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ec93bbbf9be69..930f3fd3c5c82 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -455,19 +455,27 @@ impl ToJson for Type { #[derive(Debug)] struct IndexItemFunctionType { inputs: Vec, - output: Vec, + output: Option>, } impl ToJson for IndexItemFunctionType { fn to_json(&self) -> Json { // If we couldn't figure out a type, just write `null`. - if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) { + let mut iter = self.inputs.iter(); + if match self.output { + Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()), + None => iter.any(|ref i| i.name.is_none()), + } { Json::Null } else { let mut data = Vec::with_capacity(2); data.push(self.inputs.to_json()); - if !self.output.is_empty() { - data.push(self.output.to_json()); + if let Some(ref output) = self.output { + if output.len() > 1 { + data.push(output.to_json()); + } else { + data.push(output[0].to_json()); + } } Json::Array(data) } @@ -5034,11 +5042,17 @@ fn get_index_search_type(item: &clean::Item) -> Option { let inputs = all_types.iter().map(|arg| { get_index_type(&arg) - }).collect(); + }).filter(|a| a.name.is_some()).collect(); let output = ret_types.iter().map(|arg| { get_index_type(&arg) - }).collect(); + }).filter(|a| a.name.is_some()).collect::>(); + let output = if output.is_empty() { + None + } else { + Some(output) + }; + println!("===> {:?}", output); Some(IndexItemFunctionType { inputs, output }) } diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index c9880f4c41177..94247b2fa4567 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -756,6 +756,9 @@ if (!DOMTokenList.prototype.remove) { if (obj && obj.type && obj.type.length > OUTPUT_DATA) { var ret = obj.type[OUTPUT_DATA]; + //if (obj.name === "xo") { + // debugger; + //} if (!obj.type[OUTPUT_DATA].length) { ret = [ret]; } From dc628b4f6728a858b9a2715e2d2046b4758bb6e4 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 7 Mar 2019 23:32:42 +0100 Subject: [PATCH 14/19] cleanup --- src/librustc_typeck/collect.rs | 8 ++++++-- src/librustdoc/clean/mod.rs | 28 ++++++++++++++++++---------- src/librustdoc/html/render.rs | 1 - 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index e723ee1d10adc..095c92ff10d86 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1133,6 +1133,10 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { checked_type_of(tcx, def_id, true).unwrap() } +/// Same as [`type_of`] but returns [`Option`] instead of failing. +/// +/// If you want to fail anyway, you can set the `fail` parameter to true, but in this case, +/// you'd better just call [`type_of`] directly. pub fn checked_type_of<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, @@ -1382,14 +1386,14 @@ pub fn checked_type_of<'a, 'tcx>( for param in &generics.params { if let ty::GenericParamDefKind::Const = param.kind { if param_index == arg_index { - return tcx.type_of(param.def_id); + return Some(tcx.type_of(param.def_id)); } param_index += 1; } } // This is no generic parameter associated with the arg. This is // probably from an extra arg where one is not needed. - return tcx.types.err; + return Some(tcx.types.err); } Def::Err => tcx.types.err, x => { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index c41d02fbfbbc2..e7277308cd994 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1474,7 +1474,7 @@ impl GenericParamDefKind { } } - pub fn get_type(&self, cx: &DocContext<'_, '_, '_>) -> Option { + pub fn get_type(&self, cx: &DocContext<'_>) -> Option { match *self { GenericParamDefKind::Type { did, .. } => { rustc_typeck::checked_type_of(cx.tcx, did, false).map(|t| t.clean(cx)) @@ -1505,7 +1505,7 @@ impl GenericParamDef { self.kind.is_type() } - pub fn get_type(&self, cx: &DocContext<'_, '_, '_>) -> Option { + pub fn get_type(&self, cx: &DocContext<'_>) -> Option { self.kind.get_type(cx) } @@ -1750,12 +1750,16 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, } } -// The point is to replace bounds with types. +/// The point of this function is to replace bounds with types. +/// +/// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option` will return +/// `[Display, Option]` (we just returns the list of the types, we don't care about the +/// wrapped types in here). fn get_real_types( generics: &Generics, arg: &Type, - cx: &DocContext<'_, '_, '_>, -) -> Vec { + cx: &DocContext<'_>, +) -> FxHashSet { let arg_s = arg.to_string(); let mut res = Vec::new(); if arg.is_full_generic() { @@ -1776,7 +1780,7 @@ fn get_real_types( if let Some(ty) = x.get_type(cx) { let mut adds = get_real_types(generics, &ty, cx); if !adds.is_empty() { - res.append(&mut adds); + res.extend(adds); } else if !ty.is_full_generic() { res.push(ty); } @@ -1794,7 +1798,7 @@ fn get_real_types( if let Some(ty) = bound.get_trait_type() { let mut adds = get_real_types(generics, &ty, cx); if !adds.is_empty() { - res.append(&mut adds); + res.extend(adds); } else if !ty.is_full_generic() { res.push(ty.clone()); } @@ -1808,7 +1812,7 @@ fn get_real_types( if gen.is_full_generic() { let mut adds = get_real_types(generics, gen, cx); if !adds.is_empty() { - res.append(&mut adds); + res.extend(adds); } } else { res.push(gen.clone()); @@ -1819,10 +1823,14 @@ fn get_real_types( res } +/// Return the full list of types when bounds have been resolved. +/// +/// i.e. `fn foo>(x: u32, y: B)` will return +/// `[u32, Display, Option]`. pub fn get_all_types( generics: &Generics, decl: &FnDecl, - cx: &DocContext<'_, '_, '_>, + cx: &DocContext<'_>, ) -> (Vec, Vec) { let mut all_types = Vec::new(); for arg in decl.inputs.values.iter() { @@ -1831,7 +1839,7 @@ pub fn get_all_types( } let mut args = get_real_types(generics, &arg.type_, cx); if !args.is_empty() { - all_types.append(&mut args); + all_types.extend(args); } else { all_types.push(arg.type_.clone()); } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 930f3fd3c5c82..b0f0a26bd27ba 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -5052,7 +5052,6 @@ fn get_index_search_type(item: &clean::Item) -> Option { Some(output) }; - println!("===> {:?}", output); Some(IndexItemFunctionType { inputs, output }) } From befe9cac910f6cf1f98b9c145bcad80be659106a Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 8 Mar 2019 00:16:48 +0100 Subject: [PATCH 15/19] Add test --- src/librustdoc/clean/mod.rs | 36 +++++++++++++----------------- src/librustdoc/html/static/main.js | 16 ++++++++----- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e7277308cd994..fccb49a86cbbe 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1761,7 +1761,7 @@ fn get_real_types( cx: &DocContext<'_>, ) -> FxHashSet { let arg_s = arg.to_string(); - let mut res = Vec::new(); + let mut res = FxHashSet::default(); if arg.is_full_generic() { if let Some(where_pred) = generics.where_predicates.iter().find(|g| { match g { @@ -1778,11 +1778,11 @@ fn get_real_types( continue } if let Some(ty) = x.get_type(cx) { - let mut adds = get_real_types(generics, &ty, cx); + let adds = get_real_types(generics, &ty, cx); if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { - res.push(ty); + res.insert(ty); } } } @@ -1796,26 +1796,26 @@ fn get_real_types( }) { for bound in bound.get_bounds().unwrap_or_else(|| &[]) { if let Some(ty) = bound.get_trait_type() { - let mut adds = get_real_types(generics, &ty, cx); + let adds = get_real_types(generics, &ty, cx); if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { - res.push(ty.clone()); + res.insert(ty.clone()); } } } } } else { - res.push(arg.clone()); + res.insert(arg.clone()); if let Some(gens) = arg.generics() { for gen in gens.iter() { if gen.is_full_generic() { - let mut adds = get_real_types(generics, gen, cx); + let adds = get_real_types(generics, gen, cx); if !adds.is_empty() { res.extend(adds); } } else { - res.push(gen.clone()); + res.insert(gen.clone()); } } } @@ -1832,36 +1832,30 @@ pub fn get_all_types( decl: &FnDecl, cx: &DocContext<'_>, ) -> (Vec, Vec) { - let mut all_types = Vec::new(); + let mut all_types = FxHashSet::default(); for arg in decl.inputs.values.iter() { if arg.type_.is_self_type() { continue; } - let mut args = get_real_types(generics, &arg.type_, cx); + let args = get_real_types(generics, &arg.type_, cx); if !args.is_empty() { all_types.extend(args); } else { - all_types.push(arg.type_.clone()); + all_types.insert(arg.type_.clone()); } } - // FIXME: use a HashSet instead? - all_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).unwrap()); - all_types.dedup(); - let mut ret_types = match decl.output { + let ret_types = match decl.output { FunctionRetTy::Return(ref return_type) => { let mut ret = get_real_types(generics, &return_type, cx); if ret.is_empty() { - ret.push(return_type.clone()); + ret.insert(return_type.clone()); } - ret + ret.into_iter().collect() } _ => Vec::new(), }; - // FIXME: use a HashSet instead? - ret_types.sort_unstable_by(|a, b| a.to_string().partial_cmp(&b.to_string()).unwrap()); - ret_types.dedup(); - (all_types, ret_types) + (all_types.into_iter().collect(), ret_types) } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 94247b2fa4567..aad7eb627bfe2 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -756,16 +756,20 @@ if (!DOMTokenList.prototype.remove) { if (obj && obj.type && obj.type.length > OUTPUT_DATA) { var ret = obj.type[OUTPUT_DATA]; - //if (obj.name === "xo") { - // debugger; - //} if (!obj.type[OUTPUT_DATA].length) { ret = [ret]; } for (var x = 0; x < ret.length; ++x) { - var tmp = checkType(ret[x], val, literalSearch); - if (literalSearch === true && tmp === true) { - return true; + var r = ret[x]; + if (typeof r === "string") { + r = [r]; + } + var tmp = checkType(r, val, literalSearch); + if (literalSearch === true) { + if (tmp === true) { + return true; + } + continue; } lev_distance = Math.min(tmp, lev_distance); if (lev_distance === 0) { From 6c479c3d02e134dbc8812582c3241fa8747c35d7 Mon Sep 17 00:00:00 2001 From: Christian Date: Mon, 25 Mar 2019 22:21:05 +0100 Subject: [PATCH 16/19] Formatting changes, including better wrapping and creating short summary lines. --- src/libcore/convert.rs | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 9f72d02d865d3..cee4fc6f49a71 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -1,6 +1,6 @@ +//! Traits for conversions between types. //! //! The traits in this module provide a way to convert from one type to another type. -//! //! Each trait serves a different purpose: //! //! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions @@ -99,12 +99,14 @@ use fmt; pub const fn identity(x: T) -> T { x } /// Used to do a cheap reference-to-reference conversion. +/// /// This trait is similar to [`AsMut`] which is used for converting between mutable references. /// If you need to do a costly conversion it is better to implement [`From`] with type /// `&T` or write a custom function. /// /// /// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`]: +/// /// - Use `AsRef` when the goal is to simply convert into a reference /// - Use `Borrow` when the goal is related to writing code that is agnostic to /// the type of borrow and whether it is a reference or value @@ -127,6 +129,7 @@ pub const fn identity(x: T) -> T { x } /// /// By using trait bounds we can accept arguments of different types as long as they can be /// converted a the specified type `T`. +/// /// For example: By creating a generic function that takes an `AsRef` we express that we /// want to accept all references that can be converted to &str as an argument. /// Since both [`String`] and `&str` implement `AsRef` we can accept both as input argument. @@ -153,6 +156,7 @@ pub trait AsRef { } /// Used to do a cheap mutable-to-mutable reference conversion. +/// /// This trait is similar to [`AsRef`] but used for converting between mutable /// references. If you need to do a costly conversion it is better to /// implement [`From`] with type `&mut T` or write a custom function. @@ -199,9 +203,9 @@ pub trait AsMut { /// /// One should only implement [`Into`] if a conversion to a type outside the current crate is /// required. Otherwise one should always prefer implementing [`From`] over [`Into`] because -/// implementing [`From`] automatically provides one with a implementation of [`Into`] -/// thanks to the blanket implementation in the standard library. -/// [`From`] cannot do these type of conversions because of Rust's orphaning rules. +/// implementing [`From`] automatically provides one with a implementation of [`Into`] thanks to +/// the blanket implementation in the standard library. [`From`] cannot do these type of +/// conversions because of Rust's orphaning rules. /// /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. /// @@ -211,6 +215,7 @@ pub trait AsMut { /// - [`Into`]` is reflexive, which means that `Into for T` is implemented /// /// # Implementing `Into` for conversions to external types +/// /// If the destination type is not part of the current crate /// then you can't implement [`From`] directly. /// For example, take this code: @@ -239,6 +244,7 @@ pub trait AsMut { /// It is important to understand that `Into` does not provide a [`From`] implementation /// (as [`From`] does with `Into`). Therefore, you should always try to implement [`From`] /// and then fall back to `Into` if [`From`] can't be implemented. +/// /// Prefer using `Into` over [`From`] when specifying trait bounds on a generic function /// to ensure that types that only implement `Into` can be used as well. /// @@ -280,6 +286,7 @@ pub trait Into: Sized { /// One should always prefer implementing [`From`] over [`Into`] /// because implementing [`From`] automatically provides one with a implementation of [`Into`] /// thanks to the blanket implementation in the standard library. +/// /// Only implement [`Into`] if a conversion to a type outside the current crate is required. /// [`From`] cannot do these type of conversions because of Rust's orphaning rules. /// See [`Into`] for more details. @@ -287,12 +294,11 @@ pub trait Into: Sized { /// Prefer using [`Into`] over using [`From`] when specifying trait bounds on a generic function. /// This way, types that directly implement [`Into`] can be used as arguments as well. /// -/// The [`From`] is also very useful when performing error handling. -/// When constructing a function that is capable of failing, the return type -/// will generally be of the form `Result`. +/// The [`From`] is also very useful when performing error handling. When constructing a function +/// that is capable of failing, the return type will generally be of the form `Result`. /// The `From` trait simplifies error handling by allowing a function to return a single error type -/// that encapsulate multiple error types. See the "Examples" section -/// and [the book][book] for more details. +/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more +/// details. /// /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. /// @@ -313,13 +319,12 @@ pub trait Into: Sized { /// assert_eq!(string, other_string); /// ``` /// -/// While performing error handling it is often useful to implement `From` -/// for your own error type. By converting underlying error types to our own custom error type -/// that encapsulates the underlying error type, we can return a single error type -/// without losing information on the underlying cause. The '?' operator automatically converts -/// the underlying error type to our custom error type by calling `Into::into` -/// which is automatically provided when implementing `From`. -/// The compiler then infers which implementation of `Into` should be used. +/// While performing error handling it is often useful to implement `From` for your own error type. +/// By converting underlying error types to our own custom error type that encapsulates the +/// underlying error type, we can return a single error type without losing information on the +/// underlying cause. The '?' operator automatically converts the underlying error type to our +/// custom error type by calling `Into::into` which is automatically provided when +/// implementing `From`. The compiler then infers which implementation of `Into` should be used. /// /// ``` /// use std::fs; From fd42918a41c0093ac8db6bcf757f906c6adeaffa Mon Sep 17 00:00:00 2001 From: Chris Gregory Date: Mon, 25 Mar 2019 18:04:42 -0400 Subject: [PATCH 17/19] Link to PhantomData in NonNull documentation --- src/libcore/ptr.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index a9a029d606d6f..daae71d36e140 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -2869,10 +2869,10 @@ impl<'a, T: ?Sized> From> for Unique { /// However the pointer may still dangle if it isn't dereferenced. /// /// Unlike `*mut T`, `NonNull` is covariant over `T`. If this is incorrect -/// for your use case, you should include some PhantomData in your type to +/// for your use case, you should include some [`PhantomData`] in your type to /// provide invariance, such as `PhantomData>` or `PhantomData<&'a mut T>`. /// Usually this won't be necessary; covariance is correct for most safe abstractions, -/// such as Box, Rc, Arc, Vec, and LinkedList. This is the case because they +/// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they /// provide a public API that follows the normal shared XOR mutable rules of Rust. /// /// Notice that `NonNull` has a `From` instance for `&T`. However, this does @@ -2883,6 +2883,7 @@ impl<'a, T: ?Sized> From> for Unique { /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr` /// is never used for mutation. /// +/// [`PhantomData`]: ../marker/struct.PhantomData.html /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html #[stable(feature = "nonnull", since = "1.25.0")] #[repr(transparent)] From 868833f9a6d739f6bcb7ab9772f3a79c2c750559 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 26 Mar 2019 00:30:33 +0100 Subject: [PATCH 18/19] Fix code block display in portability element in dark theme --- src/librustdoc/html/static/themes/dark.css | 4 ++++ src/librustdoc/html/static/themes/light.css | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/librustdoc/html/static/themes/dark.css b/src/librustdoc/html/static/themes/dark.css index e756ab60ccc6d..e3bb41ae672f4 100644 --- a/src/librustdoc/html/static/themes/dark.css +++ b/src/librustdoc/html/static/themes/dark.css @@ -189,6 +189,10 @@ a.test-arrow { .stab.deprecated { background: #F3DFFF; border-color: #7F0087; color: #2f2f2f; } .stab.portability { background: #C4ECFF; border-color: #7BA5DB; color: #2f2f2f; } +.stab > code { + color: #ddd; +} + #help > div { background: #4d4d4d; border-color: #bfbfbf; diff --git a/src/librustdoc/html/static/themes/light.css b/src/librustdoc/html/static/themes/light.css index a294f6f2ff123..dd4d028c6c9be 100644 --- a/src/librustdoc/html/static/themes/light.css +++ b/src/librustdoc/html/static/themes/light.css @@ -190,6 +190,10 @@ a.test-arrow { .stab.deprecated { background: #F3DFFF; border-color: #7F0087; } .stab.portability { background: #C4ECFF; border-color: #7BA5DB; } +.stab > code { + color: #000; +} + #help > div { background: #e9e9e9; border-color: #bfbfbf; From 8a9c6203404404f0f7699d6a5da64c613b2b5a8b Mon Sep 17 00:00:00 2001 From: Philipp Hansch Date: Tue, 26 Mar 2019 07:47:38 +0100 Subject: [PATCH 19/19] Improve some compiletest documentation This adds some missing documentation for rustfix related things and adds a test for the `is_test` function. --- src/tools/compiletest/src/common.rs | 3 +++ src/tools/compiletest/src/header.rs | 3 +++ src/tools/compiletest/src/json.rs | 6 +++--- src/tools/compiletest/src/main.rs | 11 +++++++++++ 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index 80b8a8b728bb2..c1920dde5b1fe 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -117,6 +117,7 @@ impl CompareMode { } } +/// Configuration for compiletest #[derive(Clone)] pub struct Config { /// `true` to to overwrite stderr/stdout files instead of complaining about changes in output. @@ -254,6 +255,8 @@ pub struct Config { pub linker: Option, pub llvm_components: String, pub llvm_cxxflags: String, + + /// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests pub nodejs: Option, } diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 7bf56707478e3..d735d3351e666 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -333,7 +333,10 @@ pub struct TestProps { pub normalize_stdout: Vec<(String, String)>, pub normalize_stderr: Vec<(String, String)>, pub failure_status: i32, + // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the + // resulting Rust code. pub run_rustfix: bool, + // If true, `rustfix` will only apply `MachineApplicable` suggestions. pub rustfix_only_machine_applicable: bool, pub assembly_output: Option, } diff --git a/src/tools/compiletest/src/json.rs b/src/tools/compiletest/src/json.rs index 12aae303f29aa..15d449260efa0 100644 --- a/src/tools/compiletest/src/json.rs +++ b/src/tools/compiletest/src/json.rs @@ -1,12 +1,12 @@ +//! These structs are a subset of the ones found in `syntax::json`. +//! They are only used for deserialization of JSON output provided by libtest. + use crate::errors::{Error, ErrorKind}; use crate::runtest::ProcRes; use serde_json; use std::path::Path; use std::str::FromStr; -// These structs are a subset of the ones found in -// `syntax::json`. - #[derive(Deserialize)] struct Diagnostic { message: String, diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 86cdadade108f..d91710dda5239 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -598,6 +598,8 @@ fn collect_tests_from_dir( Ok(()) } + +/// Returns true if `file_name` looks like a proper test file name. pub fn is_test(file_name: &OsString) -> bool { let file_name = file_name.to_str().unwrap(); @@ -1048,3 +1050,12 @@ fn test_extract_gdb_version() { 7012050: "GNU gdb (GDB) 7.12.50.20161027-git", } } + +#[test] +fn is_test_test() { + assert_eq!(true, is_test(&OsString::from("a_test.rs"))); + assert_eq!(false, is_test(&OsString::from(".a_test.rs"))); + assert_eq!(false, is_test(&OsString::from("a_cat.gif"))); + assert_eq!(false, is_test(&OsString::from("#a_dog_gif"))); + assert_eq!(false, is_test(&OsString::from("~a_temp_file"))); +}