Auto merge of #59447 - GuillaumeGomez:rollup, r=GuillaumeGomez
Rollup of 7 pull requests Successful merges: - #59004 ([rustdoc] Improve "in parameters" search and search more generally) - #59026 (Fix moving text in search tabs headers) - #59197 (Exclude old book redirect stubs from search engines) - #59330 (Improve the documentation for std::convert (From, Into, AsRef and AsMut)) - #59424 (Fix code block display in portability element in dark theme) - #59427 (Link to PhantomData in NonNull documentation) - #59432 (Improve some compiletest documentation) Failed merges: r? @ghost
This commit is contained in:
commit
267fb90b55
17 changed files with 433 additions and 126 deletions
|
@ -331,7 +331,7 @@ fn invoke_rustdoc(
|
||||||
|
|
||||||
let path = builder.src.join("src/doc").join(markdown);
|
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 footer = builder.src.join("src/doc/footer.inc");
|
||||||
let version_info = out.join("version_info.html");
|
let version_info = out.join("version_info.html");
|
||||||
|
|
||||||
|
@ -341,7 +341,7 @@ fn invoke_rustdoc(
|
||||||
|
|
||||||
cmd.arg("--html-after-content").arg(&footer)
|
cmd.arg("--html-after-content").arg(&footer)
|
||||||
.arg("--html-before-content").arg(&version_info)
|
.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-no-toc")
|
||||||
.arg("--markdown-playground-url")
|
.arg("--markdown-playground-url")
|
||||||
.arg("https://play.rust-lang.org/")
|
.arg("https://play.rust-lang.org/")
|
||||||
|
|
2
src/doc/redirect.inc
Normal file
2
src/doc/redirect.inc
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
<meta name="robots" content="noindex,follow">
|
||||||
|
<link rel="shortcut icon" href="https://www.rust-lang.org/favicon.ico">
|
|
@ -1,26 +1,25 @@
|
||||||
//! Traits for conversions between types.
|
//! Traits for conversions between types.
|
||||||
//!
|
//!
|
||||||
//! The traits in this module provide a general way to talk about conversions
|
//! The traits in this module provide a way to convert from one type to another type.
|
||||||
//! from one type to another. They follow the standard Rust conventions of
|
//! Each trait serves a different purpose:
|
||||||
//! `as`/`into`/`from`.
|
|
||||||
//!
|
//!
|
||||||
//! Like many traits, these are often used as bounds for generic functions, to
|
//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions
|
||||||
//! support arguments of multiple types.
|
//! - 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.
|
||||||
//!
|
//!
|
||||||
//! - Implement the `As*` traits for reference-to-reference conversions
|
//! The traits in this module are often used as trait bounds for generic functions such that to
|
||||||
//! - Implement the [`Into`] trait when you want to consume the value in the conversion
|
//! arguments of multiple types are supported. See the documentation of each trait for examples.
|
||||||
//! - 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
|
|
||||||
//!
|
//!
|
||||||
//! As a library author, you should prefer implementing [`From<T>`][`From`] or
|
//! As a library author, you should always prefer implementing [`From<T>`][`From`] or
|
||||||
//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
|
//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
|
||||||
//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
|
//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
|
||||||
//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
|
//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
|
||||||
//! blanket implementation in the standard library. However, there are some cases
|
//! blanket implementation in the standard library. Only implement [`Into`] or [`TryInto`]
|
||||||
//! where this is not possible, such as creating conversions into a type defined
|
//! when a conversion to a type outside the current crate is required.
|
||||||
//! outside your library, so implementing [`Into`] instead of [`From`] is
|
|
||||||
//! sometimes necessary.
|
|
||||||
//!
|
//!
|
||||||
//! # Generic Implementations
|
//! # Generic Implementations
|
||||||
//!
|
//!
|
||||||
|
@ -99,20 +98,14 @@ use fmt;
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn identity<T>(x: T) -> T { x }
|
pub const fn identity<T>(x: T) -> T { x }
|
||||||
|
|
||||||
/// A cheap reference-to-reference conversion. Used to convert a value to a
|
/// Used to do a cheap reference-to-reference conversion.
|
||||||
/// reference value within generic code.
|
|
||||||
///
|
///
|
||||||
/// `AsRef` is very similar to, but serves a slightly different purpose than,
|
/// This trait is similar to [`AsMut`] which is used for converting between mutable references.
|
||||||
/// [`Borrow`].
|
/// 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 `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
|
/// - Use `Borrow` when the goal is related to writing code that is agnostic to
|
||||||
|
@ -120,7 +113,7 @@ pub const fn identity<T>(x: T) -> T { x }
|
||||||
///
|
///
|
||||||
/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
|
/// [`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<T>`] or a [`Result<T, E>`].
|
/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
|
||||||
///
|
///
|
||||||
/// [`Option<T>`]: ../../std/option/enum.Option.html
|
/// [`Option<T>`]: ../../std/option/enum.Option.html
|
||||||
|
@ -134,7 +127,12 @@ pub const fn identity<T>(x: T) -> T { x }
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// Both [`String`] and `&str` implement `AsRef<str>`:
|
/// 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<str>` 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<str>` we can accept both as input argument.
|
||||||
///
|
///
|
||||||
/// [`String`]: ../../std/string/struct.String.html
|
/// [`String`]: ../../std/string/struct.String.html
|
||||||
///
|
///
|
||||||
|
@ -157,12 +155,13 @@ pub trait AsRef<T: ?Sized> {
|
||||||
fn as_ref(&self) -> &T;
|
fn as_ref(&self) -> &T;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A cheap, mutable reference-to-mutable reference conversion.
|
/// Used to do a cheap mutable-to-mutable reference conversion.
|
||||||
///
|
///
|
||||||
/// This trait is similar to `AsRef` but used for converting between mutable
|
/// This trait is similar to [`AsRef`] but used for converting between mutable
|
||||||
/// references.
|
/// 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<T>`] or a [`Result<T, E>`].
|
/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
|
||||||
///
|
///
|
||||||
/// [`Option<T>`]: ../../std/option/enum.Option.html
|
/// [`Option<T>`]: ../../std/option/enum.Option.html
|
||||||
|
@ -176,10 +175,11 @@ pub trait AsRef<T: ?Sized> {
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// [`Box<T>`] implements `AsMut<T>`:
|
/// 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<T>`] implements `AsMut<T>` we can
|
||||||
/// [`Box<T>`]: ../../std/boxed/struct.Box.html
|
/// write a function `add_one`that takes all arguments that can be converted to `&mut u64`.
|
||||||
///
|
/// Because [`Box<T>`] implements `AsMut<T>` `add_one` accepts arguments of type
|
||||||
|
/// `&mut Box<u64>` as well:
|
||||||
/// ```
|
/// ```
|
||||||
/// fn add_one<T: AsMut<u64>>(num: &mut T) {
|
/// fn add_one<T: AsMut<u64>>(num: &mut T) {
|
||||||
/// *num.as_mut() += 1;
|
/// *num.as_mut() += 1;
|
||||||
|
@ -189,7 +189,7 @@ pub trait AsRef<T: ?Sized> {
|
||||||
/// add_one(&mut boxed_num);
|
/// add_one(&mut boxed_num);
|
||||||
/// assert_eq!(*boxed_num, 1);
|
/// assert_eq!(*boxed_num, 1);
|
||||||
/// ```
|
/// ```
|
||||||
///
|
/// [`Box<T>`]: ../../std/boxed/struct.Box.html
|
||||||
///
|
///
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
pub trait AsMut<T: ?Sized> {
|
pub trait AsMut<T: ?Sized> {
|
||||||
|
@ -198,29 +198,27 @@ pub trait AsMut<T: ?Sized> {
|
||||||
fn as_mut(&mut self) -> &mut T;
|
fn as_mut(&mut self) -> &mut T;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A conversion that consumes `self`, which may or may not be expensive. The
|
/// A value-to-value conversion that consumes the input value. The
|
||||||
/// reciprocal of [`From`][From].
|
/// opposite of [`From`].
|
||||||
///
|
///
|
||||||
/// **Note: this trait must not fail**. If the conversion can fail, use
|
/// One should only implement [`Into`] if a conversion to a type outside the current crate is
|
||||||
/// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
|
/// required. Otherwise one should always prefer implementing [`From`] over [`Into`] because
|
||||||
/// [`Result<T, E>`].
|
/// 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
|
/// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
|
||||||
/// 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.
|
|
||||||
///
|
///
|
||||||
/// # Generic Implementations
|
/// # Generic Implementations
|
||||||
///
|
///
|
||||||
/// - [`From<T>`][From]` for U` implies `Into<U> for T`
|
/// - [`From<T>`]` for U` implies `Into<U> for T`
|
||||||
/// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
|
/// - [`Into`]` is reflexive, which means that `Into<T> for T` is implemented
|
||||||
///
|
///
|
||||||
/// # Implementing `Into`
|
/// # Implementing `Into` for conversions to external types
|
||||||
///
|
///
|
||||||
/// There is one exception to implementing `Into`, and it's kind of esoteric.
|
/// If the destination type is not part of the current crate
|
||||||
/// If the destination type is not part of the current crate, and it uses a
|
/// then you can't implement [`From`] directly.
|
||||||
/// generic variable, then you can't implement `From` directly. For example,
|
/// For example, take this code:
|
||||||
/// take this crate:
|
|
||||||
///
|
///
|
||||||
/// ```compile_fail
|
/// ```compile_fail
|
||||||
/// struct Wrapper<T>(Vec<T>);
|
/// struct Wrapper<T>(Vec<T>);
|
||||||
|
@ -230,8 +228,9 @@ pub trait AsMut<T: ?Sized> {
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
/// This will fail to compile because we cannot implement a trait for a type
|
||||||
/// To fix this, you can implement `Into` directly:
|
/// 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<T>(Vec<T>);
|
/// struct Wrapper<T>(Vec<T>);
|
||||||
|
@ -242,17 +241,22 @@ pub trait AsMut<T: ?Sized> {
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// This won't always allow the conversion: for example, `try!` and `?`
|
/// It is important to understand that `Into` does not provide a [`From`] implementation
|
||||||
/// always use `From`. However, in most cases, people use `Into` to do the
|
/// (as [`From`] does with `Into`). Therefore, you should always try to implement [`From`]
|
||||||
/// conversions, and this will allow that.
|
/// and then fall back to `Into` if [`From`] can't be implemented.
|
||||||
///
|
///
|
||||||
/// In almost all cases, you should try to implement `From`, then fall back
|
/// Prefer using `Into` over [`From`] when specifying trait bounds on a generic function
|
||||||
/// to `Into` if `From` can't be implemented.
|
/// to ensure that types that only implement `Into` can be used as well.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// [`String`] implements `Into<Vec<u8>>`:
|
/// [`String`] implements `Into<Vec<u8>>`:
|
||||||
///
|
///
|
||||||
|
/// 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<T>`.
|
||||||
|
/// For example: The function `is_hello` takes all arguments that can be converted into a
|
||||||
|
/// `Vec<u8>`.
|
||||||
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
|
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
|
||||||
/// let bytes = b"hello".to_vec();
|
/// let bytes = b"hello".to_vec();
|
||||||
|
@ -276,36 +280,38 @@ pub trait Into<T>: Sized {
|
||||||
fn into(self) -> T;
|
fn into(self) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Simple and safe type conversions in to `Self`. It is the reciprocal of
|
/// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
|
||||||
/// `Into`.
|
/// [`Into`].
|
||||||
///
|
///
|
||||||
/// This trait is useful when performing error handling as described by
|
/// One should always prefer implementing [`From`] over [`Into`]
|
||||||
/// [the book][book] and is closely related to the `?` operator.
|
/// because implementing [`From`] automatically provides one with a implementation of [`Into`]
|
||||||
|
/// thanks to the blanket implementation in the standard library.
|
||||||
///
|
///
|
||||||
/// When constructing a function that is capable of failing the return type
|
/// Only implement [`Into`] if a conversion to a type outside the current crate is required.
|
||||||
/// will generally be of the form `Result<T, E>`.
|
/// [`From`] cannot do these type of conversions because of Rust's orphaning rules.
|
||||||
|
/// See [`Into`] for more details.
|
||||||
///
|
///
|
||||||
/// The `From` trait allows for simplification of error handling by providing a
|
/// Prefer using [`Into`] over using [`From`] when specifying trait bounds on a generic function.
|
||||||
/// means of returning a single error type that encapsulates numerous possible
|
/// This way, types that directly implement [`Into`] can be used as arguments as well.
|
||||||
/// erroneous situations.
|
|
||||||
///
|
///
|
||||||
/// This trait is not limited to error handling, rather the general case for
|
/// The [`From`] is also very useful when performing error handling. When constructing a function
|
||||||
/// this trait would be in any type conversions to have an explicit definition
|
/// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
|
||||||
/// of how they are performed.
|
/// 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.
|
||||||
///
|
///
|
||||||
/// **Note: this trait must not fail**. If the conversion can fail, use
|
/// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`].
|
||||||
/// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
|
|
||||||
/// [`Result<T, E>`].
|
|
||||||
///
|
///
|
||||||
/// # Generic Implementations
|
/// # Generic Implementations
|
||||||
///
|
///
|
||||||
/// - `From<T> for U` implies [`Into<U>`]` for T`
|
/// - [`From<T>`]` for U` implies [`Into<U>`]` for T`
|
||||||
/// - [`from`] is reflexive, which means that `From<T> for T` is implemented
|
/// - [`From`] is reflexive, which means that `From<T> for T` is implemented
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// [`String`] implements `From<&str>`:
|
/// [`String`] implements `From<&str>`:
|
||||||
///
|
///
|
||||||
|
/// An explicit conversion from a &str to a String is done as follows:
|
||||||
/// ```
|
/// ```
|
||||||
/// let string = "hello".to_string();
|
/// let string = "hello".to_string();
|
||||||
/// let other_string = String::from("hello");
|
/// let other_string = String::from("hello");
|
||||||
|
@ -313,7 +319,12 @@ pub trait Into<T>: Sized {
|
||||||
/// assert_eq!(string, other_string);
|
/// 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<CliError>::into` which is automatically provided when
|
||||||
|
/// implementing `From`. The compiler then infers which implementation of `Into` should be used.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use std::fs;
|
/// use std::fs;
|
||||||
|
|
|
@ -2869,10 +2869,10 @@ impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
|
||||||
/// However the pointer may still dangle if it isn't dereferenced.
|
/// However the pointer may still dangle if it isn't dereferenced.
|
||||||
///
|
///
|
||||||
/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
|
/// Unlike `*mut T`, `NonNull<T>` 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<Cell<T>>` or `PhantomData<&'a mut T>`.
|
/// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
|
||||||
/// Usually this won't be necessary; covariance is correct for most safe abstractions,
|
/// 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.
|
/// provide a public API that follows the normal shared XOR mutable rules of Rust.
|
||||||
///
|
///
|
||||||
/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
|
/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
|
||||||
|
@ -2883,6 +2883,7 @@ impl<'a, T: ?Sized> From<NonNull<T>> for Unique<T> {
|
||||||
/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
|
/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
|
||||||
/// is never used for mutation.
|
/// is never used for mutation.
|
||||||
///
|
///
|
||||||
|
/// [`PhantomData`]: ../marker/struct.PhantomData.html
|
||||||
/// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
|
/// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
|
||||||
#[stable(feature = "nonnull", since = "1.25.0")]
|
#[stable(feature = "nonnull", since = "1.25.0")]
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
|
|
|
@ -1134,13 +1134,33 @@ 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> {
|
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,
|
||||||
|
fail: bool,
|
||||||
|
) -> Option<Ty<'tcx>> {
|
||||||
use rustc::hir::*;
|
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);
|
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 {
|
Node::TraitItem(item) => match item.node {
|
||||||
TraitItemKind::Method(..) => {
|
TraitItemKind::Method(..) => {
|
||||||
let substs = InternalSubsts::identity_for_item(tcx, def_id);
|
let substs = InternalSubsts::identity_for_item(tcx, def_id);
|
||||||
|
@ -1148,6 +1168,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::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
|
||||||
TraitItemKind::Type(_, None) => {
|
TraitItemKind::Type(_, None) => {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
span_bug!(item.span, "associated type missing default");
|
span_bug!(item.span, "associated type missing default");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -1229,6 +1252,9 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
|
||||||
| ItemKind::GlobalAsm(..)
|
| ItemKind::GlobalAsm(..)
|
||||||
| ItemKind::ExternCrate(..)
|
| ItemKind::ExternCrate(..)
|
||||||
| ItemKind::Use(..) => {
|
| ItemKind::Use(..) => {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
span_bug!(
|
span_bug!(
|
||||||
item.span,
|
item.span,
|
||||||
"compute_type_of_item: unexpected item type: {:?}",
|
"compute_type_of_item: unexpected item type: {:?}",
|
||||||
|
@ -1267,7 +1293,7 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
|
||||||
..
|
..
|
||||||
}) => {
|
}) => {
|
||||||
if gen.is_some() {
|
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 {
|
let substs = ty::ClosureSubsts {
|
||||||
|
@ -1345,6 +1371,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.
|
// Sanity check to make sure everything is as expected.
|
||||||
if !found_const {
|
if !found_const {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
bug!("no arg matching AnonConst in path")
|
bug!("no arg matching AnonConst in path")
|
||||||
}
|
}
|
||||||
match path.def {
|
match path.def {
|
||||||
|
@ -1360,24 +1389,37 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
|
||||||
for param in &generics.params {
|
for param in &generics.params {
|
||||||
if let ty::GenericParamDefKind::Const = param.kind {
|
if let ty::GenericParamDefKind::Const = param.kind {
|
||||||
if param_index == arg_index {
|
if param_index == arg_index {
|
||||||
return tcx.type_of(param.def_id);
|
return Some(tcx.type_of(param.def_id));
|
||||||
}
|
}
|
||||||
param_index += 1;
|
param_index += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// This is no generic parameter associated with the arg. This is
|
// This is no generic parameter associated with the arg. This is
|
||||||
// probably from an extra arg where one is not needed.
|
// probably from an extra arg where one is not needed.
|
||||||
return tcx.types.err;
|
return Some(tcx.types.err);
|
||||||
}
|
}
|
||||||
Def::Err => 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 => bug!("unexpected const parent path {:?}", x),
|
x => {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
bug!("unexpected const parent path {:?}", x);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
x => {
|
x => {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
bug!("unexpected const parent in type_of_def_id(): {:?}", x);
|
bug!("unexpected const parent in type_of_def_id(): {:?}", x);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1388,13 +1430,21 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
|
||||||
hir::GenericParamKind::Const { ref ty, .. } => {
|
hir::GenericParamKind::Const { ref ty, .. } => {
|
||||||
icx.to_ty(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 => {
|
x => {
|
||||||
|
if !fail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
|
bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_existential_constraints<'a, 'tcx>(
|
fn find_existential_constraints<'a, 'tcx>(
|
||||||
|
|
|
@ -115,6 +115,8 @@ use util::common::time;
|
||||||
|
|
||||||
use std::iter;
|
use std::iter;
|
||||||
|
|
||||||
|
pub use collect::checked_type_of;
|
||||||
|
|
||||||
pub struct TypeAndSubsts<'tcx> {
|
pub struct TypeAndSubsts<'tcx> {
|
||||||
substs: SubstsRef<'tcx>,
|
substs: SubstsRef<'tcx>,
|
||||||
ty: Ty<'tcx>,
|
ty: Ty<'tcx>,
|
||||||
|
|
|
@ -210,15 +210,20 @@ fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
|
||||||
};
|
};
|
||||||
|
|
||||||
let predicates = cx.tcx.predicates_of(did);
|
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, ret_types) = clean::get_all_types(&generics, &decl, cx);
|
||||||
clean::Function {
|
clean::Function {
|
||||||
decl: (did, sig).clean(cx),
|
decl,
|
||||||
generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
|
generics,
|
||||||
header: hir::FnHeader {
|
header: hir::FnHeader {
|
||||||
unsafety: sig.unsafety(),
|
unsafety: sig.unsafety(),
|
||||||
abi: sig.abi(),
|
abi: sig.abi(),
|
||||||
constness,
|
constness,
|
||||||
asyncness: hir::IsAsync::NotAsync,
|
asyncness: hir::IsAsync::NotAsync,
|
||||||
}
|
},
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1084,9 +1084,10 @@ impl GenericBound {
|
||||||
|
|
||||||
fn get_trait_type(&self) -> Option<Type> {
|
fn get_trait_type(&self) -> Option<Type> {
|
||||||
if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
|
if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
|
||||||
return Some(trait_.clone());
|
Some(trait_.clone())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
}
|
}
|
||||||
None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1325,6 +1326,16 @@ pub enum WherePredicate {
|
||||||
EqPredicate { lhs: Type, rhs: Type },
|
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<WherePredicate> for hir::WherePredicate {
|
impl Clean<WherePredicate> for hir::WherePredicate {
|
||||||
fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
|
fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
|
||||||
match *self {
|
match *self {
|
||||||
|
@ -1461,6 +1472,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<Type> {
|
||||||
|
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)]
|
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
|
||||||
pub struct GenericParamDef {
|
pub struct GenericParamDef {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
@ -1472,12 +1502,25 @@ impl GenericParamDef {
|
||||||
pub fn is_synthetic_type_param(&self) -> bool {
|
pub fn is_synthetic_type_param(&self) -> bool {
|
||||||
match self.kind {
|
match self.kind {
|
||||||
GenericParamDefKind::Lifetime |
|
GenericParamDefKind::Lifetime |
|
||||||
GenericParamDefKind::Const { .. } => {
|
GenericParamDefKind::Const { .. } => false,
|
||||||
false
|
|
||||||
}
|
|
||||||
GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(),
|
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<Type> {
|
||||||
|
self.kind.get_type(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_bounds(&self) -> Option<&[GenericBound]> {
|
||||||
|
match self.kind {
|
||||||
|
GenericParamDefKind::Type { ref bounds, .. } => Some(bounds),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clean<GenericParamDef> for ty::GenericParamDef {
|
impl Clean<GenericParamDef> for ty::GenericParamDef {
|
||||||
|
@ -1714,12 +1757,122 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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<T>` 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<'_>,
|
||||||
|
) -> FxHashSet<Type> {
|
||||||
|
let arg_s = arg.to_string();
|
||||||
|
let mut res = FxHashSet::default();
|
||||||
|
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 adds = get_real_types(generics, &ty, cx);
|
||||||
|
if !adds.is_empty() {
|
||||||
|
res.extend(adds);
|
||||||
|
} else if !ty.is_full_generic() {
|
||||||
|
res.insert(ty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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() {
|
||||||
|
let adds = get_real_types(generics, &ty, cx);
|
||||||
|
if !adds.is_empty() {
|
||||||
|
res.extend(adds);
|
||||||
|
} else if !ty.is_full_generic() {
|
||||||
|
res.insert(ty.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res.insert(arg.clone());
|
||||||
|
if let Some(gens) = arg.generics() {
|
||||||
|
for gen in gens.iter() {
|
||||||
|
if gen.is_full_generic() {
|
||||||
|
let adds = get_real_types(generics, gen, cx);
|
||||||
|
if !adds.is_empty() {
|
||||||
|
res.extend(adds);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res.insert(gen.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the full list of types when bounds have been resolved.
|
||||||
|
///
|
||||||
|
/// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
|
||||||
|
/// `[u32, Display, Option]`.
|
||||||
|
pub fn get_all_types(
|
||||||
|
generics: &Generics,
|
||||||
|
decl: &FnDecl,
|
||||||
|
cx: &DocContext<'_>,
|
||||||
|
) -> (Vec<Type>, Vec<Type>) {
|
||||||
|
let mut all_types = FxHashSet::default();
|
||||||
|
for arg in decl.inputs.values.iter() {
|
||||||
|
if arg.type_.is_self_type() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let args = get_real_types(generics, &arg.type_, cx);
|
||||||
|
if !args.is_empty() {
|
||||||
|
all_types.extend(args);
|
||||||
|
} else {
|
||||||
|
all_types.insert(arg.type_.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.insert(return_type.clone());
|
||||||
|
}
|
||||||
|
ret.into_iter().collect()
|
||||||
|
}
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
(all_types.into_iter().collect(), ret_types)
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
||||||
pub struct Method {
|
pub struct Method {
|
||||||
pub generics: Generics,
|
pub generics: Generics,
|
||||||
pub decl: FnDecl,
|
pub decl: FnDecl,
|
||||||
pub header: hir::FnHeader,
|
pub header: hir::FnHeader,
|
||||||
pub defaultness: Option<hir::Defaultness>,
|
pub defaultness: Option<hir::Defaultness>,
|
||||||
|
pub all_types: Vec<Type>,
|
||||||
|
pub ret_types: Vec<Type>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId,
|
impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId,
|
||||||
|
@ -1728,11 +1881,14 @@ impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId,
|
||||||
let (generics, decl) = enter_impl_trait(cx, || {
|
let (generics, decl) = enter_impl_trait(cx, || {
|
||||||
(self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
|
(self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
|
||||||
});
|
});
|
||||||
|
let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
|
||||||
Method {
|
Method {
|
||||||
decl,
|
decl,
|
||||||
generics,
|
generics,
|
||||||
header: self.0.header,
|
header: self.0.header,
|
||||||
defaultness: self.3,
|
defaultness: self.3,
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1742,6 +1898,8 @@ pub struct TyMethod {
|
||||||
pub header: hir::FnHeader,
|
pub header: hir::FnHeader,
|
||||||
pub decl: FnDecl,
|
pub decl: FnDecl,
|
||||||
pub generics: Generics,
|
pub generics: Generics,
|
||||||
|
pub all_types: Vec<Type>,
|
||||||
|
pub ret_types: Vec<Type>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
||||||
|
@ -1749,6 +1907,8 @@ pub struct Function {
|
||||||
pub decl: FnDecl,
|
pub decl: FnDecl,
|
||||||
pub generics: Generics,
|
pub generics: Generics,
|
||||||
pub header: hir::FnHeader,
|
pub header: hir::FnHeader,
|
||||||
|
pub all_types: Vec<Type>,
|
||||||
|
pub ret_types: Vec<Type>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clean<Item> for doctree::Function {
|
impl Clean<Item> for doctree::Function {
|
||||||
|
@ -1763,6 +1923,7 @@ impl Clean<Item> for doctree::Function {
|
||||||
} else {
|
} else {
|
||||||
hir::Constness::NotConst
|
hir::Constness::NotConst
|
||||||
};
|
};
|
||||||
|
let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
|
||||||
Item {
|
Item {
|
||||||
name: Some(self.name.clean(cx)),
|
name: Some(self.name.clean(cx)),
|
||||||
attrs: self.attrs.clean(cx),
|
attrs: self.attrs.clean(cx),
|
||||||
|
@ -1775,6 +1936,8 @@ impl Clean<Item> for doctree::Function {
|
||||||
decl,
|
decl,
|
||||||
generics,
|
generics,
|
||||||
header: hir::FnHeader { constness, ..self.header },
|
header: hir::FnHeader { constness, ..self.header },
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1862,7 +2025,7 @@ impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
|
||||||
FnDecl {
|
FnDecl {
|
||||||
inputs: (&self.0.inputs[..], self.1).clean(cx),
|
inputs: (&self.0.inputs[..], self.1).clean(cx),
|
||||||
output: self.0.output.clean(cx),
|
output: self.0.output.clean(cx),
|
||||||
attrs: Attributes::default()
|
attrs: Attributes::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2044,10 +2207,13 @@ impl Clean<Item> for hir::TraitItem {
|
||||||
let (generics, decl) = enter_impl_trait(cx, || {
|
let (generics, decl) = enter_impl_trait(cx, || {
|
||||||
(self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
|
(self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
|
||||||
});
|
});
|
||||||
|
let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
|
||||||
TyMethodItem(TyMethod {
|
TyMethodItem(TyMethod {
|
||||||
header: sig.header,
|
header: sig.header,
|
||||||
decl,
|
decl,
|
||||||
generics,
|
generics,
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
hir::TraitItemKind::Type(ref bounds, ref default) => {
|
hir::TraitItemKind::Type(ref bounds, ref default) => {
|
||||||
|
@ -2145,6 +2311,7 @@ impl<'tcx> Clean<Item> for ty::AssociatedItem {
|
||||||
ty::ImplContainer(_) => true,
|
ty::ImplContainer(_) => true,
|
||||||
ty::TraitContainer(_) => self.defaultness.has_value()
|
ty::TraitContainer(_) => self.defaultness.has_value()
|
||||||
};
|
};
|
||||||
|
let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
|
||||||
if provided {
|
if provided {
|
||||||
let constness = if cx.tcx.is_min_const_fn(self.def_id) {
|
let constness = if cx.tcx.is_min_const_fn(self.def_id) {
|
||||||
hir::Constness::Const
|
hir::Constness::Const
|
||||||
|
@ -2161,6 +2328,8 @@ impl<'tcx> Clean<Item> for ty::AssociatedItem {
|
||||||
asyncness: hir::IsAsync::NotAsync,
|
asyncness: hir::IsAsync::NotAsync,
|
||||||
},
|
},
|
||||||
defaultness: Some(self.defaultness),
|
defaultness: Some(self.defaultness),
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
TyMethodItem(TyMethod {
|
TyMethodItem(TyMethod {
|
||||||
|
@ -2171,7 +2340,9 @@ impl<'tcx> Clean<Item> for ty::AssociatedItem {
|
||||||
abi: sig.abi(),
|
abi: sig.abi(),
|
||||||
constness: hir::Constness::NotConst,
|
constness: hir::Constness::NotConst,
|
||||||
asyncness: hir::IsAsync::NotAsync,
|
asyncness: hir::IsAsync::NotAsync,
|
||||||
}
|
},
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2420,6 +2591,13 @@ impl Type {
|
||||||
_ => None
|
_ => None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_full_generic(&self) -> bool {
|
||||||
|
match *self {
|
||||||
|
Type::Generic(_) => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GetDefId for Type {
|
impl GetDefId for Type {
|
||||||
|
@ -3849,6 +4027,7 @@ impl Clean<Item> for hir::ForeignItem {
|
||||||
let (generics, decl) = enter_impl_trait(cx, || {
|
let (generics, decl) = enter_impl_trait(cx, || {
|
||||||
(generics.clean(cx), (&**decl, &names[..]).clean(cx))
|
(generics.clean(cx), (&**decl, &names[..]).clean(cx))
|
||||||
});
|
});
|
||||||
|
let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
|
||||||
ForeignFunctionItem(Function {
|
ForeignFunctionItem(Function {
|
||||||
decl,
|
decl,
|
||||||
generics,
|
generics,
|
||||||
|
@ -3858,6 +4037,8 @@ impl Clean<Item> for hir::ForeignItem {
|
||||||
constness: hir::Constness::NotConst,
|
constness: hir::Constness::NotConst,
|
||||||
asyncness: hir::IsAsync::NotAsync,
|
asyncness: hir::IsAsync::NotAsync,
|
||||||
},
|
},
|
||||||
|
all_types,
|
||||||
|
ret_types,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
hir::ForeignItemKind::Static(ref ty, mutbl) => {
|
hir::ForeignItemKind::Static(ref ty, mutbl) => {
|
||||||
|
|
|
@ -446,7 +446,7 @@ impl ToJson for Type {
|
||||||
}
|
}
|
||||||
Json::Array(data)
|
Json::Array(data)
|
||||||
}
|
}
|
||||||
None => Json::Null
|
None => Json::Null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -455,19 +455,27 @@ impl ToJson for Type {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct IndexItemFunctionType {
|
struct IndexItemFunctionType {
|
||||||
inputs: Vec<Type>,
|
inputs: Vec<Type>,
|
||||||
output: Option<Type>,
|
output: Option<Vec<Type>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ToJson for IndexItemFunctionType {
|
impl ToJson for IndexItemFunctionType {
|
||||||
fn to_json(&self) -> Json {
|
fn to_json(&self) -> Json {
|
||||||
// If we couldn't figure out a type, just write `null`.
|
// 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
|
Json::Null
|
||||||
} else {
|
} else {
|
||||||
let mut data = Vec::with_capacity(2);
|
let mut data = Vec::with_capacity(2);
|
||||||
data.push(self.inputs.to_json());
|
data.push(self.inputs.to_json());
|
||||||
if let Some(ref output) = self.output {
|
if let Some(ref output) = self.output {
|
||||||
data.push(output.to_json());
|
if output.len() > 1 {
|
||||||
|
data.push(output.to_json());
|
||||||
|
} else {
|
||||||
|
data.push(output[0].to_json());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Json::Array(data)
|
Json::Array(data)
|
||||||
}
|
}
|
||||||
|
@ -5025,20 +5033,26 @@ fn make_item_keywords(it: &clean::Item) -> String {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
|
fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
|
||||||
let decl = match item.inner {
|
let (all_types, ret_types) = match item.inner {
|
||||||
clean::FunctionItem(ref f) => &f.decl,
|
clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
|
||||||
clean::MethodItem(ref m) => &m.decl,
|
clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
|
||||||
clean::TyMethodItem(ref m) => &m.decl,
|
clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
|
||||||
_ => return None
|
_ => return None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
|
let inputs = all_types.iter().map(|arg| {
|
||||||
let output = match decl.output {
|
get_index_type(&arg)
|
||||||
clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
|
}).filter(|a| a.name.is_some()).collect();
|
||||||
_ => None
|
let output = ret_types.iter().map(|arg| {
|
||||||
|
get_index_type(&arg)
|
||||||
|
}).filter(|a| a.name.is_some()).collect::<Vec<_>>();
|
||||||
|
let output = if output.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(output)
|
||||||
};
|
};
|
||||||
|
|
||||||
Some(IndexItemFunctionType { inputs: inputs, output: output })
|
Some(IndexItemFunctionType { inputs, output })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_index_type(clean_type: &clean::Type) -> Type {
|
fn get_index_type(clean_type: &clean::Type) -> Type {
|
||||||
|
|
|
@ -714,7 +714,10 @@ if (!DOMTokenList.prototype.remove) {
|
||||||
}
|
}
|
||||||
lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
|
lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
|
||||||
if (lev_distance <= MAX_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) {
|
} 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!
|
// We can check if the type we're looking for is inside the generics!
|
||||||
var olength = obj[GENERICS_DATA].length;
|
var olength = obj[GENERICS_DATA].length;
|
||||||
|
@ -752,13 +755,26 @@ if (!DOMTokenList.prototype.remove) {
|
||||||
var lev_distance = MAX_LEV_DISTANCE + 1;
|
var lev_distance = MAX_LEV_DISTANCE + 1;
|
||||||
|
|
||||||
if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
|
if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
|
||||||
var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
|
var ret = obj.type[OUTPUT_DATA];
|
||||||
if (literalSearch === true && tmp === true) {
|
if (!obj.type[OUTPUT_DATA].length) {
|
||||||
return true;
|
ret = [ret];
|
||||||
}
|
}
|
||||||
lev_distance = Math.min(tmp, lev_distance);
|
for (var x = 0; x < ret.length; ++x) {
|
||||||
if (lev_distance === 0) {
|
var r = ret[x];
|
||||||
return 0;
|
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) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return literalSearch === true ? false : lev_distance;
|
return literalSearch === true ? false : lev_distance;
|
||||||
|
|
|
@ -1195,7 +1195,7 @@ pre.rust {
|
||||||
border-top: 2px solid;
|
border-top: 2px solid;
|
||||||
}
|
}
|
||||||
|
|
||||||
#titles > div:not(:last-child):not(.selected) {
|
#titles > div:not(:last-child) {
|
||||||
margin-right: 1px;
|
margin-right: 1px;
|
||||||
width: calc(33.3% - 1px);
|
width: calc(33.3% - 1px);
|
||||||
}
|
}
|
||||||
|
|
|
@ -189,6 +189,10 @@ a.test-arrow {
|
||||||
.stab.deprecated { background: #F3DFFF; border-color: #7F0087; color: #2f2f2f; }
|
.stab.deprecated { background: #F3DFFF; border-color: #7F0087; color: #2f2f2f; }
|
||||||
.stab.portability { background: #C4ECFF; border-color: #7BA5DB; color: #2f2f2f; }
|
.stab.portability { background: #C4ECFF; border-color: #7BA5DB; color: #2f2f2f; }
|
||||||
|
|
||||||
|
.stab > code {
|
||||||
|
color: #ddd;
|
||||||
|
}
|
||||||
|
|
||||||
#help > div {
|
#help > div {
|
||||||
background: #4d4d4d;
|
background: #4d4d4d;
|
||||||
border-color: #bfbfbf;
|
border-color: #bfbfbf;
|
||||||
|
|
|
@ -190,6 +190,10 @@ a.test-arrow {
|
||||||
.stab.deprecated { background: #F3DFFF; border-color: #7F0087; }
|
.stab.deprecated { background: #F3DFFF; border-color: #7F0087; }
|
||||||
.stab.portability { background: #C4ECFF; border-color: #7BA5DB; }
|
.stab.portability { background: #C4ECFF; border-color: #7BA5DB; }
|
||||||
|
|
||||||
|
.stab > code {
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
#help > div {
|
#help > div {
|
||||||
background: #e9e9e9;
|
background: #e9e9e9;
|
||||||
border-color: #bfbfbf;
|
border-color: #bfbfbf;
|
||||||
|
|
|
@ -117,6 +117,7 @@ impl CompareMode {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Configuration for compiletest
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
/// `true` to to overwrite stderr/stdout files instead of complaining about changes in output.
|
/// `true` to to overwrite stderr/stdout files instead of complaining about changes in output.
|
||||||
|
@ -254,6 +255,8 @@ pub struct Config {
|
||||||
pub linker: Option<String>,
|
pub linker: Option<String>,
|
||||||
pub llvm_components: String,
|
pub llvm_components: String,
|
||||||
pub llvm_cxxflags: String,
|
pub llvm_cxxflags: String,
|
||||||
|
|
||||||
|
/// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests
|
||||||
pub nodejs: Option<String>,
|
pub nodejs: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -333,7 +333,10 @@ pub struct TestProps {
|
||||||
pub normalize_stdout: Vec<(String, String)>,
|
pub normalize_stdout: Vec<(String, String)>,
|
||||||
pub normalize_stderr: Vec<(String, String)>,
|
pub normalize_stderr: Vec<(String, String)>,
|
||||||
pub failure_status: i32,
|
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,
|
pub run_rustfix: bool,
|
||||||
|
// If true, `rustfix` will only apply `MachineApplicable` suggestions.
|
||||||
pub rustfix_only_machine_applicable: bool,
|
pub rustfix_only_machine_applicable: bool,
|
||||||
pub assembly_output: Option<String>,
|
pub assembly_output: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
|
@ -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::errors::{Error, ErrorKind};
|
||||||
use crate::runtest::ProcRes;
|
use crate::runtest::ProcRes;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
// These structs are a subset of the ones found in
|
|
||||||
// `syntax::json`.
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Diagnostic {
|
struct Diagnostic {
|
||||||
message: String,
|
message: String,
|
||||||
|
|
|
@ -598,6 +598,8 @@ fn collect_tests_from_dir(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Returns true if `file_name` looks like a proper test file name.
|
||||||
pub fn is_test(file_name: &OsString) -> bool {
|
pub fn is_test(file_name: &OsString) -> bool {
|
||||||
let file_name = file_name.to_str().unwrap();
|
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",
|
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")));
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue