}
// Set a flag for `check` so that certain build scripts can do less work
- // (e.g. not building/requiring LLVM).
+ // (e.g., not building/requiring LLVM).
if cmd == "check" {
cargo.env("RUST_CHECK", "1");
}
cargo.env("RUSTC_FORCE_UNSTABLE", "1");
// Currently the compiler depends on crates from crates.io, and
- // then other crates can depend on the compiler (e.g. proc-macro
+ // then other crates can depend on the compiler (e.g., proc-macro
// crates). Let's say, for example that rustc itself depends on the
// bitflags crate. If an external crate then depends on the
// bitflags crate as well, we need to make sure they don't
// conflict, even if they pick the same version of bitflags. We'll
- // want to make sure that e.g. a plugin and rustc each get their
+ // want to make sure that e.g., a plugin and rustc each get their
// own copy of bitflags.
// Cargo ensures that this works in general through the -C metadata
/// Build the `rust-mingw` installer component.
///
/// This contains all the bits and pieces to run the MinGW Windows targets
- /// without any extra installed software (e.g. we bundle gcc, libraries, etc).
+ /// without any extra installed software (e.g., we bundle gcc, libraries, etc).
fn run(self, builder: &Builder) -> Option<PathBuf> {
let host = self.host;
opts.optopt("", "on-fail", "command to run on failure", "CMD");
opts.optflag("", "dry-run", "dry run; don't build anything");
opts.optopt("", "stage",
- "stage to build (indicates compiler to use/test, e.g. stage 0 uses the \
+ "stage to build (indicates compiler to use/test, e.g., stage 0 uses the \
bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)",
"N");
opts.optmulti("", "keep-stage", "stage(s) to keep without recompiling \
- (pass multiple times to keep e.g. both stages 0 and 1)", "N");
+ (pass multiple times to keep e.g., both stages 0 and 1)", "N");
opts.optopt("", "src", "path to the root of the rust checkout", "DIR");
opts.optopt("j", "jobs", "number of jobs to run in parallel", "JOBS");
opts.optflag("h", "help", "print this help message");
//! Job management on Windows for bootstrapping
//!
-//! Most of the time when you're running a build system (e.g. make) you expect
+//! Most of the time when you're running a build system (e.g., make) you expect
//! Ctrl-C or abnormal termination to actually terminate the entire tree of
//! process in play, not just the one at the top. This currently works "by
//! default" on Unix platforms because Ctrl-C actually sends a signal to the
return
}
- // If we've got a parent process (e.g. the python script that called us)
+ // If we've got a parent process (e.g., the python script that called us)
// then move ownership of this job object up to them. That way if the python
- // script is killed (e.g. via ctrl-c) then we'll all be torn down.
+ // script is killed (e.g., via ctrl-c) then we'll all be torn down.
//
- // If we don't have a parent (e.g. this was run directly) then we
+ // If we don't have a parent (e.g., this was run directly) then we
// intentionally leak the job object handle. When our process exits
// (normally or abnormally) it will close the handle implicitly, causing all
// processes in the job to be cleaned up.
// If this failed, well at least we tried! An example of DuplicateHandle
// failing in the past has been when the wrong python2 package spawned this
- // build system (e.g. the `python2` package in MSYS instead of
+ // build system (e.g., the `python2` package in MSYS instead of
// `mingw-w64-x86_64-python2`. Not sure why it failed, but the "failure
// mode" here is that we only clean everything up when the build system
// dies, not when the python parent does, so not too bad.
//! However, compiletest itself tries to avoid running tests when the artifacts
//! that are involved (mainly the compiler) haven't changed.
//!
-//! When you execute `x.py build`, the steps which are executed are:
+//! When you execute `x.py build`, the steps executed are:
//!
//! * First, the python script is run. This will automatically download the
//! stage0 rustc and cargo according to `src/stage0.txt`, or use the cached
configure_cmake(builder, target, &mut cfg, false);
// FIXME: we don't actually need to build all LLVM tools and all LLVM
- // libraries here, e.g. we just want a few components and a few
+ // libraries here, e.g., we just want a few components and a few
// tools. Figure out how to filter them down and only build the right
// tools and libs on all platforms.
}
if builder.no_std(target) == Some(true) {
- // for no_std run-make (e.g. thumb*),
+ // for no_std run-make (e.g., thumb*),
// we need a host compiler which is called by cargo.
builder.ensure(compile::Std { compiler, target: compiler.host });
}
/// Run `rustdoc --test` for all documentation in `src/doc`.
///
- /// This will run all tests in our markdown documentation (e.g. the book)
+ /// This will run all tests in our markdown documentation (e.g., the book)
/// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
/// `compiler`.
fn run(self, builder: &Builder) {
self.cargo_out(compiler, tool.get_mode(), *host).join("deps"),
];
- // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
+ // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
// mode) and that C compiler may need some extra PATH modification. Do
// so here.
if compiler.host.contains("msvc") {
* safe.)
* - It is in practice very useful to have Box<T> be unconditionally
* Unpin because of trait objects, for which the structural auto
- * trait functionality does not apply (e.g. Box<dyn Foo> would
+ * trait functionality does not apply (e.g., Box<dyn Foo> would
* otherwise not be Unpin).
*
* Another type with the same semantics as Box but only a conditional
}
}
-/// Hole represents a hole in a slice i.e. an index without valid value
+/// Hole represents a hole in a slice i.e., an index without valid value
/// (because it was moved from or duplicated).
/// In drop, `Hole` will restore the slice by filling the hole
/// position with the value that was originally removed.
}
/// Visits the values representing the difference,
- /// i.e. the values that are in `self` but not in `other`,
+ /// i.e., the values that are in `self` but not in `other`,
/// in ascending order.
///
/// # Examples
}
/// Visits the values representing the symmetric difference,
- /// i.e. the values that are in `self` or in `other` but not in both,
+ /// i.e., the values that are in `self` or in `other` but not in both,
/// in ascending order.
///
/// # Examples
}
/// Visits the values representing the intersection,
- /// i.e. the values that are both in `self` and `other`,
+ /// i.e., the values that are both in `self` and `other`,
/// in ascending order.
///
/// # Examples
}
/// Visits the values representing the union,
- /// i.e. all the values in `self` or `other`, without duplicates,
+ /// i.e., all the values in `self` or `other`, without duplicates,
/// in ascending order.
///
/// # Examples
}
/// Returns `true` if the set is a subset of another,
- /// i.e. `other` contains at least all the values in `self`.
+ /// i.e., `other` contains at least all the values in `self`.
///
/// # Examples
///
}
/// Returns `true` if the set is a superset of another,
- /// i.e. `self` contains at least all the values in `other`.
+ /// i.e., `self` contains at least all the values in `other`.
///
/// # Examples
///
// On 64-bit we just need to check for overflow since trying to allocate
// `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
// an extra guard for this in case we're running on a platform which can use
-// all 4GB in user-space. e.g. PAE or x32
+// all 4GB in user-space. e.g., PAE or x32
#[inline]
fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> {
/// See the [module-level documentation](./index.html) for more details.
///
/// The inherent methods of `Rc` are all associated functions, which means
-/// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
+/// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
/// `value.get_mut()`. This avoids conflicts with methods of the inner
/// type `T`.
///
}
/// Return `None` when the pointer is dangling and there is no allocated `RcBox`,
- /// i.e. this `Weak` was created by `Weak::new`
+ /// i.e., this `Weak` was created by `Weak::new`
#[inline]
fn inner(&self) -> Option<&RcBox<T>> {
if is_dangling(self.ptr) {
impl<T> [T] {
/// Sorts the slice.
///
- /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
+ /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case.
///
/// When applicable, unstable sorting is preferred because it is generally faster than stable
/// sorting and it doesn't allocate auxiliary memory.
/// Sorts the slice with a comparator function.
///
- /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
+ /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case.
///
/// The comparator function must define a total ordering for the elements in the slice. If
/// the ordering is not total, the order of the elements is unspecified. An order is a
/// Sorts the slice with a key extraction function.
///
- /// This sort is stable (i.e. does not reorder equal elements) and `O(m n log(m n))`
+ /// This sort is stable (i.e., does not reorder equal elements) and `O(m n log(m n))`
/// worst-case, where the key function is `O(m)`.
///
/// When applicable, unstable sorting is preferred because it is generally faster than stable
///
/// During sorting, the key function is called only once per element.
///
- /// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)`
+ /// This sort is stable (i.e., does not reorder equal elements) and `O(m n + n log n)`
/// worst-case, where the key function is `O(m)`.
///
- /// For simple key functions (e.g. functions that are property accesses or
+ /// For simple key functions (e.g., functions that are property accesses or
/// basic operations), [`sort_by_key`](#method.sort_by_key) is likely to be
/// faster.
///
}
/// Return `None` when the pointer is dangling and there is no allocated `ArcInner`,
- /// i.e. this `Weak` was created by `Weak::new`
+ /// i.e., this `Weak` was created by `Weak::new`
#[inline]
fn inner(&self) -> Option<&ArcInner<T>> {
if is_dangling(self.ptr) {
// create a vector like [(6, 1), (5, 1), (6, 2), ...],
// where the first item of each tuple is random, but
// the second item represents which occurrence of that
- // number this element is, i.e. the second elements
+ // number this element is, i.e., the second elements
// will occur in sorted order.
let mut orig: Vec<_> = (0..len)
.map(|_| {
// This comparison includes the count (the second item
// of the tuple), so elements with equal first items
// will need to be ordered with increasing
- // counts... i.e. exactly asserting that this sort is
+ // counts... i.e., exactly asserting that this sort is
// stable.
assert!(v.windows(2).all(|w| w[0] <= w[1]));
}).join();
// Check that the number of things dropped is exactly
- // what we expect (i.e. the contents of `v`).
+ // what we expect (i.e., the contents of `v`).
for (i, c) in DROP_COUNTS.iter().enumerate().take(len) {
let count = c.load(Relaxed);
assert!(count == 1,
// Note that there are subtleties with the number of backslashes
// on the left- and right-hand sides. In particular, Unicode code points
// are usually escaped with two backslashes on the right-hand side, as
- // they are escaped. However, when the character is unescaped (e.g. for
+ // they are escaped. However, when the character is unescaped (e.g., for
// printable characters), only a single backslash appears (as the character
// itself appears in the debug string).
assert_eq!("abc".escape_debug(), "abc");
/// about its design. This ensures that it's as low-overhead as possible in
/// the general case, and can be correctly manipulated in primitive ways
/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
-/// If additional type parameters are added (e.g. to support custom allocators),
+/// If additional type parameters are added (e.g., to support custom allocators),
/// overriding their defaults may change the behavior.
///
/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
/// * `align` must be a power of two,
///
/// * `size`, when rounded up to the nearest multiple of `align`,
- /// must not overflow (i.e. the rounded value must be less than
+ /// must not overflow (i.e., the rounded value must be less than
/// `usize::MAX`).
#[stable(feature = "alloc_layout", since = "1.28.0")]
#[inline]
/// to ensure that the following address will satisfy `align`
/// (measured in bytes).
///
- /// E.g. if `self.size()` is 9, then `self.padding_needed_for(4)`
+ /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
/// returns 3, because that is the minimum number of bytes of
/// padding required to get a 4-aligned address (assuming that the
/// corresponding memory block starts at a 4-aligned address).
/// if the caller does not ensure that `layout` has non-zero size.
///
/// (Extension subtraits might provide more specific bounds on
- /// behavior, e.g. guarantee a sentinel address or a null pointer
+ /// behavior, e.g., guarantee a sentinel address or a null pointer
/// in response to a zero-size allocation request.)
///
/// The allocated block of memory may or may not be initialized.
/// * `new_size` must be greater than zero.
///
/// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
- /// must not overflow (i.e. the rounded value must be less than `usize::MAX`).
+ /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
///
/// (Extension subtraits might provide more specific bounds on
- /// behavior, e.g. guarantee a sentinel address or a null pointer
+ /// behavior, e.g., guarantee a sentinel address or a null pointer
/// in response to a zero-size allocation request.)
///
/// # Errors
/// whether to return `Err`, or to return `Ok` with some pointer.
///
/// * If an `Alloc` implementation chooses to return `Ok` in this
-/// case (i.e. the pointer denotes a zero-sized inaccessible block)
+/// case (i.e., the pointer denotes a zero-sized inaccessible block)
/// then that returned pointer must be considered "currently
/// allocated". On such an allocator, *all* methods that take
/// currently-allocated pointers as inputs must accept these
///
/// * if a layout `k` fits a memory block (denoted by `ptr`)
/// currently allocated via an allocator `a`, then it is legal to
-/// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
+/// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
///
/// # Unsafety
///
// (Note: some existing allocators have unspecified but well-defined
// behavior in response to a zero size allocation request ;
- // e.g. in C, `malloc` of 0 will either return a null pointer or a
+ // e.g., in C, `malloc` of 0 will either return a null pointer or a
// unique pointer, but will not have arbitrary undefined
// behavior.
// However in jemalloc for example,
///
/// The returned block of storage may or may not have its contents
/// initialized. (Extension subtraits might restrict this
- /// behavior, e.g. to ensure initialization to particular sets of
+ /// behavior, e.g., to ensure initialization to particular sets of
/// bit patterns.)
///
/// # Safety
/// if the caller does not ensure that `layout` has non-zero size.
///
/// (Extension subtraits might provide more specific bounds on
- /// behavior, e.g. guarantee a sentinel address or a null pointer
+ /// behavior, e.g., guarantee a sentinel address or a null pointer
/// in response to a zero-size allocation request.)
///
/// # Errors
/// * `new_size` must be greater than zero.
///
/// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
- /// must not overflow (i.e. the rounded value must be less than `usize::MAX`).
+ /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
///
/// (Extension subtraits might provide more specific bounds on
- /// behavior, e.g. guarantee a sentinel address or a null pointer
+ /// behavior, e.g., guarantee a sentinel address or a null pointer
/// in response to a zero-size allocation request.)
///
/// # Errors
}
}
-// Ensure that the result of e.g. joining a thread can be printed and
+// Ensure that the result of e.g., joining a thread can be printed and
// hence used with `unwrap`. May eventually no longer be needed if
// dispatch works with upcasting.
#[stable(feature = "rust1", since = "1.0.0")]
//! ## Implementation details of logically-immutable methods
//!
//! Occasionally it may be desirable not to expose in an API that there is mutation happening
-//! "under the hood". This may be because logically the operation is immutable, but e.g. caching
+//! "under the hood". This may be because logically the operation is immutable, but e.g., caching
//! forces the implementation to perform mutation; or because you must employ mutation to implement
//! a trait method that was originally defined to take `&self`.
//!
}
impl<'b, T: ?Sized> RefMut<'b, T> {
- /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
+ /// Make a new `RefMut` for a component of the borrowed data, e.g., an enum
/// variant.
///
/// The `RefCell` is already mutably borrowed, so this cannot fail.
state: EscapeUnicodeState,
// The index of the next hex digit to be printed (0 if none),
- // i.e. the number of remaining hex digits to be printed;
+ // i.e., the number of remaining hex digits to be printed;
// increasing from the least significant digit: 0x543210
hex_digit_idx: usize,
}
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
-//! allocation to copy and do not have finalizers (i.e. they do not
+//! allocation to copy and do not have finalizers (i.e., they do not
//! contain owned boxes or implement [`Drop`]), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the [`Clone`] trait and calling
/// In addition to the [implementors listed below][impls],
/// the following types also implement `Clone`:
///
-/// * Function item types (i.e. the distinct types defined for each function)
-/// * Function pointer types (e.g. `fn() -> i32`)
-/// * Array types, for all sizes, if the item type also implements `Clone` (e.g. `[i32; 123456]`)
-/// * Tuple types, if each component also implements `Clone` (e.g. `()`, `(i32, bool)`)
+/// * Function item types (i.e., the distinct types defined for each function)
+/// * Function pointer types (e.g., `fn() -> i32`)
+/// * Array types, for all sizes, if the item type also implements `Clone` (e.g., `[i32; 123456]`)
+/// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
/// * Closure types, if they capture no value from the environment
/// or if all such captured values implement `Clone` themselves.
/// Note that variables captured by shared reference always implement `Clone`
///
/// [`!`]: ../../std/primitive.never.html
/// [pointer]: ../../std/primitive.pointer.html
-// NB: For LLVM to recognize the void pointer type and by extension
+// N.B., for LLVM to recognize the void pointer type and by extension
// functions like malloc(), we need to have it represented as i8* in
// LLVM bitcode. The enum used here ensures this and prevents misuse
// of the "raw" type by only having private variants.. We need two
/// A trait for creating instances of [`Hasher`].
///
-/// A `BuildHasher` is typically used (e.g. by [`HashMap`]) to create
+/// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
/// [`Hasher`]s for each key such that they are hashed independently of one
/// another, since [`Hasher`]s contain state.
///
/// therefore will eliminate all branches that reach to a call to
/// `unreachable_unchecked()`.
///
-/// Like all instances of UB, if this assumption turns out to be wrong, i.e. the
+/// Like all instances of UB, if this assumption turns out to be wrong, i.e., the
/// `unreachable_unchecked()` call is actually reachable among all possible
/// control flow, the compiler will apply the wrong optimization strategy, and
/// may sometimes even corrupt seemingly unrelated code, causing
pub use ptr::drop_in_place;
extern "rust-intrinsic" {
- // NB: These intrinsics take raw pointers because they mutate aliased
+ // N.B., these intrinsics take raw pointers because they mutate aliased
// memory, which is not valid for either `&` or `&mut`.
/// Stores a value if the current value is the same as the `old` value.
/// Tells LLVM that this point in the code is not reachable, enabling
/// further optimizations.
///
- /// NB: This is very different from the `unreachable!()` macro: Unlike the
+ /// N.B., this is very different from the `unreachable!()` macro: Unlike the
/// macro, which panics when it is executed, it is *undefined behavior* to
/// reach code marked with this function.
///
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be
- /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
+ /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
fn product<I: Iterator<Item=A>>(iter: I) -> Self;
}
-// NB: explicitly use Add and Mul here to inherit overflow checks
+// N.B., explicitly use Add and Mul here to inherit overflow checks
macro_rules! integer_sum_product {
(@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
#[$attr]
/// In addition to the [implementors listed below][impls],
/// the following types also implement `Copy`:
///
-/// * Function item types (i.e. the distinct types defined for each function)
-/// * Function pointer types (e.g. `fn() -> i32`)
-/// * Array types, for all sizes, if the item type also implements `Copy` (e.g. `[i32; 123456]`)
-/// * Tuple types, if each component also implements `Copy` (e.g. `()`, `(i32, bool)`)
+/// * Function item types (i.e., the distinct types defined for each function)
+/// * Function pointer types (e.g., `fn() -> i32`)
+/// * Array types, for all sizes, if the item type also implements `Copy` (e.g., `[i32; 123456]`)
+/// * Tuple types, if each component also implements `Copy` (e.g., `()`, `(i32, bool)`)
/// * Closure types, if they capture no value from the environment
/// or if all such captured values implement `Copy` themselves.
/// Note that variables captured by shared reference always implement `Copy`
/// Returns the size of the pointed-to value in bytes.
///
/// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
-/// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
+/// statically known size, e.g., a slice [`[T]`][slice] or a [trait object],
/// then `size_of_val` can be used to get the dynamically-known size.
///
/// [slice]: ../../std/primitive.slice.html
/// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
/// state, otherwise this will immediately cause undefined behavior.
// FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
- // to uninitialized data (e.g. in `libcore/fmt/float.rs`). We should make
+ // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
// a final decision about the rules before stabilization.
#[unstable(feature = "maybe_uninit", issue = "53491")]
#[inline(always)]
let nonzero = &digits[..end];
if nonzero.is_empty() {
- // There are no non-zero digits, i.e. the number is zero.
+ // There are no non-zero digits, i.e., the number is zero.
return 0;
}
// This could be optimized with leading_zeros() and bit shifts, but that's
///
/// The only field which is relevant for the following code is PC, Precision Control. This
/// field determines the precision of the operations performed by the FPU. It can be set to:
- /// - 0b00, single precision i.e. 32-bits
- /// - 0b10, double precision i.e. 64-bits
- /// - 0b11, double extended precision i.e. 80-bits (default state)
+ /// - 0b00, single precision i.e., 32-bits
+ /// - 0b10, double precision i.e., 64-bits
+ /// - 0b11, double extended precision i.e., 80-bits (default state)
/// The 0b01 value is reserved and should not be used.
pub struct FPUControlWord(u16);
}
// Find the smallest floating point number strictly larger than the argument.
-// This operation is saturating, i.e. next_float(inf) == inf.
+// This operation is saturating, i.e., next_float(inf) == inf.
// Unlike most code in this module, this function does handle zero, subnormals, and infinities.
// However, like all other code here, it does not deal with NaN and negative numbers.
pub fn next_float<T: RawFloat>(x: T) -> T {
- `d[0]` is non-zero.
- It's correctly rounded when parsed back: `v - minus < V < v + plus`.
- Furthermore it is shortest such one, i.e. there is no representation
+ Furthermore it is shortest such one, i.e., there is no representation
with less than `n` digits that is correctly rounded.
- It's closest to the original value: `abs(V - v) <= 10^(k-n) / 2`. Note that
/// given number of fractional digits. The result is stored to the supplied parts
/// array while utilizing given byte buffer as a scratch. `upper` is currently
/// unused but left for the future decision to change the case of non-finite values,
-/// i.e. `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
+/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
/// (which can be an empty string if no sign is rendered).
///
/// `format_shortest` should be the underlying digit-generation function.
/// given number of fractional digits. The result is stored to the supplied parts
/// array while utilizing given byte buffer as a scratch. `upper` is currently
/// unused but left for the future decision to change the case of non-finite values,
-/// i.e. `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
+/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
/// (which can be an empty string if no sign is rendered).
///
/// `format_exact` should be the underlying digit-generation function.
// - followed by `(mant + 2 * plus) * 2^exp` in the original type.
//
// obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
- // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
+ // also we assume that at least one digit is generated, i.e., `mant` cannot be zero too.
//
// this also means that any number between `low = (mant - minus) * 2^exp` and
// `high = (mant + plus) * 2^exp` will map to this exact floating point number,
- // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
+ // with bounds included when the original mantissa was even (i.e., `!mant_was_odd`).
assert!(d.mant > 0);
assert!(d.minus > 0);
// - `high - v = plus / scale * 10^(k-n)`
//
// assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
- // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
+ // i.e., `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
// - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
// - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
//
// rounding up if we stop in the middle of digits
// if the following digits are exactly 5000..., check the prior digit and try to
- // round to even (i.e. avoid rounding up when the prior digit is even).
+ // round to even (i.e., avoid rounding up when the prior digit is even).
let order = mant.cmp(scale.mul_small(5));
if order == Ordering::Greater || (order == Ordering::Equal &&
(len == 0 || buf[len-1] & 1 == 1)) {
//
// find the digit length `kappa` between `(minus1, plus1)` as per Theorem 6.2.
// Theorem 6.2 can be adopted to exclude `x` by requiring `y mod 10^k < y - x` instead.
- // (e.g. `x` = 32000, `y` = 32777; `kappa` = 2 since `y mod 10^3 = 777 < y - x = 777`.)
+ // (e.g., `x` = 32000, `y` = 32777; `kappa` = 2 since `y mod 10^3 = 777 < y - x = 777`.)
// the algorithm relies on the later verification phase to exclude `y`.
let delta1 = plus1 - minus1;
// let delta1int = (delta1 >> e) as usize; // only for explanation
// proceed, but we then have at least one valid representation known to be closest to
// `v + 1 ulp` anyway. we will denote them as TC1 through TC3 for brevity.
//
- // TC1: `w(n) <= v + 1 ulp`, i.e. this is the last repr that can be the closest one.
+ // TC1: `w(n) <= v + 1 ulp`, i.e., this is the last repr that can be the closest one.
// this is equivalent to `plus1 - w(n) = plus1w(n) >= plus1 - (v + 1 ulp) = plus1v_up`.
// combined with TC2 (which checks if `w(n+1)` is valid), this prevents the possible
// overflow on the calculation of `plus1w(n)`.
//
- // TC2: `w(n+1) < minus1`, i.e. the next repr definitely does not round to `v`.
+ // TC2: `w(n+1) < minus1`, i.e., the next repr definitely does not round to `v`.
// this is equivalent to `plus1 - w(n) + 10^kappa = plus1w(n) + 10^kappa >
// plus1 - minus1 = threshold`. the left hand side can overflow, but we know
// `threshold > plus1v`, so if TC1 is false, `threshold - plus1w(n) >
// threshold - (plus1v - 1 ulp) > 1 ulp` and we can safely test if
// `threshold - plus1w(n) < 10^kappa` instead.
//
- // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e. the next repr is
+ // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e., the next repr is
// no closer to `v + 1 ulp` than the current repr. given `z(n) = plus1v_up - plus1w(n)`,
// this becomes `abs(z(n)) <= abs(z(n+1))`. again assuming that TC1 is false, we have
// `z(n) > 0`. we have two cases to consider:
// - when `z(n+1) < 0`:
// - TC3a: the precondition is `plus1v_up < plus1w(n) + 10^kappa`. assuming TC2 is
// false, `threshold >= plus1w(n) + 10^kappa` so it cannot overflow.
- // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e. `plus1v_up - plus1w(n) >=
+ // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e., `plus1v_up - plus1w(n) >=
// plus1w(n+1) - plus1v_up = plus1w(n) + 10^kappa - plus1v_up`. the negated TC1
// gives `plus1v_up > plus1w(n)`, so it cannot overflow or underflow when
// combined with TC3a.
// now we have the closest representation to `v` between `plus1` and `minus1`.
// this is too liberal, though, so we reject any `w(n)` not between `plus0` and `minus0`,
- // i.e. `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts
+ // i.e., `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts
// that `threshold = plus1 - minus1` and `plus1 - plus0 = minus0 - minus1 = 2 ulp`.
if 2 * ulp <= plus1w && plus1w <= threshold - 4 * ulp {
Some((buf.len(), exp))
return Some((len, exp));
}
- // otherwise we are doomed (i.e. some values between `v - 1 ulp` and `v + 1 ulp` are
+ // otherwise we are doomed (i.e., some values between `v - 1 ulp` and `v + 1 ulp` are
// rounding down and others are rounding up) and give up.
None
}
concat!("Negates self, overflowing if this is equal to the minimum value.
Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
-happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
+happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
minimum value will be returned again and `true` will be returned for an overflow happening.
# Examples
concat!("Computes the absolute value of `self`.
Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
-happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
+happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
for an overflow happening.
doc_comment! {
concat!("Returns the smallest power of two greater than or equal to `self`.
-When return value overflows (i.e. `self > (1 << (N-1))` for type
+When return value overflows (i.e., `self > (1 << (N-1))` for type
`uN`), it panics in debug mode and return value is wrapped to 0 in
release mode (the only situation in which method can return 0).
/// # Potential causes
///
/// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
-/// in the string e.g. when it is obtained from the standard input.
+/// in the string e.g., when it is obtained from the standard input.
/// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
///
/// [`str.trim()`]: ../../std/primitive.str.html#method.trim
doc_comment! {
concat!("Returns the smallest power of two greater than or equal to `self`.
-When return value overflows (i.e. `self > (1 << (N-1))` for type
+When return value overflows (i.e., `self > (1 << (N-1))` for type
`uN`), overflows to `2^N = 0`.
# Examples
/// is expected.
///
/// Use `Fn` as a bound when you want to accept a parameter of function-like
-/// type and need to call it repeatedly and without mutating state (e.g. when
+/// type and need to call it repeatedly and without mutating state (e.g., when
/// calling it concurrently). If you do not need such strict requirements, use
/// [`FnMut`] or [`FnOnce`] as bounds.
///
///
/// `FnMut` is implemented automatically by closures which take mutable
/// references to captured variables, as well as all types that implement
-/// [`Fn`], e.g. (safe) [function pointers][] (since `FnMut` is a supertrait of
+/// [`Fn`], e.g., (safe) [function pointers][] (since `FnMut` is a supertrait of
/// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`
/// implements `FnMut`, too.
///
/// implements `FnOnce`, it can only be called once.
///
/// `FnOnce` is implemented automatically by closure that might consume captured
-/// variables, as well as all types that implement [`FnMut`], e.g. (safe)
+/// variables, as well as all types that implement [`FnMut`], e.g., (safe)
/// [function pointers][] (since `FnOnce` is a supertrait of [`FnMut`]).
///
/// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of
//! should have some resemblance to multiplication (and share expected
//! properties like associativity).
//!
-//! Note that the `&&` and `||` operators short-circuit, i.e. they only
+//! Note that the `&&` and `||` operators short-circuit, i.e., they only
//! evaluate their second operand if it contributes to the result. Since this
//! behavior is not enforceable by traits, `&&` and `||` are not supported as
//! overloadable operators.
//! The following example uses [`Option`] to create an optional box of
//! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
//! `check_optional` function needs to use pattern matching to
-//! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or
+//! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
//! not ([`None`]).
//!
//! ```
//!
//! In order to prevent objects from moving, they must be pinned
//! by wrapping a pointer to the data in the [`Pin`] type. A pointer wrapped
-//! in a `Pin` is otherwise equivalent to its normal version, e.g. `Pin<Box<T>>`
+//! in a `Pin` is otherwise equivalent to its normal version, e.g., `Pin<Box<T>>`
//! and `Box<T>` work the same way except that the first is pinning the value
//! of `T` in place.
//!
/// dropped normally.
///
/// * It is friendlier to the optimizer to do this over [`ptr::read`] when
-/// dropping manually allocated memory (e.g. when writing Box/Rc/Vec),
+/// dropping manually allocated memory (e.g., when writing Box/Rc/Vec),
/// as the compiler doesn't need to prove that it's sound to elide the
/// copy.
///
///
/// The compiler shouldn't change the relative order or number of volatile
/// memory operations. However, volatile memory operations on zero-sized types
-/// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops
+/// (e.g., if a zero-sized type is passed to `read_volatile`) are no-ops
/// and may be ignored.
///
/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
///
/// The compiler shouldn't change the relative order or number of volatile
/// memory operations. However, volatile memory operations on zero-sized types
-/// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops
+/// (e.g., if a zero-sized type is passed to `write_volatile`) are no-ops
/// and may be ignored.
///
/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
/// Calculates the offset from a pointer.
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer using wrapping arithmetic.
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer (convenience for
/// `.offset((count as isize).wrapping_neg())`).
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer using wrapping arithmetic.
/// (convenience for `.wrapping_offset(count as isize)`)
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer using wrapping arithmetic.
/// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer.
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
}
/// Calculates the offset from a pointer using wrapping arithmetic.
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer (convenience for
/// `.offset((count as isize).wrapping_neg())`).
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer using wrapping arithmetic.
/// (convenience for `.wrapping_offset(count as isize)`)
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
/// Calculates the offset from a pointer using wrapping arithmetic.
/// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`)
///
- /// `count` is in units of T; e.g. a `count` of 3 represents a pointer
+ /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
fn mod_inv(x: usize, m: usize) -> usize {
/// Multiplicative modular inverse table modulo 2⁴ = 16.
///
- /// Note, that this table does not contain values where inverse does not exist (i.e. for
+ /// Note, that this table does not contain values where inverse does not exist (i.e., for
/// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
/// Modulo for which the `INV_TABLE_MOD_16` is intended.
// y = y * (2 - xy) mod n
//
// Note, that we use wrapping operations here intentionally – the original formula
- // uses e.g. subtraction `mod n`. It is entirely fine to do them `mod
+ // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
// usize::max_value()` instead, because we take the result `mod n` at the end
// anyway.
inverse = inverse.wrapping_mul(
}
/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
-// NB: This impl is unnecessary, but should provide better error messages.
+// N.B., this impl is unnecessary, but should provide better error messages.
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> !Send for NonNull<T> { }
/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
-// NB: This impl is unnecessary, but should provide better error messages.
+// N.B., this impl is unnecessary, but should provide better error messages.
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> !Sync for NonNull<T> { }
/// `Box<dyn AnotherTrait>`.
///
/// `TraitObject` is guaranteed to match layouts, but it is not the
-/// type of trait objects (e.g. the fields are not directly accessible
+/// type of trait objects (e.g., the fields are not directly accessible
/// on a `&SomeTrait`) nor does it control that layout (changing the
/// definition will not change the layout of a `&SomeTrait`). It is
/// only designed to be used by unsafe code that needs to manipulate
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Slice management and manipulation
+//! Slice management and manipulation.
//!
//! For more details see [`std::slice`].
//!
///
/// # Examples
///
- /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
+ /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
/// `[20, 60, 50]`):
///
/// ```
/// # Examples
///
/// Print the slice split once, starting from the end, by numbers divisible
- /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
+ /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
///
/// ```
/// let v = [10, 40, 30, 20, 60, 50];
/// Sorts the slice, but may not preserve the order of equal elements.
///
- /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
- /// and `O(n log n)` worst-case.
+ /// This sort is unstable (i.e., may reorder equal elements), in-place
+ /// (i.e., does not allocate), and `O(n log n)` worst-case.
///
/// # Current implementation
///
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
/// deterministic behavior.
///
- /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
+ /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
/// slice consists of several concatenated sorted sequences.
///
/// # Examples
/// Sorts the slice with a comparator function, but may not preserve the order of equal
/// elements.
///
- /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
- /// and `O(n log n)` worst-case.
+ /// This sort is unstable (i.e., may reorder equal elements), in-place
+ /// (i.e., does not allocate), and `O(n log n)` worst-case.
///
/// The comparator function must define a total ordering for the elements in the slice. If
/// the ordering is not total, the order of the elements is unspecified. An order is a
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
/// deterministic behavior.
///
- /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
+ /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
/// slice consists of several concatenated sorted sequences.
///
/// # Examples
/// Sorts the slice with a key extraction function, but may not preserve the order of equal
/// elements.
///
- /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
- /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
+ /// This sort is unstable (i.e., may reorder equal elements), in-place
+ /// (i.e., does not allocate), and `O(m n log(m n))` worst-case, where the key function is
+ /// `O(m)`.
///
/// # Current implementation
///
#[inline]
fn index(self, slice: &[T]) -> &T {
- // NB: use intrinsic indexing
+ // N.B., use intrinsic indexing
&(*slice)[self]
}
#[inline]
fn index_mut(self, slice: &mut [T]) -> &mut T {
- // NB: use intrinsic indexing
+ // N.B., use intrinsic indexing
&mut (*slice)[self]
}
}
#[inline]
fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 }
-/// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the
+/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
/// bits `10`).
#[inline]
fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 }
let found_char = index - shift;
if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size)) {
if slice == &self.utf8_encoded[0..self.utf8_size] {
- // move finger to before the character found (i.e. at its start index)
+ // move finger to before the character found (i.e., at its start index)
self.finger_back = found_char;
return Some((self.finger_back, self.finger_back + self.utf8_size));
}
It can be proven that the following is an equivalent definition of a local period
for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for
all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are
- defined. (i.e. i > 0 and i + r < |x|).
+ defined. (i.e., i > 0 and i + r < |x|).
Using the above reformulation, it is easy to prove that
/// # Unsafety
///
/// This function is unsafe to call because it's asserting the `UnsafeWake`
- /// value is in a consistent state, i.e. hasn't been dropped.
+ /// value is in a consistent state, i.e., hasn't been dropped.
unsafe fn clone_raw(&self) -> Waker;
/// Drops this instance of `UnsafeWake`, deallocating resources
/// # Unsafety
///
/// This function is unsafe to call because it's asserting the `UnsafeWake`
- /// value is in a consistent state, i.e. hasn't been dropped.
+ /// value is in a consistent state, i.e., hasn't been dropped.
unsafe fn drop_raw(&self);
/// Indicates that the associated task is ready to make progress and should
/// # Unsafety
///
/// This function is unsafe to call because it's asserting the `UnsafeWake`
- /// value is in a consistent state, i.e. hasn't been dropped.
+ /// value is in a consistent state, i.e., hasn't been dropped.
unsafe fn wake(&self);
/// Indicates that the associated task is ready to make progress and should
/// # Unsafety
///
/// This function is unsafe to call because it's asserting the `UnsafeWake`
- /// value is in a consistent state, i.e. hasn't been dropped, and that the
+ /// value is in a consistent state, i.e., hasn't been dropped, and that the
/// `UnsafeWake` hasn't moved from the thread on which it was created.
unsafe fn wake_local(&self) {
self.wake()
// Take a float literal, turn it into a string in various ways (that are all trusted
// to be correct) and see if those strings are parsed back to the value of the literal.
-// Requires a *polymorphic literal*, i.e. one that can serve as f64 as well as f32.
+// Requires a *polymorphic literal*, i.e., one that can serve as f64 as well as f32.
macro_rules! test_literal {
($x: expr) => ({
let x32: f32 = $x;
// this is of course very stressful (and thus should be behind an `#[ignore]` attribute),
// but with `-C opt-level=3 -C lto` this only takes about an hour or so.
- // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e. all finite ranges
+ // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e., all finite ranges
let (npassed, nignored) = iterate("f32_exhaustive_equivalence_test",
k, 0x7f7f_ffff, f, g, |i: usize| {
///
/// This method does **not** return the length of the duration when
/// represented by milliseconds. The returned number always represents a
- /// fractional portion of a second (i.e. it is less than one thousand).
+ /// fractional portion of a second (i.e., it is less than one thousand).
///
/// # Examples
///
///
/// This method does **not** return the length of the duration when
/// represented by microseconds. The returned number always represents a
- /// fractional portion of a second (i.e. it is less than one million).
+ /// fractional portion of a second (i.e., it is less than one million).
///
/// # Examples
///
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
- /// fractional portion of a second (i.e. it is less than one billion).
+ /// fractional portion of a second (i.e., it is less than one billion).
///
/// # Examples
///
//! Generate files suitable for use with [Graphviz](http://www.graphviz.org/)
//!
-//! The `render` function generates output (e.g. an `output.dot` file) for
+//! The `render` function generates output (e.g., an `output.dot` file) for
//! use with [Graphviz](http://www.graphviz.org/) by walking a labeled
//! graph. (Graphviz can then automatically lay out the nodes and edges
//! of the graph, and also optionally render the graph as an image or
//! expressiveness of the [DOT language](
//! http://www.graphviz.org/doc/info/lang.html). For example, there are
//! many [attributes](http://www.graphviz.org/content/attrs) related to
-//! providing layout hints (e.g. left-to-right versus top-down, which
+//! providing layout hints (e.g., left-to-right versus top-down, which
//! algorithm to use, etc). The current intention of this library is to
//! emit a human-readable .dot file with very regular structure suitable
//! for easy post-processing.
// implement a Labelling service) that I have encountered is that it
// makes it impossible to use types outside of the current crate
// directly as Nodes/Edges; you need to wrap them in newtype'd
-// structs. See e.g. the `No` and `Ed` structs in the examples. (In
+// structs. See e.g., the `No` and `Ed` structs in the examples. (In
// practice clients using a graph in some other crate would need to
// provide some sort of adapter shim over the graph anyway to
// interface with this library).
/// The caller must ensure that the input conforms to an
/// identifier format: it must be a non-empty string made up of
/// alphanumeric or underscore characters, not beginning with a
- /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
+ /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`).
///
/// (Note: this format is a strict subset of the `ID` format
/// defined by the DOT language. This function may change in the
DwarfReader { ptr }
}
- // DWARF streams are packed, so e.g. a u32 would not necessarily be aligned
+ // DWARF streams are packed, so e.g., a u32 would not necessarily be aligned
// on a 4-byte boundary. This may cause problems on platforms with strict
// alignment requirements. By wrapping data in a "packed" struct, we are
// telling the backend to generate "misalignment-safe" code.
//!
//! In both phases the unwinder walks stack frames from top to bottom using
//! information from the stack frame unwind sections of the current process's
-//! modules ("module" here refers to an OS module, i.e. an executable or a
+//! modules ("module" here refers to an OS module, i.e., an executable or a
//! dynamic library).
//!
//! For each stack frame, it invokes the associated "personality routine", whose
// Each module's image contains a frame unwind info section (usually
// ".eh_frame"). When a module is loaded/unloaded into the process, the
// unwinder must be informed about the location of this section in memory. The
-// methods of achieving that vary by the platform. On some (e.g. Linux), the
+// methods of achieving that vary by the platform. On some (e.g., Linux), the
// unwinder can discover unwind info sections on its own (by dynamically
// enumerating currently loaded modules via the dl_iterate_phdr() API and
// finding their ".eh_frame" sections); Others, like Windows, require modules
//!
//! On Windows (currently only on MSVC), the default exception handling
//! mechanism is Structured Exception Handling (SEH). This is quite different
-//! than Dwarf-based exception handling (e.g. what other unix platforms use) in
+//! than Dwarf-based exception handling (e.g., what other unix platforms use) in
//! terms of compiler internals, so LLVM is required to have a good deal of
//! extra support for SEH.
//!
})
}
-// This is required by the compiler to exist (e.g. it's a lang item), but
+// This is required by the compiler to exist (e.g., it's a lang item), but
// it's never actually called by the compiler because __C_specific_handler
// or _except_handler3 is the personality function that is always used.
// Hence this is just an aborting stub.
Connected(Bridge<'a>),
/// Access to the bridge is being exclusively acquired
- /// (e.g. during `BridgeState::with`).
+ /// (e.g., during `BridgeState::with`).
InUse,
}
/// The state will be restored after `f` exits, even
/// by panic, including modifications made to it by `f`.
///
- /// NB: while `f` is running, the thread-local state
+ /// N.B., while `f` is running, the thread-local state
/// is `BridgeState::InUse`.
fn with<R>(f: impl FnOnce(&mut BridgeState) -> R) -> R {
BRIDGE_STATE.with(|state| {
/// which may be using a different `proc_macro` from the one
/// used by the server, but can be interacted with compatibly.
///
-/// NB: `F` must have FFI-friendly memory layout (e.g. a pointer).
+/// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer).
/// The call ABI of function pointers used for `F` doesn't
/// need to match between server and client, since it's only
/// passed between them and (eventually) called by the client.
//! Serialization (with C ABI buffers) and unique integer handles are employed
//! to allow safely interfacing between two copies of `proc_macro` built
//! (from the same source) by different compilers with potentially mismatching
-//! Rust ABIs (e.g. stage0/bin/rustc vs stage1/bin/rustc during bootstrap).
+//! Rust ABIs (e.g., stage0/bin/rustc vs stage1/bin/rustc during bootstrap).
#![deny(unsafe_code)]
type Out;
}
-/// Type lambda taking a lifetime, i.e. `Lifetime -> Type`.
+/// Type lambda taking a lifetime, i.e., `Lifetime -> Type`.
pub trait LambdaL: for<'a> ApplyL<'a> {}
impl<T: for<'a> ApplyL<'a>> LambdaL for T {}
use super::client::HandleStore;
/// Declare an associated item of one of the traits below, optionally
-/// adjusting it (i.e. adding bounds to types and default bodies to methods).
+/// adjusting it (i.e., adding bounds to types and default bodies to methods).
macro_rules! associated_item {
(type TokenStream) =>
(type TokenStream: 'static + Clone;);
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for TokenStream {
use {bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream};
/// An iterator over `TokenStream`'s `TokenTree`s.
- /// The iteration is "shallow", e.g. the iterator doesn't recurse into delimited groups,
+ /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
/// and returns whole groups as token trees.
#[derive(Clone)]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
#[unstable(feature = "proc_macro_span", issue = "54725")]
impl Eq for SourceFile {}
-/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
+/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
#[derive(Clone)]
pub enum TokenTree {
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for TokenTree {
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for Group {
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub enum Spacing {
- /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
+ /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
Alone,
- /// E.g. `+` is `Joint` in `+=` or `'#`.
+ /// e.g., `+` is `Joint` in `+=` or `'#`.
/// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
Joint,
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for Punct {
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for Ident {
}
}
-// NB: the bridge only provides `to_string`, implement `fmt::Display`
+// N.B., the bridge only provides `to_string`, implement `fmt::Display`
// based on it (the reverse of the usual relationship between the two).
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ToString for Literal {
}
hir::ExprKind::Index(ref l, ref r) |
- hir::ExprKind::Binary(_, ref l, ref r) => { // NB: && and || handled earlier
+ hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier
self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
}
//! fully identify a dependency node, even across multiple compilation sessions.
//! In other words, the value of the fingerprint does not depend on anything
//! that is specific to a given compilation session, like an unpredictable
-//! interning key (e.g. NodeId, DefId, Symbol) or the numeric value of a
+//! interning key (e.g., NodeId, DefId, Symbol) or the numeric value of a
//! pointer. The concept behind this could be compared to how git commit hashes
//! uniquely identify a given commit and has a few advantages:
//!
//! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
//! implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
//! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
-//! memory without any post-processing (e.g. "abomination-style" pointer
+//! memory without any post-processing (e.g., "abomination-style" pointer
//! reconstruction).
//! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
//! refer to things that do not exist anymore. In previous implementations
use ty::subst::Substs;
// erase!() just makes tokens go away. It's used to specify which macro argument
-// is repeated (i.e. which sub-expression of the macro we are in) but don't need
+// is repeated (i.e., which sub-expression of the macro we are in) but don't need
// to actually use any of the arguments.
macro_rules! erase {
($x:tt) => ({})
We cannot create an object of type `Box<Foo>` or `&Foo` since in this case
`Self` would not be `Sized`.
-Generally, `Self : Sized` is used to indicate that the trait should not be used
+Generally, `Self: Sized` is used to indicate that the trait should not be used
as a trait object. If the trait comes from your own crate, consider removing
this restriction.
```
If this is not an option, consider replacing the type parameter with another
-trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
-of types you intend to feed to this method is limited, consider manually listing
-out the methods of different types.
+trait object (e.g., if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the
+number of types you intend to feed to this method is limited, consider manually
+listing out the methods of different types.
### Method has no receiver
```
Lang items are already implemented in the standard library. Unless you are
-writing a free-standing application (e.g. a kernel), you do not need to provide
+writing a free-standing application (e.g., a kernel), you do not need to provide
them yourself.
You can build a free-standing crate by adding `#![no_std]` to the crate
match with any of the type parameters or the string `Self`. This might happen
if you misspelled a type parameter, or if you intended to use literal curly
braces. If it is the latter, escape the curly braces with a second curly brace
-of the same type; e.g. a literal `{` is `{{`.
+of the same type; e.g., a literal `{` is `{{`.
"##,
E0231: r##"
E0271: r##"
This is because of a type mismatch between the associated type of some
-trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
+trait (e.g., `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
and another type `U` that is required to be equal to `T::Bar`, but is not.
Examples follow.
won't work on enums.
`#[repr(simd)]` will give a struct consisting of a homogeneous series of machine
-types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
+types (i.e., `u8`, `i32`, etc) a representation that permits vectorization via
SIMD. This doesn't make much sense for enums since they don't consist of a
single list of data.
"##,
pub enum Def {
// Type namespace
Mod(DefId),
- Struct(DefId), // DefId refers to NodeId of the struct itself
+ Struct(DefId), // `DefId` refers to `NodeId` of the struct itself
Union(DefId),
Enum(DefId),
Variant(DefId),
PrimTy(hir::PrimTy),
TyParam(DefId),
SelfTy(Option<DefId> /* trait */, Option<DefId> /* impl */),
- ToolMod, // e.g. `rustfmt` in `#[rustfmt::skip]`
+ ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
// Value namespace
Fn(DefId),
Const(DefId),
Static(DefId, bool /* is_mutbl */),
- StructCtor(DefId, CtorKind), // DefId refers to NodeId of the struct's constructor
- VariantCtor(DefId, CtorKind), // DefId refers to the enum variant
- SelfCtor(DefId /* impl */), // DefId refers to the impl
+ StructCtor(DefId, CtorKind), // `DefId` refers to `NodeId` of the struct's constructor
+ VariantCtor(DefId, CtorKind), // `DefId` refers to the enum variant
+ SelfCtor(DefId /* impl */), // `DefId` refers to the impl
Method(DefId),
AssociatedConst(DefId),
Local(ast::NodeId),
- Upvar(ast::NodeId, // node id of closed over local
- usize, // index in the freevars list of the closure
+ Upvar(ast::NodeId, // `NodeId` of closed over local
+ usize, // index in the `freevars` list of the closure
ast::NodeId), // expr node that creates the closure
Label(ast::NodeId),
// Macro namespace
Macro(DefId, MacroKind),
- NonMacroAttr(NonMacroAttrKind), // e.g. `#[inline]` or `#[rustfmt::skip]`
+ NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
// Both namespaces
Err,
impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
type Output = T;
+
fn index(&self, ns: Namespace) -> &T {
match ns {
ValueNS => &self.value_ns,
ast::VariantData::Struct(..) => CtorKind::Fictive,
}
}
+
pub fn from_hir(vdata: &hir::VariantData) -> CtorKind {
match *vdata {
hir::VariantData::Tuple(..) => CtorKind::Fn,
/// Each method of the Visitor trait is a hook to be potentially
/// overridden. Each method's default implementation recursively visits
/// the substructure of the input via the corresponding `walk` method;
-/// e.g. the `visit_mod` method by default calls `intravisit::walk_mod`.
+/// e.g., the `visit_mod` method by default calls `intravisit::walk_mod`.
///
/// Note that this visitor does NOT visit nested items by default
/// (this is why the module is called `intravisit`, to distinguish it
item.id)
}
ItemKind::Mod(ref module) => {
- // visit_mod() takes care of visiting the Item's NodeId
+ // `visit_mod()` takes care of visiting the `Item`'s `NodeId`.
visitor.visit_mod(module, item.span, item.id)
}
ItemKind::ForeignMod(ref foreign_module) => {
}
ItemKind::Enum(ref enum_definition, ref type_parameters) => {
visitor.visit_generics(type_parameters);
- // visit_enum_def() takes care of visiting the Item's NodeId
+ // `visit_enum_def()` takes care of visiting the `Item`'s `NodeId`.
visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span)
}
ItemKind::Impl(
}
pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) {
- // NB: Deliberately force a compilation error if/when new fields are added.
+ // N.B., deliberately force a compilation error if/when new fields are added.
let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref;
visitor.visit_nested_trait_item(id);
visitor.visit_ident(ident);
}
pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem) {
- // NB: Deliberately force a compilation error if/when new fields are added.
+ // N.B., deliberately force a compilation error if/when new fields are added.
let ImplItem {
id: _,
hir_id: _,
}
pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) {
- // NB: Deliberately force a compilation error if/when new fields are added.
+ // N.B., deliberately force a compilation error if/when new fields are added.
let ImplItemRef { id, ident, ref kind, span: _, ref vis, ref defaultness } = *impl_item_ref;
visitor.visit_nested_impl_item(id);
visitor.visit_ident(ident);
pub struct LoweringContext<'a> {
crate_root: Option<&'static str>,
- // Use to assign ids to hir nodes that do not directly correspond to an ast node
+ // Used to assign ids to HIR nodes that do not directly correspond to an AST node.
sess: &'a Session,
cstore: &'a dyn CrateStore,
anonymous_lifetime_mode: AnonymousLifetimeMode,
// Used to create lifetime definitions from in-band lifetime usages.
- // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
+ // e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
// When a named lifetime is encountered in a function or impl header and
// has not been defined
- // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
+ // (i.e., it doesn't appear in the in_scope_lifetimes list), it is added
// to this list. The results of this list are then added to the list of
// lifetime definitions in the corresponding impl or function generics.
lifetimes_to_define: Vec<(Span, ParamName)>,
is_value: bool,
) -> hir::Path;
- /// Obtain the resolution for a node id
+ /// Obtain the resolution for a node-id.
fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution>;
/// Obtain the possible resolutions for the given `use` statement.
/// This should only return `None` during testing.
fn definitions(&mut self) -> &mut Definitions;
- /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves
- /// it based on `is_value`.
+ /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and
+ /// resolves it based on `is_value`.
fn resolve_str_path(
&mut self,
span: Span,
///
/// We optionally store a `DefId` for the parent item here so we can look up necessary
/// information later. It is `None` when no information about the context should be stored,
- /// e.g. for consts and statics.
+ /// e.g., for consts and statics.
Existential(Option<DefId>),
/// `impl Trait` is not accepted in this position.
fn lower_crate(mut self, c: &Crate) -> hir::Crate {
/// Full-crate AST visitor that inserts into a fresh
/// `LoweringContext` any information that may be
- /// needed from arbitrary locations in the crate.
- /// E.g. The number of lifetime generic parameters
+ /// needed from arbitrary locations in the crate,
+ /// e.g., the number of lifetime generic parameters
/// declared for every type and trait definition.
struct MiscCollector<'lcx, 'interner: 'lcx> {
lctx: &'lcx mut LoweringContext<'interner>,
debug
);
}
- // Always allocate the first HirId for the owner itself
+ // Always allocate the first `HirId` for the owner itself.
self.lower_node_id_with_owner(owner, owner)
}
let existing_hir_id = self.node_id_to_hir_id[ast_node_id];
if existing_hir_id == hir::DUMMY_HIR_ID {
- // Generate a new HirId
+ // Generate a new `HirId`.
let hir_id = alloc_hir_id(self);
self.node_id_to_hir_id[ast_node_id] = hir_id;
LoweredNodeId {
ret
}
- /// This method allocates a new HirId for the given NodeId and stores it in
- /// the LoweringContext's NodeId => HirId map.
- /// Take care not to call this method if the resulting HirId is then not
+ /// This method allocates a new `HirId` for the given `NodeId` and stores it in
+ /// the `LoweringContext`'s `NodeId => HirId` map.
+ /// Take care not to call this method if the resulting `HirId` is then not
/// actually used in the HIR, as that would trigger an assertion in the
- /// HirIdValidator later on, which makes sure that all NodeIds got mapped
- /// properly. Calling the method twice with the same NodeId is fine though.
+ /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
+ /// properly. Calling the method twice with the same `NodeId` is fine though.
fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId {
self.lower_node_id_generic(ast_node_id, |this| {
let &mut (def_index, ref mut local_id_counter) =
),
};
- // Add a definition for the in-band lifetime def
+ // Add a definition for the in-band lifetime def.
self.resolver.definitions().create_def_with_parent(
parent_id.index,
def_node_id,
fn lower_attr(&mut self, attr: &Attribute) -> Attribute {
// Note that we explicitly do not walk the path. Since we don't really
// lower attributes (we use the AST version) there is nowhere to keep
- // the HirIds. We don't actually need HIR version of attributes anyway.
+ // the `HirId`s. We don't actually need HIR version of attributes anyway.
Attribute {
id: attr.id,
style: attr.style,
}
ImplTraitContext::Universal(in_band_ty_params) => {
self.lower_node_id(def_node_id);
- // Add a definition for the in-band Param
+ // Add a definition for the in-band `Param`.
let def_index = self
.resolver
.definitions()
bounds,
ImplTraitContext::Universal(in_band_ty_params),
);
- // Set the name to `impl Bound1 + Bound2`
+ // Set the name to `impl Bound1 + Bound2`.
let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span);
in_band_ty_params.push(hir::GenericParam {
id: def_node_id,
impl_trait_fn: fn_def_id,
});
let exist_ty_id = lctx.lower_node_id(exist_ty_node_id);
- // Generate an `existential type Foo: Trait;` declaration
+ // Generate an `existential type Foo: Trait;` declaration.
trace!("creating existential type with id {:#?}", exist_ty_id);
trace!("exist ty def index: {:#?}", exist_ty_def_index);
// does not actually exist in the AST.
lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
- // `impl Trait` now just becomes `Foo<'a, 'b, ..>`
+ // `impl Trait` now just becomes `Foo<'a, 'b, ..>`.
hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
})
}
) -> (HirVec<hir::GenericArg>, HirVec<hir::GenericParam>) {
// This visitor walks over impl trait bounds and creates defs for all lifetimes which
// appear in the bounds, excluding lifetimes that are created within the bounds.
- // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>`
+ // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`.
struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
context: &'r mut LoweringContext<'a>,
parent: DefIndex,
}
fn visit_ty(&mut self, t: &'v hir::Ty) {
- // Don't collect elided lifetimes used inside of `fn()` syntax
+ // Don't collect elided lifetimes used inside of `fn()` syntax.
if let hir::TyKind::BareFn(_) = t.node {
let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
self.collect_elided_lifetimes = false;
}
fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
- // Record the introduction of 'a in `for<'a> ...`
+ // Record the introduction of 'a in `for<'a> ...`.
if let hir::GenericParamKind::Lifetime { .. } = param.kind {
// Introduce lifetimes one at a time so that we can handle
- // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
+ // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`.
let lt_name = hir::LifetimeName::Param(param.name);
self.currently_bound_lifetimes.push(lt_name);
}
hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => {
if self.collect_elided_lifetimes {
// Use `'_` for both implicit and underscore lifetimes in
- // `abstract type Foo<'_>: SomeTrait<'_>;`
+ // `abstract type Foo<'_>: SomeTrait<'_>;`.
hir::LifetimeName::Underscore
} else {
return;
{
ParenthesizedGenericArgs::Ok
}
- // Avoid duplicated errors
+ // Avoid duplicated errors.
Def::Err => ParenthesizedGenericArgs::Ok,
// An error
Def::Struct(..)
});
// Simple case, either no projections, or only fully-qualified.
- // E.g. `std::mem::size_of` or `<I as Iterator>::Item`.
+ // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
if resolution.unresolved_segments() == 0 {
return hir::QPath::Resolved(qself, path);
}
// Create the innermost type that we're projecting from.
let mut ty = if path.segments.is_empty() {
// If the base path is empty that means there exists a
- // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`.
+ // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
qself.expect("missing QSelf for <T>::...")
} else {
// Otherwise, the base path is an implicit `Self` type path,
- // e.g. `Vec` in `Vec::new` or `<I as Iterator>::Item` in
+ // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
// `<I as Iterator>::Item::default`.
let new_id = self.next_id();
P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
// Anything after the base path are associated "extensions",
// out of which all but the last one are associated types,
- // e.g. for `std::vec::Vec::<T>::IntoIter::Item::clone`:
+ // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
// * base path is `std::vec::Vec<T>`
// * "extensions" are `IntoIter`, `Item` and `clone`
// * type nodes are:
ty = P(self.ty_path(new_id, p.span, qpath));
}
- // Should've returned in the for loop above.
+ // We should've returned in the for loop above.
span_bug!(
p.span,
"lower_qpath: no final extension segment in {}..{}",
let no_bindings = generic_args.bindings.is_empty();
let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings {
// If there are no (non-implicit) generic args or associated-type
- // bindings, our suggestion includes the angle brackets
+ // bindings, our suggestion includes the angle brackets.
(true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
} else {
// Otherwise—sorry, this is kind of gross—we need to infer the
- // place to splice in the `'_, ` from the generics that do exist
+ // place to splice in the `'_, ` from the generics that do exist.
let first_generic_span = first_generic_span
.expect("already checked that type args or bindings exist");
(false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
return_impl_trait_id: NodeId,
) -> hir::FunctionRetTy {
// Get lifetimes used in the input arguments to the function. Our output type must also
- // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed
- // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither
- // is a subset of the other. We really want some new lifetime that is a subset of all input
- // lifetimes, but that doesn't exist at the moment.
+ // have the same lifetime.
+ // FIXME(cramertj): multiple different lifetimes are not allowed because
+ // `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither is a subset
+ // of the other. We really want some new lifetime that is a subset of all input lifetimes,
+ // but that doesn't exist at the moment.
struct AsyncFnLifetimeCollector<'r, 'a: 'r> {
context: &'r mut LoweringContext<'a>,
- // Lifetimes bound by HRTB
+ // Lifetimes bound by HRTB.
currently_bound_lifetimes: Vec<hir::LifetimeName>,
// Whether to count elided lifetimes.
// Disabled inside of `Fn` or `fn` syntax.
}
fn visit_ty(&mut self, t: &'v hir::Ty) {
- // Don't collect elided lifetimes used inside of `fn()` syntax
+ // Don't collect elided lifetimes used inside of `fn()` syntax.
if let &hir::TyKind::BareFn(_) = &t.node {
let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
self.collect_elided_lifetimes = false;
GenericParamKind::Type { ref default, .. } => {
// Don't expose `Self` (recovered "keyword used as ident" parse error).
// `rustc::ty` expects `Self` to be only used for a trait's `Self`.
- // Instead, use gensym("Self") to create a distinct name that looks the same.
+ // Instead, use `gensym("Self")` to create a distinct name that looks the same.
let ident = if param.ident.name == keywords::SelfUpper.name() {
param.ident.gensym()
} else {
-> hir::Generics
{
// Collect `?Trait` bounds in where clause and move them to parameter definitions.
- // FIXME: This could probably be done with less rightward drift. Also looks like two control
+ // FIXME: this could probably be done with less rightward drift. Also looks like two control
// paths where report_error is called are also the only paths that advance to after
// the match statement, so the error reporting could probably just be moved there.
let mut add_bounds: NodeMap<Vec<_>> = Default::default();
.iter()
.filter_map(|bound| match *bound {
// Ignore `?Trait` bounds.
- // Tthey were copied into type parameters already.
+ // They were copied into type parameters already.
GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
_ => Some(this.lower_param_bound(
bound,
id: self.lower_node_id(f.id).node_id,
ident: match f.ident {
Some(ident) => ident,
- // FIXME(jseyfried) positional field hygiene
+ // FIXME(jseyfried): positional field hygiene
None => Ident::new(Symbol::intern(&index.to_string()), f.span),
},
vis: self.lower_visibility(&f.vis, None),
}
// [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to
- // not cause an assertion failure inside the `lower_defaultness` function
+ // not cause an assertion failure inside the `lower_defaultness` function.
}
fn lower_use_tree(
/// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated
/// many times in the HIR tree; for each occurrence, we need to assign distinct
- /// node-ids. (See e.g. #56128.)
+ /// node-ids. (See e.g., #56128.)
fn renumber_segment_ids(&mut self, path: &P<hir::Path>) -> P<hir::Path> {
debug!("renumber_segment_ids(path = {:?})", path);
let mut path = path.clone();
let else_opt = else_opt.as_ref().map(|els| {
match els.node {
ExprKind::IfLet(..) => {
- // wrap the if-let expr in a block
+ // Wrap the `if let` expr in a block.
let span = els.span;
let els = P(self.lower_expr(els));
let LoweredNodeId { node_id, hir_id } = self.next_id();
let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
self.with_new_scopes(|this| {
- // FIXME(cramertj) allow `async` non-`move` closures with
+ // FIXME(cramertj): allow `async` non-`move` closures with arguments.
if capture_clause == CaptureBy::Ref &&
!decl.inputs.is_empty()
{
are not currently supported",
)
.help("consider using `let` statements to manually capture \
- variables by reference before entering an \
- `async move` closure")
+ variables by reference before entering an \
+ `async move` closure")
.emit();
}
// Transform `async |x: u8| -> X { ... }` into
- // `|x: u8| future_from_generator(|| -> X { ... })`
+ // `|x: u8| future_from_generator(|| -> X { ... })`.
let body_id = this.lower_body(Some(&outer_decl), |this| {
let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
Some(&**ty)
ExprKind::Index(ref el, ref er) => {
hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
}
- // Desugar `<start>..=<end>` to `std::ops::RangeInclusive::new(<start>, <end>)`
+ // Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
let id = self.next_id();
let e1 = self.lower_expr(e1);
),
ExprKind::Paren(ref ex) => {
let mut ex = self.lower_expr(ex);
- // include parens in span, but only if it is a super-span.
+ // Include parens in span, but only if it is a super-span.
if e.span.contains(ex.span) {
ex.span = e.span;
}
- // merge attributes into the inner expression.
+ // Merge attributes into the inner expression.
let mut attrs = e.attrs.clone();
attrs.extend::<Vec<_>>(ex.attrs.into());
ex.attrs = attrs;
hir::ExprKind::Yield(P(expr))
}
- // Desugar ExprIfLet
- // From: `if let <pat> = <sub_expr> <body> [<else_opt>]`
+ // Desugar `ExprIfLet`
+ // from: `if let <pat> = <sub_expr> <body> [<else_opt>]`
ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => {
// to:
//
)
}
- // Desugar ExprWhileLet
- // From: `[opt_ident]: while let <pat> = <sub_expr> <body>`
+ // Desugar `ExprWhileLet`
+ // from: `[opt_ident]: while let <pat> = <sub_expr> <body>`
ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => {
// to:
//
self.lower_label(opt_label),
hir::LoopSource::WhileLet,
);
- // add attributes to the outer returned expr node
+ // Add attributes to the outer returned expr node.
loop_expr
}
- // Desugar ExprForLoop
- // From: `[opt_ident]: for <pat> in <head> <body>`
+ // Desugar `ExprForLoop`
+ // from: `[opt_ident]: for <pat> in <head> <body>`
ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
// to:
//
));
// `{ let _result = ...; _result }`
- // underscore prevents an unused_variables lint if the head diverges
+ // Underscore prevents an `unused_variables` lint if the head diverges.
let result_ident = self.str_to_ident("_result");
let (let_stmt, let_stmt_binding) =
self.stmt_let(e.span, false, result_ident, match_expr);
let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding));
let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result)));
- // add the attributes to the outer returned expr node
+ // Add the attributes to the outer returned expr node.
return self.expr_block(block, e.attrs.clone());
}
- // Desugar ExprKind::Try
- // From: `<expr>?`
+ // Desugar `ExprKind::Try`
+ // from: `<expr>?`
ExprKind::Try(ref sub_expr) => {
- // to:
+ // into:
//
// match Try::into_result(<expr>) {
// Ok(val) => #[allow(unreachable_code)] val,
let unstable_span =
self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span);
- // Try::into_result(<expr>)
+ // `Try::into_result(<expr>)`
let discr = {
// expand <expr>
let sub_expr = self.lower_expr(sub_expr);
P(self.expr_call(e.span, path, hir_vec![sub_expr]))
};
- // #[allow(unreachable_code)]
+ // `#[allow(unreachable_code)]`
let attr = {
- // allow(unreachable_code)
+ // `allow(unreachable_code)`
let allow = {
let allow_ident = Ident::from_str("allow").with_span_pos(e.span);
let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span);
};
let attrs = vec![attr];
- // Ok(val) => #[allow(unreachable_code)] val,
+ // `Ok(val) => #[allow(unreachable_code)] val,`
let ok_arm = {
let val_ident = self.str_to_ident("val");
let val_pat = self.pat_ident(e.span, val_ident);
self.arm(hir_vec![ok_pat], val_expr)
};
- // Err(err) => #[allow(unreachable_code)]
- // return Try::from_error(From::from(err)),
+ // `Err(err) => #[allow(unreachable_code)]
+ // return Try::from_error(From::from(err)),`
let err_arm = {
let err_ident = self.str_to_ident("err");
let err_local = self.pat_ident(e.span, err_ident);
/// error, depending on the mode.
fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> {
match self.anonymous_lifetime_mode {
- // NB. We intentionally ignore the create-parameter mode here
+ // N.B., We intentionally ignore the create-parameter mode here
// and instead "pass through" to resolve-lifetimes, which will then
// report an error. This is because we don't want to support
// impl elision for deprecated forms like
//! it captures a common set of attributes that all "function-like
//! things" (represented by `FnLike` instances) share. For example,
//! all `FnLike` instances have a type signature (be it explicit or
-//! inferred). And all `FnLike` instances have a body, i.e. the code
+//! inferred). And all `FnLike` instances have a body, i.e., the code
//! that is run when the function-like thing it represents is invoked.
//!
//! With the above abstraction in place, one can treat the program
/// More specifically, it is one of either:
///
/// - A function item,
-/// - A closure expr (i.e. an ExprKind::Closure), or
+/// - A closure expr (i.e., an ExprKind::Closure), or
/// - The default implementation for a trait method.
///
/// To construct one, use the `Code::from_node` function.
}
}
-
/// The definition table containing node definitions.
-/// It holds the DefPathTable for local DefIds/DefPaths and it also stores a
-/// mapping from NodeIds to local DefIds.
+/// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
+/// mapping from `NodeId`s to local `DefId`s.
#[derive(Clone, Default)]
pub struct Definitions {
table: DefPathTable,
match node {
Node::Item(item) => {
- let def_id = || {
- self.local_def_id(item.id)
- };
+ let def_id = || self.local_def_id(item.id);
match item.node {
ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)),
pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
self.read(id.node_id);
- // NB: intentionally bypass `self.forest.krate()` so that we
+ // N.B., intentionally bypass `self.forest.krate()` so that we
// do not trigger a read of the whole krate here
self.forest.krate.trait_item(id)
}
pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
self.read(id.node_id);
- // NB: intentionally bypass `self.forest.krate()` so that we
+ // N.B., intentionally bypass `self.forest.krate()` so that we
// do not trigger a read of the whole krate here
self.forest.krate.impl_item(id)
}
pub fn body(&self, id: BodyId) -> &'hir Body {
self.read(id.node_id);
- // NB: intentionally bypass `self.forest.krate()` so that we
+ // N.B., intentionally bypass `self.forest.krate()` so that we
// do not trigger a read of the whole krate here
self.forest.krate.body(id)
}
}
/// Returns the `NodeId` that corresponds to the definition of
- /// which this is the body of, i.e. a `fn`, `const` or `static`
+ /// which this is the body of, i.e., a `fn`, `const` or `static`
/// item (possibly associated), a closure, or a `hir::AnonConst`.
pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
let parent = self.get_parent_node(node_id);
pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
- // NB: intentionally bypass `self.forest.krate()` so that we
+ // N.B., intentionally bypass `self.forest.krate()` so that we
// do not trigger a read of the whole krate here
self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
}
pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
- // NB: intentionally bypass `self.forest.krate()` so that we
+ // N.B., intentionally bypass `self.forest.krate()` so that we
// do not trigger a read of the whole krate here
self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
}
result
}
- /// Similar to get_parent, returns the parent node id or id if there is no
- /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
+ /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is
+ /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself
/// present in the map -- so passing the return value of get_parent_node to
/// get may actually panic.
/// This function returns the immediate parent in the AST, whereas get_parent
/// returns the enclosing item. Note that this might not be the actual parent
/// node in the AST - some kinds of nodes are not in the map and these will
- /// never appear as the parent_node. So you can always walk the parent_nodes
+ /// never appear as the parent_node. So you can always walk the `parent_nodes`
/// from a node to the root of the ast (unless you get the same id back here
/// that can happen if the id is not in the map itself or is just weird).
pub fn get_parent_node(&self, id: NodeId) -> NodeId {
/// If there is some error when walking the parents (e.g., a node does not
/// have a parent in the map or a node can't be found), then we return the
- /// last good node id we found. Note that reaching the crate root (id == 0),
+ /// last good node id we found. Note that reaching the crate root (`id == 0`),
/// is not an error, since items in the crate module have the crate root as
/// parent.
fn walk_parent_nodes<F, F2>(&self,
}
}
- /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
+ /// Retrieve the `NodeId` for `id`'s enclosing method, unless there's a
/// `while` or `loop` before reaching it, as block tail returns are not
/// available in them.
///
self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
}
- /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
+ /// Retrieve the `NodeId` for `id`'s parent item, or `id` itself if no
/// parent item is in this map. The "parent item" is the closest parent node
/// in the HIR which is recorded by the map and is an item, either an item
/// in a module, trait, or impl.
}
}
- /// Returns the DefId of `id`'s nearest module parent, or `id` itself if no
+ /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
/// module parent is in this map.
pub fn get_module_parent(&self, id: NodeId) -> DefId {
self.local_def_id(self.get_module_parent_node(id))
}
- /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
+ /// Returns the `NodeId` of `id`'s nearest module parent, or `id` itself if no
/// module parent is in this map.
pub fn get_module_parent_node(&self, id: NodeId) -> NodeId {
match self.walk_parent_nodes(id, |node| match *node {
}
/// Returns the nearest enclosing scope. A scope is an item or block.
- /// FIXME it is not clear to me that all items qualify as scopes - statics
+ /// FIXME: it is not clear to me that all items qualify as scopes -- statics
/// and associated types probably shouldn't, for example. Behavior in this
/// regard should be expected to be highly unstable.
pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// The Rust HIR.
+// HIR datatypes. See the [rustc guide] for more info.
+//!
+//! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
pub use self::BlockCheckMode::*;
pub use self::CaptureClause::*;
/// A HirId uniquely identifies a node in the HIR of the current crate. It is
/// composed of the `owner`, which is the DefIndex of the directly enclosing
-/// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
+/// hir::Item, hir::TraitItem, or hir::ImplItem (i.e., the closest "item-like"),
/// and the `local_id` which is unique within the given owner.
///
/// This two-level structure makes for more stable values: One can move an item
Plain(Ident),
/// Synthetic name generated when user elided a lifetime in an impl header,
- /// e.g. the lifetimes in cases like these:
+ /// e.g., the lifetimes in cases like these:
///
/// impl Foo for &u32
/// impl Foo<'_> for u32
/// Indicates an illegal name was given and an error has been
/// repored (so we should squelch other derived errors). Occurs
- /// when e.g. `'_` is used in the wrong place.
+ /// when e.g., `'_` is used in the wrong place.
Error,
}
/// User-given names or fresh (synthetic) names.
Param(ParamName),
- /// User typed nothing. e.g. the lifetime in `&u32`.
+ /// User typed nothing. e.g., the lifetime in `&u32`.
Implicit,
/// Indicates an error during lowering (usually `'_` in wrong place)
/// Whether to infer remaining type parameters, if any.
/// This only applies to expression and pattern paths, and
/// out of those only the segments with no type parameters
- /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
+ /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
pub infer_types: bool,
}
}
// FIXME: hack required because you can't create a static
- // GenericArgs, so you can't just return a &GenericArgs.
+ // `GenericArgs`, so you can't just return a `&GenericArgs`.
pub fn with_generic_args<F, R>(&self, f: F) -> R
where F: FnOnce(&GenericArgs) -> R
{
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub enum LifetimeParamKind {
- // Indicates that the lifetime definition was explicitly declared, like:
- // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`
+ // Indicates that the lifetime definition was explicitly declared (e.g., in
+ // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
Explicit,
// Indicates that the lifetime definition was synthetically added
- // as a result of an in-band lifetime usage like:
- // `fn foo(x: &'a u8) -> &'a u8 { x }`
+ // as a result of an in-band lifetime usage (e.g., in
+ // `fn foo(x: &'a u8) -> &'a u8 { x }`).
InBand,
- // Indication that the lifetime was elided like both cases here:
- // `fn foo(x: &u8) -> &'_ u8 { x }`
+ // Indication that the lifetime was elided (e.g., in both cases in
+ // `fn foo(x: &u8) -> &'_ u8 { x }`).
Elided,
// Indication that the lifetime name was somehow in error.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericParamKind {
- /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
+ /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
Lifetime {
kind: LifetimeParamKind,
},
/// A single predicate in a `where` clause
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum WherePredicate {
- /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
+ /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
BoundPredicate(WhereBoundPredicate),
- /// A lifetime predicate, e.g. `'a: 'b+'c`
+ /// A lifetime predicate (e.g., `'a: 'b + 'c`).
RegionPredicate(WhereRegionPredicate),
- /// An equality predicate (unsupported)
+ /// An equality predicate (unsupported).
EqPredicate(WhereEqPredicate),
}
pub bounds: GenericBounds,
}
-/// A lifetime predicate, e.g. `'a: 'b+'c`
+/// A lifetime predicate, e.g., `'a: 'b+'c`
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereRegionPredicate {
pub span: Span,
pub bounds: GenericBounds,
}
-/// An equality predicate (unsupported), e.g. `T=int`
+/// An equality predicate (unsupported), e.g., `T=int`
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
pub exported_macros: HirVec<MacroDef>,
- // NB: We use a BTreeMap here so that `visit_all_items` iterates
+ // N.B., we use a BTreeMap here so that `visit_all_items` iterates
// over the ids in increasing order. In principle it should not
// matter what order we visit things in, but in *practice* it
// does, because it can affect the order in which errors are
/// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
/// The `NodeId` is the canonical ID for the variable being bound,
- /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
+ /// e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
/// which is the pattern ID of the first `x`.
Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
- /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
+ /// A struct or struct variant pattern, e.g., `Variant {x, y, ..}`.
/// The `bool` is `true` in the presence of a `..`.
Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
Tuple(HirVec<P<Pat>>, Option<usize>),
/// A `box` pattern
Box(P<Pat>),
- /// A reference pattern, e.g. `&mut (a, b)`
+ /// A reference pattern, e.g., `&mut (a, b)`
Ref(P<Pat>, Mutability),
/// A literal
Lit(P<Expr>),
- /// A range pattern, e.g. `1...2` or `1..2`
+ /// A range pattern, e.g., `1...2` or `1..2`
Range(P<Expr>, P<Expr>, RangeEnd),
/// `[a, b, ..i, y, z]` is represented as:
/// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
/// A constant (expression) that's not an item or associated item,
/// but needs its own `DefId` for type-checking, const-eval, etc.
-/// These are usually found nested inside types (e.g. array lengths)
-/// or expressions (e.g. repeat counts), and also used to define
+/// These are usually found nested inside types (e.g., array lengths)
+/// or expressions (e.g., repeat counts), and also used to define
/// explicit discriminant values for enum variants.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub struct AnonConst {
/// Path to a definition, optionally "fully-qualified" with a `Self`
/// type, if the path points to an associated item in a trait.
///
- /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
+ /// e.g., an unqualified path like `Clone::clone` has `None` for `Self`,
/// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
/// even though they both have the same two-segment `Clone::clone` `Path`.
Resolved(Option<P<Ty>>, P<Path>),
- /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
+ /// Type-related paths, e.g., `<T>::default` or `<T>::Output`.
/// Will be resolved by type-checking to an associated item.
///
/// UFCS source paths can desugar into this, with `Vec::new` turning into
CaptureByRef,
}
-// NB: If you change this, you'll probably want to change the corresponding
+// N.B., if you change this, you'll probably want to change the corresponding
// type structure in middle/ty.rs as well.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MutTy {
Ptr(MutTy),
/// A reference (`&'a T` or `&'a mut T`)
Rptr(Lifetime, MutTy),
- /// A bare function (e.g. `fn(usize) -> bool`)
+ /// A bare function (e.g., `fn(usize) -> bool`)
BareFn(P<BareFnTy>),
/// The never type (`!`)
Never,
/// A tuple (`(A, B, C, D,...)`)
Tup(HirVec<Ty>),
/// A path to a type definition (`module::module::...::Type`), or an
- /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
+ /// associated type, e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`.
///
/// Type parameters may be stored in each `PathSegment`.
Path(QPath),
TraitObject(HirVec<PolyTraitRef>, Lifetime),
/// Unused for now
Typeof(AnonConst),
- /// TyKind::Infer means the type should be inferred instead of it having been
+ /// `TyKind::Infer` means the type should be inferred instead of it having been
/// specified. This can appear anywhere in a type.
Infer,
/// Placeholder for a type that has failed to be defined.
pub name: Name,
pub attrs: HirVec<Attribute>,
pub data: VariantData,
- /// Explicit discriminant, eg `Foo = 1`
+ /// Explicit discriminant, e.g., `Foo = 1`
pub disr_expr: Option<AnonConst>,
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum UseKind {
- /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
+ /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
/// Also produced for each element of a list `use`, e.g.
// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
Single,
- /// Glob import, e.g. `use foo::*`.
+ /// Glob import, e.g., `use foo::*`.
Glob,
- /// Degenerate list import, e.g. `use foo::{a, b}` produces
+ /// Degenerate list import, e.g., `use foo::{a, b}` produces
/// an additional `use foo::{}` for performing checks such as
/// unstable feature gating. May be removed in the future.
ListStem,
pub enum ItemKind {
/// An `extern crate` item, with optional *original* crate name if the crate was renamed.
///
- /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
+ /// e.g., `extern crate foo` or `extern crate foo_bar as foo`
ExternCrate(Option<Name>),
/// `use foo::bar::*;` or `use foo::bar::baz as quux;`
ForeignMod(ForeignMod),
/// Module-level inline assembly (from global_asm!)
GlobalAsm(P<GlobalAsm>),
- /// A type alias, e.g. `type Foo = Bar<u8>`
+ /// A type alias, e.g., `type Foo = Bar<u8>`
Ty(P<Ty>, Generics),
- /// An existential type definition, e.g. `existential type Foo: Bar;`
+ /// An existential type definition, e.g., `existential type Foo: Bar;`
Existential(ExistTy),
- /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
+ /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
Enum(EnumDef, Generics),
- /// A struct definition, e.g. `struct Foo<A> {x: A}`
+ /// A struct definition, e.g., `struct Foo<A> {x: A}`
Struct(VariantData, Generics),
- /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
+ /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
Union(VariantData, Generics),
/// Represents a Trait Declaration
Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
}
/// Checks if the pattern contains any patterns that bind something to
- /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
+ /// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
pub fn contains_bindings(&self) -> bool {
let mut contains_bindings = false;
self.walk(|p| {
}
/// Checks if the pattern contains any patterns that bind something to
- /// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`,
+ /// an ident or wildcard, e.g., `foo`, or `Foo(_)`, `foo @ Bar(..)`,
pub fn contains_bindings_or_wild(&self) -> bool {
let mut contains_bindings = false;
self.walk(|p| {
}
}
-/// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
-/// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
+/// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
+/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
/// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
match value.node {
/// This is the context state available during incr. comp. hashing. It contains
/// enough information to transform DefIds and HirIds into stable DefPaths (i.e.
/// a reference to the TyCtxt) and it holds a few caches for speeding up various
-/// things (e.g. each DefId/DefPath is only hashed once).
+/// things (e.g., each DefId/DefPath is only hashed once).
#[derive(Clone)]
pub struct StableHashingContext<'a> {
sess: &'a Session,
if self.ambient_variance == ty::Variance::Invariant {
// Avoid fetching the variance if we are in an invariant
// context; no need, and it can induce dependency cycles
- // (e.g. #41849).
+ // (e.g., #41849).
relate::relate_substs(self, None, a_subst, b_subst)
} else {
let opt_variances = self.tcx().variances_of(item_def_id);
b_subst: &'tcx Substs<'tcx>)
-> RelateResult<'tcx, &'tcx Substs<'tcx>>
{
- // NB: Once we are equating types, we don't care about
+ // N.B., once we are equating types, we don't care about
// variance, so don't try to lookup the variance here. This
- // also avoids some cycles (e.g. #41849) since looking up
+ // also avoids some cycles (e.g., #41849) since looking up
// variance requires computing types which can require
// performing trait matching (which then performs equality
// unification).
/// { x.push(y); }
/// ```
/// The function returns the nested type corresponding to the anonymous region
- /// for e.g. `&u8` and Vec<`&u8`.
+ /// for e.g., `&u8` and Vec<`&u8`.
pub(super) fn find_anon_type(
&self,
region: Region<'tcx>,
// associated with the anonymous region we are looking for.
bound_region: ty::BoundRegion,
// The type where the anonymous lifetime appears
- // for e.g. Vec<`&u8`> and <`&u8`>
+ // for e.g., Vec<`&u8`> and <`&u8`>
found_type: Option<&'gcx hir::Ty>,
current_index: ty::DebruijnIndex,
}
/// Pops the placeholder regions found in `placeholder_map` from the region
/// inference context. Whenever you create placeholder regions via
/// `replace_bound_vars_with_placeholders`, they must be popped before you
- /// commit the enclosing snapshot (if you do not commit, e.g. within a
+ /// commit the enclosing snapshot (if you do not commit, e.g., within a
/// probe or as a result of an error, then this is not necessary, as
/// popping happens as part of the rollback).
///
/// `UniverseIndex::root()` but grows from there as we enter
/// universal quantifiers.
///
- /// NB: At present, we exclude the universal quantifiers on the
+ /// N.B., at present, we exclude the universal quantifiers on the
/// item we are type-checking, and just consider those names as
/// part of the root universe. So this would only get incremented
/// when we enter into a higher-ranked (`for<..>`) type or trait
region_obligations_snapshot: self.region_obligations.borrow().len(),
universe: self.universe(),
was_in_snapshot: in_snapshot,
- // Borrow tables "in progress" (i.e. during typeck)
+ // Borrow tables "in progress" (i.e., during typeck)
// to ban writes from within a snapshot to them.
_in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
}
// type parameter definition. The substitutions are
// for actual parameters that may be referred to by
// the default of this type parameter, if it exists.
- // E.g. `struct Foo<A, B, C = (A, B)>(...);` when
+ // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
// used in a path such as `Foo::<T, U>::new()` will
// use an inference variable for `C` with `[T, U]`
// as the substitutions for the default, `(T, U)`.
* Where possible, replaces type/int/float variables in
* `value` with their final value. Note that region variables
* are unaffected. If a type variable has not been unified, it
- * is left as is. This is an idempotent operation that does
+ * is left as is. This is an idempotent operation that does
* not affect inference state in any way and so you can do it
* at will.
*/
/*!
* Attempts to resolve all type/region variables in
* `value`. Region inference must have been run already (e.g.,
- * by calling `resolve_regions_and_report_errors`). If some
+ * by calling `resolve_regions_and_report_errors`). If some
* variable was never unified, an `Err` results.
*
* This method is idempotent, but it not typically not invoked
let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
- // Don't report an error if actual type is Error.
+ // Don't report an error if actual type is `Error`.
if actual_ty.references_error() {
return self.tcx.sess.diagnostic().struct_dummy();
}
//!
//! Here are the key differences:
//!
-//! - This code may choose to bypass some checks (e.g. the occurs check)
+//! - This code may choose to bypass some checks (e.g., the occurs check)
//! in the case where we know that there are no unbound type inference
//! variables. This is the case for NLL, because at NLL time types are fully
//! inferred up-to regions.
/// region that is instantiated existentially. This creates an
/// inference variable, typically.
///
- /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
+ /// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'a` with an
/// inference variable (though `'b` would be instantiated first,
/// as a placeholder).
/// higher-ranked region that is instantiated universally.
/// This creates a new region placeholder, typically.
///
- /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
+ /// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'b` with a
/// placeholder region.
fn next_placeholder_region(&mut self, placeholder: ty::PlaceholderRegion) -> ty::Region<'tcx>;
);
// Use the same type variable if the exact same Opaque appears more
- // than once in the return type (e.g. if it's passed to a type alias).
+ // than once in the return type (e.g., if it's passed to a type alias).
if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
return opaque_defn.concrete_ty;
}
);
// make sure that we are in fact defining the *entire* type
- // e.g. `existential type Foo<T: Bound>: Bar;` needs to be
+ // e.g., `existential type Foo<T: Bound>: Bar;` needs to be
// defined by a function like `fn foo<T: Bound>() -> Foo<T>`.
debug!(
"instantiate_opaque_types: param_env: {:#?}",
// Remove outlives bounds that we get from the environment but
// which are also deducable from the trait. This arises (cc
- // #55756) in cases where you have e.g. `<T as Foo<'a>>::Item:
+ // #55756) in cases where you have e.g., `<T as Foo<'a>>::Item:
// 'a` in the environment but `trait Foo<'b> { type Item: 'b
// }` in the trait definition.
approx_env_bounds.retain(|bound| {
/// which can never be rolled back.
undo_log: Vec<UndoLog<'tcx>>,
- /// The number of open snapshots, i.e. those that haven't been committed or
+ /// The number of open snapshots, i.e., those that haven't been committed or
/// rolled back.
num_open_snapshots: usize,
// never overwrite an existing (constraint, origin) - only insert one if it isn't
// present in the map yet. This prevents origins from outside the snapshot being
- // replaced with "less informative" origins e.g. during calls to `can_eq`
+ // replaced with "less informative" origins e.g., during calls to `can_eq`
let in_snapshot = self.in_snapshot();
let undo_log = &mut self.undo_log;
self.data.constraints.entry(constraint).or_insert_with(|| {
/// Creates a new type variable.
///
/// - `diverging`: indicates if this is a "diverging" type
- /// variable, e.g. one created as the type of a `return`
+ /// variable, e.g., one created as the type of a `return`
/// expression. The code in this module doesn't care if a
/// variable is diverging, but the main Rust type-checker will
/// sometimes "unify" such variables with the `!` or `()` types.
#[macro_use]
mod macros;
-// NB: This module needs to be declared first so diagnostics are
+// N.B., this module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
declare_lint! {
pub LEGACY_DIRECTORY_OWNERSHIP,
Deny,
- "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \
+ "non-inline, non-`#[path]` modules (e.g., `mod foo;`) were erroneously allowed in some files \
not named `mod.rs`"
}
}
/// Does nothing as a lint pass, but registers some `Lint`s
-/// which are used by other parts of the compiler.
+/// that are used by other parts of the compiler.
#[derive(Copy, Clone)]
pub struct HardwiredLints;
//
// Rustdoc runs everybody-loops before the early lints and removes
// function bodies, so it's totally possible for linted
- // node ids to not exist (e.g. macros defined within functions for the
+ // node ids to not exist (e.g., macros defined within functions for the
// unused_macro lint) anymore. So we only run this check
// when we're not in rustdoc mode. (see issue #47639)
if !sess.opts.actually_rustdoc {
for &(ref lint_name, level) in &sess.opts.lint_opts {
store.check_lint_name_cmdline(sess, &lint_name, level);
- // If the cap is less than this specified level, e.g. if we've got
+ // If the cap is less than this specified level, e.g., if we've got
// `--cap-lints allow` but we've also got `-D foo` then we ignore
// this specification as the lint cap will set it to allow anyway.
let level = cmp::min(level, self.lint_cap);
/// * It'll validate all lint-related attributes in `attrs`
/// * It'll mark all lint-related attributes as used
/// * Lint levels will be updated based on the attributes provided
- /// * Lint attributes are validated, e.g. a #[forbid] can't be switched to
+ /// * Lint attributes are validated, e.g., a #[forbid] can't be switched to
/// #[allow]
///
/// Don't forget to call `pop`!
/// `declare_lint!()` invocations to follow the convention of upper-case
/// statics without repeating the name.
///
- /// The name is written with underscores, e.g. "unused_imports".
+ /// The name is written with underscores, e.g., "unused_imports".
/// On the command line, underscores become dashes.
pub name: &'static str,
/// Description of the lint or the issue it detects.
///
- /// e.g. "imports that are never used"
+ /// e.g., "imports that are never used"
pub desc: &'static str,
/// Starting at the given edition, default to the given lint level. If this is `None`, then use
pub trait LintPass {
/// Get descriptions of the lints this `LintPass` object can emit.
///
- /// NB: there is no enforcement that the object only emits lints it registered.
+ /// N.B., there is no enforcement that the object only emits lints it registered.
/// And some `rustc` internal `LintPass`es register lints to be emitted by other
/// parts of the compiler. If you want enforced access restrictions for your
/// `Lint`, make it a private `static` item in its own module.
/// A dependency that is only used for its macros.
MacrosOnly,
/// A dependency that is always injected into the dependency list and so
- /// doesn't need to be linked to an rlib, e.g. the injected allocator.
+ /// doesn't need to be linked to an rlib, e.g., the injected allocator.
Implicit,
/// A dependency that is required by an rlib version of this crate.
/// Ordinary `extern crate`s result in `Explicit` dependencies.
let cg_attrs = tcx.codegen_fn_attrs(def_id);
// #[used], #[no_mangle], #[export_name], etc also keeps the item alive
- // forcefully, e.g. for placing it in a specific section.
+ // forcefully, e.g., for placing it in a specific section.
if cg_attrs.contains_extern_indicator() ||
cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
return true;
// static libraries.
//
// If the crate hasn't been included yet and it's not actually required
- // (e.g. it's an allocator) then we skip it here as well.
+ // (e.g., it's an allocator) then we skip it here as well.
for &cnum in tcx.crates().iter() {
let src = tcx.used_crate_source(cnum);
if src.dylib.is_none() &&
// Given a list of how to link upstream dependencies so far, ensure that an
// injected dependency is activated. This will not do anything if one was
-// transitively included already (e.g. via a dylib or explicitly so).
+// transitively included already (e.g., via a dylib or explicitly so).
//
// If an injected dependency was not found then we're guaranteed the
// metadata::creader module has injected that dependency (not listed as
configure_main(&mut ctxt, crate_name);
}
-// Beware, this is duplicated in libsyntax/entry.rs, make sure to keep
+// Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
// them in sync.
fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
match item.node {
EntryPointType::MainAttr
} else if item.name == "main" {
if at_root {
- // This is a top-level function so can be 'main'
+ // This is a top-level function so can be 'main'.
EntryPointType::MainNamed
} else {
EntryPointType::OtherMain
self.consume_expr(&arm.body);
}
- /// Walks a pat that occurs in isolation (i.e. top-level of fn
+ /// Walks a pat that occurs in isolation (i.e., top-level of fn
/// arg or let binding. *Not* a match arm or nested pat.)
fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
let mut mode = Unknown;
}
/// The core driver for walking a pattern; `match_mode` must be
- /// established up front, e.g. via `determine_pat_move_mode` (see
+ /// established up front, e.g., via `determine_pat_move_mode` (see
/// also `walk_irrefutable_pat` for patterns that stand alone).
fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
-// * Traits that specify "kinds"; e.g. "Sync", "Send".
+// * Traits that specify "kinds"; e.g., "Sync", "Send".
//
-// * Traits that represent operators; e.g. "Add", "Sub", "Index".
+// * Traits that represent operators; e.g., "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// Detecting lib features (i.e. features that are not lang features).
+// Detecting lib features (i.e., features that are not lang features).
//
-// These are declared using stability attributes (e.g. `#[stable (..)]`
+// These are declared using stability attributes (e.g., `#[stable (..)]`
// and `#[unstable (..)]`), but are not declared in one single location
// (unlike lang features), which means we need to collect them instead.
fn extract(&self, attr: &Attribute) -> Option<(Symbol, Option<Symbol>, Span)> {
let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
- // Find a stability attribute (i.e. `#[stable (..)]`, `#[unstable (..)]`,
+ // Find a stability attribute (i.e., `#[stable (..)]`, `#[unstable (..)]`,
// `#[rustc_const_unstable (..)]`).
if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| {
attr.check_name(stab_attr)
/// 65 bits of data into 32; in the uncommon cases, it expands the 65 bits
/// in 96.
///
- /// More compact representations are possible -- e.g. use only 2 bits per
+ /// More compact representations are possible -- e.g., use only 2 bits per
/// packed `RWU` and make the secondary table a HashMap that maps from
/// indices to `RWU`s -- but this one strikes a good balance between size
/// and speed.
}
// We use the term "interior" to mean "something reachable from the
-// base without a pointer dereference", e.g. a field
+// base without a pointer dereference", e.g., a field
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum InteriorKind {
InteriorField(FieldIndex),
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum InteriorOffsetKind {
- Index, // e.g. `array_expr[index_expr]`
- Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
+ Index, // e.g., `array_expr[index_expr]`
+ Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
debug!("cat_rvalue_node: promotable = {:?}", promotable);
- // Always promote `[T; 0]` (even when e.g. borrowed mutably).
+ // Always promote `[T; 0]` (even when e.g., borrowed mutably).
let promotable = match expr_ty.sty {
ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
_ => promotable,
/// (D9.): DestructionScope for temporaries created during M8.
/// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
/// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
-/// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
+/// (D12.): DestructionScope for temporaries created during M1 (e.g., f()).
/// ```
///
/// Note that while the above picture shows the destruction scopes
/// everything after that first `let`. (If you want a scope that
/// includes EXPR_1 as well, then do not use `Scope::Remainder`,
/// but instead another `Scope` that encompasses the whole block,
-/// e.g. `Scope::Node`.
+/// e.g., `Scope::Node`.
///
/// * the subscope with `first_statement_index == 1` is scope of `c`,
/// and thus does not include EXPR_2, but covers the `...`.
impl Scope {
/// Returns a item-local id associated with this scope.
///
- /// NB: likely to be replaced as API is refined; e.g. pnkfelix
+ /// N.B., likely to be replaced as API is refined; e.g., pnkfelix
/// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
pub fn item_local_id(&self) -> hir::ItemLocalId {
self.id
// }, other_argument());
//
// Each of the statements within the block is a terminating
- // scope, and thus a temporary (e.g. the result of calling
+ // scope, and thus a temporary (e.g., the result of calling
// `bar()` in the initializer expression for `let inner = ...;`)
// will be cleaned up immediately after its corresponding
- // statement (i.e. `let inner = ...;`) executes.
+ // statement (i.e., `let inner = ...;`) executes.
//
// On the other hand, temporaries associated with evaluating the
// tail expression for the block are assigned lifetimes so that
// As an exception to the normal rules governing temporary
// lifetimes, initializers in a let have a temporary lifetime
- // of the enclosing block. This means that e.g. a program
+ // of the enclosing block. This means that e.g., a program
// like the following is legal:
//
// let ref x = HashMap::new();
loop {
// Note: give all the expressions matching `ET` with the
// extended temporary lifetime, not just the innermost rvalue,
- // because in codegen if we must compile e.g. `*rvalue()`
+ // because in codegen if we must compile e.g., `*rvalue()`
// into a temporary, we request the temporary scope of the
// outer expression.
visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
// according to rvalue lifetime semantics, using the same
// syntactical rules used for let initializers.
//
- // E.g. in `let x = &f();`, the temporary holding the result from
+ // e.g., in `let x = &f();`, the temporary holding the result from
// the `f()` call lives for the entirety of the surrounding block.
//
// Similarly, `const X: ... = &f();` would have the result of `f()`
//
// However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
// would *not* let the `f()` temporary escape into an outer scope
- // (i.e. `'static`), which means that after `g` returns, it drops,
+ // (i.e., `'static`), which means that after `g` returns, it drops,
// and all the associated destruction scope rules apply.
self.cx.var_parent = None;
resolve_local(self, None, Some(&body.value));
/// Lifetimes introduced by a fn are scoped to the call-site for that fn,
/// if this is a fn body, otherwise the original definitions are used.
/// Unspecified lifetimes are inferred, unless an elision scope is nested,
- /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
+ /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
Body {
id: hir::BodyId,
s: ScopeRef<'a>,
},
/// A scope which either determines unspecified lifetimes or errors
- /// on them (e.g. due to ambiguity). For more details, see `Elide`.
+ /// on them (e.g., due to ambiguity). For more details, see `Elide`.
Elision {
elide: Elide,
s: ScopeRef<'a>,
LifetimeName::Implicit => {
// If the user does not write *anything*, we
// use the object lifetime defaulting
- // rules. So e.g. `Box<dyn Debug>` becomes
+ // rules. So e.g., `Box<dyn Debug>` becomes
// `Box<dyn Debug + 'static>`.
self.resolve_object_lifetime_default(lifetime)
}
LifetimeName::Underscore => {
// If the user writes `'_`, we use the *ordinary* elision
- // rules. So the `'_` in e.g. `Box<dyn Debug + '_>` will be
+ // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
// resolved the same as the `'_` in `&'_ Foo`.
//
// cc #48468
{
insert_late_bound_lifetimes(self.map, decl, generics);
- // Find the start of nested early scopes, e.g. in methods.
+ // Find the start of nested early scopes, e.g., in methods.
let mut index = 0;
if let Some(parent_id) = parent_id {
let parent = self.tcx.hir().expect_item(parent_id);
pub use self::StabilityLevel::*;
use lint;
+use hir::{self, Item, Generics, StructField, Variant, HirId};
use hir::def::Def;
use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
-use ty::{self, TyCtxt};
+use hir::intravisit::{self, Visitor, NestedVisitorMap};
use middle::privacy::AccessLevels;
use session::{DiagnosticMessageId, Session};
use syntax::symbol::Symbol;
use syntax::ast::{NodeId, Attribute};
use syntax::feature_gate::{GateIssue, emit_feature_err};
use syntax::attr::{self, Stability, Deprecation};
+use ty::{self, TyCtxt};
use util::nodemap::{FxHashSet, FxHashMap};
-use hir;
-use hir::{Item, Generics, StructField, Variant, HirId};
-use hir::intravisit::{self, Visitor, NestedVisitorMap};
-
use std::mem::replace;
use std::cmp::Ordering;
}
/// Check whether an item marked with `deprecated(since="X")` is currently
-/// deprecated (i.e. whether X is not greater than the current rustc version).
+/// deprecated (i.e., whether X is not greater than the current rustc version).
pub fn deprecation_in_effect(since: &str) -> bool {
fn parse_version(ver: &str) -> Vec<u32> {
- // We ignore non-integer components of the version (e.g. "nightly").
+ // We ignore non-integer components of the version (e.g., "nightly").
ver.split(|c| c == '.' || c == '-').flat_map(|s| s.parse()).collect()
}
}
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
- // (See issue #38412)
+ // See issue #38412.
fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
// Check if `def_id` is a trait method.
match self.describe_def(def_id) {
if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
// Trait methods do not declare visibility (even
// for visibility info in cstore). Use containing
- // trait instead, so methods of pub traits are
- // themselves considered pub.
+ // trait instead, so methods of `pub` traits are
+ // themselves considered `pub`.
def_id = trait_def_id;
}
}
let visibility = self.visibility(def_id);
match visibility {
- // must check stability for pub items.
+ // Must check stability for `pub` items.
ty::Visibility::Public => false,
- // these are not visible outside crate; therefore
+ // These are not visible outside crate; therefore
// stability markers are irrelevant, if even present.
ty::Visibility::Restricted(..) |
ty::Visibility::Invisible => true,
return EvalResult::Allow;
}
- // Issue 38412: private items lack stability markers.
+ // Issue #38412: private items lack stability markers.
if self.skip_stability_check_due_to_privacy(def_id) {
return EvalResult::Allow;
}
// crates also pulled in from crates.io. We want to ideally be
// able to compile everything without requiring upstream
// modifications, so in the case that this looks like a
- // rustc_private crate (e.g. a compiler crate) and we also have
+ // `rustc_private` crate (e.g., a compiler crate) and we also have
// the `-Z force-unstable-if-unmarked` flag present (we're
// compiling a compiler crate), then let this missing feature
// annotation slide.
}
}
-/// Given the list of enabled features that were not language features (i.e. that
+/// Given the list of enabled features that were not language features (i.e., that
/// were expected to be library features), and the list of features used from
/// libraries, identify activated features that don't exist and error about them.
pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
"tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
- e.g. comparing pointers into different allocations",
+ e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attempted to read undefined bytes",
DeadLocal =>
/// Data is mutable and not aliasable.
Mut {
/// True if this borrow arose from method-call auto-ref
- /// (i.e. `adjustment::Adjust::Borrow`)
+ /// (i.e., `adjustment::Adjust::Borrow`)
allow_two_phase_borrow: bool,
},
}
/// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
///
/// It is used to improve diagnostics when such temporaries are
-/// involved in borrow_check errors, e.g. explanations of where the
+/// involved in borrow_check errors, e.g., explanations of where the
/// temporaries come from, when their destructors are run, and/or how
/// one might revise the code to satisfy the borrow checker's rules.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
/// expression is ignored by the block's expression context.
///
/// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
- /// but not e.g. `let _x = { ...; tail };`
+ /// but not e.g., `let _x = { ...; tail };`
pub tail_result_is_ignored: bool,
}
pub ty: Ty<'tcx>,
/// If the user manually ascribed a type to this variable,
- /// e.g. via `let x: T`, then we carry that type here. The MIR
+ /// e.g., via `let x: T`, then we carry that type here. The MIR
/// borrow checker needs this information since it can affect
/// region inference.
pub user_ty: UserTypeProjections<'tcx>,
/// to generate better debuginfo.
pub name: Option<Name>,
- /// The *syntactic* (i.e. not visibility) source scope the local is defined
+ /// The *syntactic* (i.e., not visibility) source scope the local is defined
/// in. If the local was defined in a let-statement, this
/// is *within* the let-statement, rather than outside
/// of it.
Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
/// This represents all the reading that a pattern match may do
- /// (e.g. inspecting constants and discriminant values), and the
+ /// (e.g., inspecting constants and discriminant values), and the
/// kind of pattern it comes from. This is in order to adapt potential
/// error messages to these specific patterns.
FakeRead(FakeReadCause, Place<'tcx>),
/// Read the discriminant of an ADT.
///
- /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
+ /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
/// be defined to return, say, a 0) if ADT is not an enum.
Discriminant(Place<'tcx>),
/// The second field is the variant index. It's equal to 0 for struct
/// and union expressions. The fourth field is
/// active field number and is present only for union expressions
- /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
+ /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
/// active field index would identity the field `c`
Adt(
&'tcx AdtDef,
///
/// The '.' before `<special-suffix>` makes sure that names with a special
/// suffix can never collide with a name built out of regular Rust
- /// identifiers (e.g. module paths).
+ /// identifiers (e.g., module paths).
pub fn build_cgu_name<I, C, S>(&mut self,
cnum: CrateNum,
components: I,
/// ```
///
/// A reverse postorder traversal of this graph is either `A B C D` or `A C B D`
-/// Note that for a graph containing no loops (i.e. A DAG), this is equivalent to
+/// Note that for a graph containing no loops (i.e., A DAG), this is equivalent to
/// a topological sort.
///
/// Construction of a `ReversePostorder` traversal requires doing a full
// in that circumstance.
//
// For the most part, we do not destructure things external to the
-// MIR, e.g. types, spans, etc, but simply visit them and stop. This
+// MIR, e.g., types, spans, etc, but simply visit them and stop. This
// avoids duplication with other visitors like `TypeFoldable`.
//
// ## Updating
ShallowBorrow(Region<'tcx>),
/// Unique borrow.
UniqueBorrow(Region<'tcx>),
- /// Used as base for another place, e.g. `x` in `x.y`. Will not mutate the place.
+ /// Used as base for another place, e.g., `x` in `x.y`. Will not mutate the place.
/// For example, the projection `x.y` is not marked as a mutation in these cases:
///
/// z = x.y;
Drop,
/// Mutable borrow.
Borrow(Region<'tcx>),
- /// Used as base for another place, e.g. `x` in `x.y`. Could potentially mutate the place.
+ /// Used as base for another place, e.g., `x` in `x.y`. Could potentially mutate the place.
/// For example, the projection `x.y` is marked as a mutation in these cases:
///
/// x.y = ...;
dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
"if set, exclude the pass number when dumping MIR (used in tests)"),
mir_emit_retag: bool = (false, parse_bool, [TRACKED],
- "emit Retagging MIR statements, interpreted e.g. by miri; implies -Zmir-opt-level=0"),
+ "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"),
perf_stats: bool = (false, parse_bool, [UNTRACKED],
"print some performance-related statistics"),
hir_stats: bool = (false, parse_bool, [UNTRACKED],
// adds extra rustc-specific metadata to each option; such metadata
// is exposed by . The public
// functions below ending with `_u` are the functions that return
-// *unstable* options, i.e. options that are only enabled when the
+// *unstable* options, i.e., options that are only enabled when the
// user also passes the `-Z unstable-options` debugging flag.
mod opt {
// The `fn opt_u` etc below are written so that we can use them
/// tracking are hashed into a single value that determines whether the
/// incremental compilation cache can be re-used or not. This hashing is done
/// via the DepTrackingHash trait defined below, since the standard Hash
-/// implementation might not be suitable (e.g. arguments are stored in a Vec,
+/// implementation might not be suitable (e.g., arguments are stored in a Vec,
/// the hash of which is order dependent, but we might not want the order of
/// arguments to make a difference for the hash).
///
// of the directory where librustc is located, rather than where the rustc
// binary is.
// If --libdir is set during configuration to the value other than
- // "lib" (i.e. non-default), this value is used (see issue #16552).
+ // "lib" (i.e., non-default), this value is used (see issue #16552).
#[cfg(target_pointer_width = "64")]
const PRIMARY_LIB_DIR: &str = "lib64";
// either return `No` or `ThinLocal`.
// If processing command line options determined that we're incompatible
- // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
+ // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
if self.opts.cli_forced_thinlto_off {
return config::Lto::No;
}
// the first evaluate_predicates call.
//
// The problem is this: most of rustc, including SelectionContext and traits::project,
- // are designed to work with a concrete usage of a type (e.g. Vec<u8>
+ // are designed to work with a concrete usage of a type (e.g., Vec<u8>
// fn<T>() { Vec<T> }. This information will generally never change - given
// the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'.
// If we're unable to prove that 'T' implements a particular trait, we're done -
//
// One additional consideration is supertrait bounds. Normally, a ParamEnv is only ever
// constructed once for a given type. As part of the construction process, the ParamEnv will
- // have any supertrait bounds normalized - e.g. if we have a type 'struct Foo<T: Copy>', the
+ // have any supertrait bounds normalized - e.g., if we have a type 'struct Foo<T: Copy>', the
// ParamEnv will contain 'T: Copy' and 'T: Clone', since 'Copy: Clone'. When we construct our
// own ParamEnv, we need to do this ourselves, through traits::elaborate_predicates, or else
// SelectionContext will choke on the missing predicates. However, this should never show up in
match &result {
&Ok(Some(ref vtable)) => {
- // If we see an explicit negative impl (e.g. 'impl !Send for MyStruct'),
+ // If we see an explicit negative impl (e.g., 'impl !Send for MyStruct'),
// we immediately bail out, since it's impossible for us to continue.
match vtable {
Vtable::VtableImpl(VtableImplData { impl_def_id, .. }) => {
// If we put both of these predicates in our computed ParamEnv, we'll
// confuse SelectionContext, since it will (correctly) view both as being applicable.
//
- // To solve this, we pick the 'more strict' lifetime bound - i.e. the HRTB
+ // To solve this, we pick the 'more strict' lifetime bound - i.e., the HRTB
// Our end goal is to generate a user-visible description of the conditions
// under which a type implements an auto trait. A trait predicate involving
// a HRTB means that the type needs to work with any choice of lifetime,
- // not just one specific lifetime (e.g. 'static).
+ // not just one specific lifetime (e.g., 'static).
fn add_user_pred<'c>(
&self,
user_computed_preds: &mut FxHashSet<ty::Predicate<'c>>,
/// The current rule is that a trait-ref orphan checks in a crate C:
///
/// 1. Order the parameters in the trait-ref in subst order - Self first,
-/// others linearly (e.g. `<U as Foo<V, W>>` is U < V < W).
+/// others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
/// 2. Of these type parameters, there is at least one type parameter
/// in which, walking the type as a tree, you can reach a type local
/// to C where all types in-between are fundamental types. Call the
/// first such parameter the "local key parameter".
-/// - e.g. `Box<LocalType>` is OK, because you can visit LocalType
+/// - e.g., `Box<LocalType>` is OK, because you can visit LocalType
/// going through `Box`, which is fundamental.
/// - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
/// the same reason.
/// not local), `Vec<LocalType>` is bad, because `Vec<->` is between
/// the local type and the type parameter.
/// 3. Every type parameter before the local key parameter is fully known in C.
-/// - e.g. `impl<T> T: Trait<LocalType>` is bad, because `T` might be
+/// - e.g., `impl<T> T: Trait<LocalType>` is bad, because `T` might be
/// an unknown type.
/// - but `impl<T> LocalType: Trait<T>` is OK, because `LocalType`
/// occurs before `T`.
/// through the parameter's type tree, must appear only as a subtree of
/// a type local to C, with only fundamental types between the type
/// local to C and the local key parameter.
-/// - e.g. `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
+/// - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
/// is bad, because the only local type with `T` as a subtree is
/// `LocalType<T>`, and `Vec<->` is between it and the type parameter.
/// - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
///
/// The orphan rules actually serve several different purposes:
///
-/// 1. They enable link-safety - i.e. 2 mutually-unknowing crates (where
+/// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
/// every type local to one crate is unknown in the other) can't implement
/// the same trait-ref. This follows because it can be seen that no such
/// type can orphan-check in 2 such crates.
}
}
- // returns if `cond` not occurring implies that `error` does not occur - i.e. that
+ // returns if `cond` not occurring implies that `error` does not occur - i.e., that
// `error` occurring implies that `cond` occurs.
fn error_implies(&self,
cond: &ty::Predicate<'tcx>,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Trait Resolution. See [rustc guide] for more info on how this works.
+//! Trait Resolution. See the [rustc guide] for more information on how this works.
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
-pub use self::SelectionError::*;
-pub use self::FulfillmentErrorCode::*;
-pub use self::Vtable::*;
-pub use self::ObligationCauseCode::*;
+#[allow(dead_code)]
+pub mod auto_trait;
+mod coherence;
+pub mod error_reporting;
+mod engine;
+mod fulfill;
+mod project;
+mod object_safety;
+mod on_unimplemented;
+mod select;
+mod specialize;
+mod structural_impls;
+pub mod codegen;
+mod util;
+pub mod query;
use chalk_engine;
use hir;
use hir::def_id::DefId;
-use infer::SuppressRegionErrors;
+use infer::{InferCtxt, SuppressRegionErrors};
use infer::outlives::env::OutlivesEnvironment;
use middle::region;
use mir::interpret::ErrorHandled;
+use rustc_data_structures::sync::Lrc;
+use syntax::ast;
+use syntax_pos::{Span, DUMMY_SP};
use ty::subst::Substs;
use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
use ty::error::{ExpectedFound, TypeError};
use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
-use infer::{InferCtxt};
use util::common::ErrorReported;
-use rustc_data_structures::sync::Lrc;
-use std::fmt::Debug;
-use std::rc::Rc;
-use syntax::ast;
-use syntax_pos::{Span, DUMMY_SP};
+pub use self::SelectionError::*;
+pub use self::FulfillmentErrorCode::*;
+pub use self::Vtable::*;
+pub use self::ObligationCauseCode::*;
pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
pub use self::specialize::find_associated_item;
pub use self::engine::{TraitEngine, TraitEngineExt};
pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
-pub use self::util::{supertraits, supertrait_def_ids, Supertraits, SupertraitDefIds};
-pub use self::util::transitive_bounds;
-
-#[allow(dead_code)]
-pub mod auto_trait;
-mod coherence;
-pub mod error_reporting;
-mod engine;
-mod fulfill;
-mod project;
-mod object_safety;
-mod on_unimplemented;
-mod select;
-mod specialize;
-mod structural_impls;
-pub mod codegen;
-mod util;
+pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds,
+ Supertraits, SupertraitDefIds};
-pub mod query;
+pub use self::ObligationCauseCode::*;
+pub use self::FulfillmentErrorCode::*;
+pub use self::SelectionError::*;
+pub use self::Vtable::*;
// Whether to enable bug compatibility with issue #43355
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
Canonical,
}
-/// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
+/// An `Obligation` represents some trait reference (e.g., `int:Eq`) for
/// which the vtable must be found. The process of finding a vtable is
/// called "resolving" the `Obligation`. This process consists of
/// either identifying an `impl` (e.g., `impl Eq for int`) that
/// Given a trait `trait_ref`, iterates the vtable entries
/// that come from `trait_ref`, including its supertraits.
-#[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
+#[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
fn vtable_methods<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
trait_ref: ty::PolyTraitRef<'tcx>)
SizedSelf,
/// Supertrait reference references `Self` an in illegal location
- /// (e.g. `trait Foo : Bar<Self>`)
+ /// (e.g., `trait Foo : Bar<Self>`)
SupertraitSelf,
/// Method has something illegal
/// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
ReferencesSelf,
- /// e.g. `fn foo(&self) where Self: Clone`
+ /// e.g., `fn foo(&self) where Self: Clone`
WhereClauseReferencesSelf(Span),
/// e.g., `fn foo<A>()`
}
};
- // e.g. Rc<()>
+ // e.g., Rc<()>
let unit_receiver_ty = self.receiver_for_self_ty(
receiver_ty, self.mk_unit(), method.def_id
);
trait_def_id, self.mk_region(ty::ReStatic)
);
- // e.g. Rc<dyn Trait>
+ // e.g., Rc<dyn Trait>
let trait_object_receiver = self.receiver_for_self_ty(
receiver_ty, trait_object_ty, method.def_id
);
}
/// performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
- /// e.g. for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`
+ /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`
fn receiver_for_self_ty(
self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
) -> Ty<'tcx> {
///
/// The only case where the receiver is not dispatchable, but is still a valid receiver
/// type (just not object-safe), is when there is more than one level of pointer indirection.
- /// e.g. `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
+ /// e.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
/// contained by the trait object, because the object that needs to be coerced is behind
/// be observable directly by the user, `Reveal::All`
/// should not be used by checks which may expose
/// type equality or type contents to the user.
- /// There are some exceptions, e.g. around OIBITS and
+ /// There are some exceptions, e.g., around OIBITS and
/// transmute-checking, which expose some details, but
/// not the whole concrete type of the `impl Trait`.
All,
// created (and hence the new ones will quickly be
// discarded as duplicated). But when doing trait
// evaluation this is not the case, and dropping the trait
- // evaluations can causes ICEs (e.g. #43132).
+ // evaluations can causes ICEs (e.g., #43132).
debug!("opt_normalize_projection_type: \
found normalized ty `{:?}`",
ty);
/// When working with a fulfillment context, the derived obligations of each
/// projection cache entry will be registered on the fulfillcx, so any users
/// that can wait for a fulfillcx fixed point need not care about this. However,
-/// users that don't wait for a fixed point (e.g. trait evaluation) have to
+/// users that don't wait for a fixed point (e.g., trait evaluation) have to
/// resolve the obligations themselves to make sure the projected result is
/// ok and avoid issues like #43132.
///
NormalizedTy(NormalizedTy<'tcx>),
}
-// NB: intentionally not Clone
+// N.B., intentionally not Clone
pub struct ProjectionCacheSnapshot {
snapshot: Snapshot,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! See [rustc guide] for more info on how this works.
+//! Candidate selection. See the [rustc guide] for more information on how this works.
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
/// require themselves.
freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
- /// If true, indicates that the evaluation should be conservative
+ /// If `true`, indicates that the evaluation should be conservative
/// and consider the possibility of types outside this crate.
/// This comes up primarily when resolving ambiguity. Imagine
- /// there is some trait reference `$0 : Bar` where `$0` is an
+ /// there is some trait reference `$0: Bar` where `$0` is an
/// inference variable. If `intercrate` is true, then we can never
/// say for sure that this reference is not implemented, even if
/// there are *no impls at all for `Bar`*, because `$0` could be
/// `Bar`. This is the suitable mode for coherence. Elsewhere,
/// though, we set this to false, because we are only interested
/// in types that the user could actually have written --- in
- /// other words, we consider `$0 : Bar` to be unimplemented if
+ /// other words, we consider `$0: Bar` to be unimplemented if
/// there is no type that the user could *actually name* that
/// would satisfy it. This avoids crippling inference, basically.
intercrate: Option<IntercrateMode>,
//
// The selection process begins by examining all in-scope impls,
// caller obligations, and so forth and assembling a list of
- // candidates. See [rustc guide] for more details.
+ // candidates. See the [rustc guide] for more details.
//
// [rustc guide]:
// https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
};
if obligation.predicate.skip_binder().self_ty().is_ty_var() {
- // Self is a type variable (e.g. `_: AsRef<str>`).
+ // Self is a type variable (e.g., `_: AsRef<str>`).
//
// This is somewhat problematic, as the current scheme can't really
// handle it turning to be a projection. This does end up as truly
self.assemble_candidates_for_unsizing(obligation, &mut candidates);
} else {
if lang_items.clone_trait() == Some(def_id) {
- // Same builtin conditions as `Copy`, i.e. every type which has builtin support
+ // Same builtin conditions as `Copy`, i.e., every type which has builtin support
// for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
// types have builtin support for `Clone`.
let clone_conditions = self.copy_clone_conditions(obligation);
{
candidates.vec.push(ImplCandidate(impl_def_id));
- // NB: we can safely drop the placeholder map
+ // N.B., we can safely drop the placeholder map
// since we are in a probe.
mem::drop(placeholder_map);
}
// that this obligation holds. That could be a
// where-clause or, in the case of an object type,
// it could be that the object type lists the
- // trait (e.g. `Foo+Send : Send`). See
+ // trait (e.g., `Foo+Send : Send`). See
// `compile-fail/typeck-default-trait-impl-send-param.rs`
// for an example of a test case that exercises
// this path.
);
self.probe(|this, _snapshot| {
- // the code below doesn't care about regions, and the
+ // The code below doesn't care about regions, and the
// self-ty here doesn't escape this probe, so just erase
// any LBR.
let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
.count();
if upcast_trait_refs > 1 {
- // can be upcast in many ways; need more type information
+ // Can be upcast in many ways; need more type information.
candidates.ambiguous = true;
} else if upcast_trait_refs == 1 {
candidates.vec.push(ObjectCandidate);
(&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
// Upcasts permit two things:
//
- // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
- // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
+ // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
+ // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
//
// Note that neither of these changes requires any
// change at runtime. Eventually this will be
ImplCandidate(other_def) => {
// See if we can toss out `victim` based on specialization.
// This requires us to know *for sure* that the `other` impl applies
- // i.e. EvaluatedToOk:
+ // i.e., EvaluatedToOk:
if other.evaluation == EvaluatedToOk {
match victim.candidate {
ImplCandidate(victim_def) => {
//
// Confirmation unifies the output type parameters of the trait
// with the values found in the obligation, possibly yielding a
- // type error. See [rustc guide] for more details.
+ // type error. See the [rustc guide] for more details.
//
// [rustc guide]:
// https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
// are sufficient to determine the impl substs, without
// relying on projections in the impl-trait-ref.
//
- // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
+ // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
impl_obligations.append(&mut substs.obligations);
VtableImplData {
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/specialization.html
-use super::{SelectionContext, FulfillmentContext};
-use super::util::impl_trait_ref_and_oblig;
+pub mod specialization_graph;
-use rustc_data_structures::fx::FxHashSet;
use hir::def_id::DefId;
use infer::{InferCtxt, InferOk};
-use ty::subst::{Subst, Substs};
+use lint;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::sync::Lrc;
+use syntax_pos::DUMMY_SP;
use traits::{self, ObligationCause, TraitEngine};
use traits::select::IntercrateAmbiguityCause;
use ty::{self, TyCtxt, TypeFoldable};
-use syntax_pos::DUMMY_SP;
-use rustc_data_structures::sync::Lrc;
-
-use lint;
+use ty::subst::{Subst, Substs};
-pub mod specialization_graph;
+use super::{SelectionContext, FulfillmentContext};
+use super::util::impl_trait_ref_and_oblig;
/// Information pertinent to an overlapping impl error.
pub struct OverlapError {
//
// See RFC 1210 for more details and justification.
- // Currently we do not allow e.g. a negative impl to specialize a positive one
+ // Currently we do not allow e.g., a negative impl to specialize a positive one
if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) {
return false;
}
}
// Query provider for `specialization_graph_of`.
-pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
- trait_id: DefId)
- -> Lrc<specialization_graph::Graph> {
+pub(super) fn specialization_graph_provider<'a, 'tcx>(
+ tcx: TyCtxt<'a, 'tcx, 'tcx>,
+ trait_id: DefId,
+) -> Lrc<specialization_graph::Graph> {
let mut sg = specialization_graph::Graph::new();
let mut trait_impls = tcx.all_impls(trait_id);
// The coherence checking implementation seems to rely on impls being
// iterated over (roughly) in definition order, so we are sorting by
- // negated CrateNum (so remote definitions are visited first) and then
- // by a flattened version of the DefIndex.
+ // negated `CrateNum` (so remote definitions are visited first) and then
+ // by a flattened version of the `DefIndex`.
trait_impls.sort_unstable_by_key(|def_id| {
(-(def_id.krate.as_u32() as i64),
def_id.index.address_space().index(),
///
/// The graph provides two key services:
///
-/// - Construction, which implicitly checks for overlapping impls (i.e., impls
+/// - Construction. This implicitly checks for overlapping impls (i.e., impls
/// that overlap but where neither specializes the other -- an artifact of the
/// simple "chain" rule.
///
/// has at most one parent.
#[derive(RustcEncodable, RustcDecodable)]
pub struct Graph {
- // all impls have a parent; the "root" impls have as their parent the def_id
- // of the trait
+ // All impls have a parent; the "root" impls have as their parent the `def_id`
+ // of the trait.
parent: DefIdMap<DefId>,
- // the "root" impls are found by looking up the trait's def_id.
+ // The "root" impls are found by looking up the trait's def_id.
children: DefIdMap<Children>,
}
}
impl<'a, 'gcx, 'tcx> Children {
- /// Insert an impl into this set of children without comparing to any existing impls
+ /// Insert an impl into this set of children without comparing to any existing impls.
fn insert_blindly(&mut self,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
impl_def_id: DefId) {
);
let overlap_error = |overlap: traits::coherence::OverlapResult<'_>| {
- // overlap, but no specialization; error out
+ // Found overlap, but no specialization; error out.
let trait_ref = overlap.impl_header.trait_ref.unwrap();
let self_ty = trait_ref.self_ty();
OverlapError {
with_impl: possible_sibling,
trait_desc: trait_ref.to_string(),
- // only report the Self type if it has at least
+ // Only report the `Self` type if it has at least
// some outer concrete shell; otherwise, it's
// not adding much information.
self_desc: if self_ty.has_concrete_skeleton() {
debug!("descending as child of TraitRef {:?}",
tcx.impl_trait_ref(possible_sibling).unwrap());
- // the impl specializes possible_sibling
+ // The impl specializes `possible_sibling`.
return Ok(Inserted::ShouldRecurseOn(possible_sibling));
} else if ge && !le {
debug!("placing as parent of TraitRef {:?}",
return Ok(Inserted::ReplaceChildren(replace_children));
}
- // no overlap with any potential siblings, so add as a new sibling
+ // No overlap with any potential siblings, so add as a new sibling.
debug!("placing as new sibling");
self.insert_blindly(tcx, impl_def_id);
Ok(Inserted::BecameNewSibling(last_lint))
debug!("insert({:?}): inserting TraitRef {:?} into specialization graph",
impl_def_id, trait_ref);
- // if the reference itself contains an earlier error (e.g., due to a
+ // If the reference itself contains an earlier error (e.g., due to a
// resolution failure), then we just insert the impl at the top level of
// the graph and claim that there's no overlap (in order to suppress
// bogus errors).
let mut last_lint = None;
let simplified = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false);
- // Descend the specialization tree, where `parent` is the current parent node
+ // Descend the specialization tree, where `parent` is the current parent node.
loop {
use self::Inserted::*;
siblings.insert_blindly(tcx, impl_def_id);
}
- // Set G's parent to N and N's parent to P
+ // Set G's parent to N and N's parent to P.
for &grand_child_to_be in &grand_children_to_be {
self.parent.insert(grand_child_to_be, impl_def_id);
}
impl<'a, 'gcx, 'tcx> Ancestors {
/// Search the items from the given ancestors, returning each definition
/// with the given name and the given kind.
- #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
+ // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
+ #[inline]
pub fn defs(
self,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
// except according to those terms.
use hir::def_id::DefId;
-use ty::subst::{Kind, Subst, Substs};
+use traits::specialize::specialization_graph::NodeItem;
use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
use ty::outlives::Component;
+use ty::subst::{Kind, Subst};
use util::nodemap::FxHashSet;
-use hir::{self};
-use traits::specialize::specialization_graph::NodeItem;
use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
/// Take the address and produce either a `&` or `*` pointer.
Borrow(AutoBorrow<'tcx>),
- /// Unsize a pointer/reference value, e.g. `&[T; n]` to
+ /// Unsize a pointer/reference value, e.g., `&[T; n]` to
/// `&[T]`. Note that the source could be a thin or fat pointer.
/// This will do things like convert thin pointers to fat
/// pointers, or convert structs containing thin pointers to
let leb128_bits = len * 7;
// Check that the shorthand is a not longer than the
- // full encoding itself, i.e. it's an obvious win.
+ // full encoding itself, i.e., it's an obvious win.
if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
cache(encoder).insert(value.clone(), shorthand);
}
// auto-ref. The type returned by this function does not consider such
// adjustments. See `expr_ty_adjusted()` instead.
//
- // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
+ // NB (2): This type doesn't provide type parameter substitutions; e.g., if you
// ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize"
// instead of "fn(ty) -> T with T = isize".
pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> {
/// For Ty, None can be returned if either the type interner doesn't
/// contain the TyKind key or if the address of the interned
/// pointer differs. The latter case is possible if a primitive type,
-/// e.g. `()` or `u8`, was interned in a different context.
+/// e.g., `()` or `u8`, was interned in a different context.
pub trait Lift<'tcx>: fmt::Debug {
type Lifted: fmt::Debug + 'tcx;
fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Self::Lifted>;
}
impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {}
-// NB: An Interned<Ty> compares and hashes as a sty.
+// N.B., an `Interned<Ty>` compares and hashes as a sty.
impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> {
fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool {
self.0.sty == other.0.sty
}
}
-// NB: An Interned<List<T>> compares and hashes as its elements.
+// N.B., an `Interned<List<T>>` compares and hashes as its elements.
impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List<T>> {
fn eq(&self, other: &Interned<'tcx, List<T>>) -> bool {
self.0[..] == other.0[..]
/// Given a closure signature `sig`, returns an equivalent `fn`
/// type with the same signature. Detuples and so forth -- so
- /// e.g. if we have a sig with `Fn<(u32, i32)>` then you would get
+ /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get
/// a `fn(u32, i32)`.
pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
let converted_sig = sig.map_bound(|s| {
}
pub fn lint_hir_note<S: Into<MultiSpan>>(self,
- lint: &'static Lint,
- hir_id: HirId,
- span: S,
- msg: &str,
- note: &str) {
+ lint: &'static Lint,
+ hir_id: HirId,
+ span: S,
+ msg: &str,
+ note: &str) {
let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg);
err.note(note);
err.emit()
}
pub fn provide(providers: &mut ty::query::Providers<'_>) {
- // FIXME(#44234) - almost all of these queries have no sub-queries and
+ // FIXME(#44234): almost all of these queries have no sub-queries and
// therefore no actual inputs, they're just reading tables calculated in
- // resolve! Does this work? Unsure! That's what the issue is about
+ // resolve! Does this work? Unsure! That's what the issue is about.
providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned();
providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned();
providers.crate_name = |tcx, id| {
}
fn erase_regions_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
- // NB: use `super_fold_with` here. If we used `fold_with`, it
+ // N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx })
}
// anything. when lazy normalization happens, this
// will change. It would still be nice to have a way
// to deal with known-not-to-unify-with-anything
- // projections (e.g. the likes of <__S as Encoder>::Error).
+ // projections (e.g., the likes of <__S as Encoder>::Error).
Some(ParameterSimplifiedType)
} else {
None
/// If true, we only want regions that are known to be
/// "constrained" when you equate this type with another type. In
- /// particular, if you have e.g. `&'a u32` and `&'b u32`, equating
+ /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
/// them constraints `'a == 'b`. But if you have `<&'a u32 as
/// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
/// types may mean that `'a` and `'b` don't appear in the results,
// Unclear if there is any value in distinguishing these.
// Probably eventually (and maybe we would even want
- // finer-grained distinctions, e.g. between enum/struct).
+ // finer-grained distinctions, e.g., between enum/struct).
data @ DefPathData::Misc |
data @ DefPathData::TypeNs(..) |
data @ DefPathData::Trait(..) |
AlwaysSized,
/// A univariant, the last field of which may be coerced to unsized.
MaybeUnsized,
- /// A univariant, but with a prefix of an arbitrary size & alignment (e.g. enum tag).
+ /// A univariant, but with a prefix of an arbitrary size & alignment (e.g., enum tag).
Prefixed(Size, Align),
}
// A variant is absent if it's uninhabited and only has ZST fields.
// Present uninhabited variants only require space for their fields,
- // but *not* an encoding of the discriminant (e.g. a tag value).
+ // but *not* an encoding of the discriminant (e.g., a tag value).
// See issue #49298 for more details on the need to leave space
// for non-ZST uninhabited data (mostly partial initialization).
let absent = |fields: &[TyLayout<'_>]| {
}).collect();
session::VariantInfo {
- name: n.map(|n|n.to_string()),
+ name: n.map(|n| n.to_string()),
kind: if layout.is_unsized() {
session::SizeKind::Min
} else {
}
}
-/// Type size "skeleton", i.e. the only information determining a type's size.
+/// Type size "skeleton", i.e., the only information determining a type's size.
/// While this is conservative, (aside from constant sizes, only pointers,
/// newtypes thereof and null pointer optimized enums are allowed), it is
/// enough to statically check common use cases of transmute.
details
};
- // NB: This recording is normally disabled; when enabled, it
+ // N.B., this recording is normally disabled; when enabled, it
// can however trigger recursive invocations of `layout_of`.
// Therefore, we execute it *after* the main query has
// completed, to avoid problems around recursive structures
details
};
- // NB: This recording is normally disabled; when enabled, it
+ // N.B., this recording is normally disabled; when enabled, it
// can however trigger recursive invocations of `layout_of`.
// Therefore, we execute it *after* the main query has
// completed, to avoid problems around recursive structures
assert!(i < this.fields.count());
// Reuse the fat *T type as its own thin pointer data field.
- // This provides information about e.g. DST struct pointees
+ // This provides information about e.g., DST struct pointees
// (which may have no non-DST form), and will work as long
// as the `Abi` or `FieldPlacement` is checked by users.
if i == 0 {
/// The complete set of all analyses described in this module. This is
/// produced by the driver and fed to codegen and later passes.
///
-/// NB: These contents are being migrated into queries using the
+/// N.B., these contents are being migrated into queries using the
/// *on-demand* infrastructure.
#[derive(Clone)]
pub struct CrateAnalysis {
/// by some sub-binder.
///
/// So, for a type without any late-bound things, like `u32`, this
- /// will be INNERMOST, because that is the innermost binder that
+ /// will be *innermost*, because that is the innermost binder that
/// captures nothing. But for a type `&'D u32`, where `'D` is a
- /// late-bound region with debruijn index D, this would be D+1 --
- /// the binder itself does not capture D, but D is captured by an
- /// inner binder.
+ /// late-bound region with debruijn index `D`, this would be `D + 1`
+ /// -- the binder itself does not capture `D`, but `D` is captured
+ /// by an inner binder.
///
- /// We call this concept an "exclusive" binder D (because all
+ /// We call this concept an "exclusive" binder `D` because all
/// debruijn indices within the type are contained within `0..D`
- /// (exclusive)).
+ /// (exclusive).
outer_exclusive_binder: ty::DebruijnIndex,
}
}
/// Information about the formal type/lifetime parameters associated
-/// with an item or method. Analogous to hir::Generics.
+/// with an item or method. Analogous to `hir::Generics`.
///
-/// The ordering of parameters is the same as in Subst (excluding child generics):
-/// Self (optionally), Lifetime params..., Type params...
+/// The ordering of parameters is the same as in `Subst` (excluding child generics):
+/// `Self` (optionally), `Lifetime` params..., `Type` params...
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct Generics {
pub parent: Option<DefId>,
/// pair it with the empty environment. This improves caching and is generally
/// invisible.
///
- /// NB: We preserve the environment when type-checking because it
+ /// N.B., we preserve the environment when type-checking because it
/// is possible for the user to have wacky where-clauses like
/// `where Box<u32>: Copy`, which are clearly never
/// satisfiable. We generally want to behave as if they were true,
#[derive(Debug)]
pub struct VariantDef {
- /// The variant's DefId. If this is a tuple-like struct,
- /// this is the DefId of the struct's ctor.
+ /// The variant's `DefId`. If this is a tuple-like struct,
+ /// this is the `DefId` of the struct's ctor.
pub did: DefId,
pub name: Name, // struct's name if this is a struct
pub discr: VariantDiscr,
///
/// Note that we *could* use the constructor DefId, because the constructor attributes
/// redirect to the base attributes, but compiling a small crate requires
- /// loading the AdtDefs for all the structs in the universe (e.g. coherence for any
+ /// loading the AdtDefs for all the structs in the universe (e.g., coherence for any
/// built-in trait), and we do not want to load attributes twice.
///
/// If someone speeds up attribute loading to not be a performance concern, they can
#[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub enum VariantDiscr {
- /// Explicit value for this variant, i.e. `X = 123`.
+ /// Explicit value for this variant, i.e., `X = 123`.
/// The `DefId` corresponds to the embedded constant.
Explicit(DefId),
pub vis: Visibility,
}
-/// The definition of an abstract data type - a struct or enum.
+/// The definition of an abstract data type -- a struct or enum.
///
-/// These are all interned (by intern_adt_def) into the adt_defs
+/// These are all interned (by `intern_adt_def`) into the `adt_defs`
/// table.
pub struct AdtDef {
pub did: DefId,
/// Self would prevent its containing ADT from being Sized.
///
/// Due to normalization being eager, this applies even if
- /// the associated type is behind a pointer, e.g. issue #31299.
+ /// the associated type is behind a pointer, e.g., issue #31299.
pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
match tcx.try_adt_sized_constraint(DUMMY_SP, self.did) {
Ok(tys) => tys,
) -> Result<DtorckConstraint<'tcx>, NoSolution>,
/// True if this is a const fn, use the `is_const_fn` to know whether your crate actually
- /// sees it as const fn (e.g. the const-fn-ness might be unstable and you might not have
+ /// sees it as const fn (e.g., the const-fn-ness might be unstable and you might not have
/// the feature gate active)
///
- /// DO NOT CALL MANUALLY, it is only meant to cache the base data for the `is_const_fn`
- /// function
+ /// **Do not call this function manually.** It is only meant to cache the base data for the
+ /// `is_const_fn` function.
[] fn is_const_fn_raw: IsConstFn(DefId) -> bool,
/// Returns true if calls to the function may be promoted
///
- /// This is either because the function is e.g. a tuple-struct or tuple-variant constructor,
- /// or because it has the `#[rustc_promotable]` attribute. The attribute should be removed
- /// in the future in favour of some form of check which figures out whether the function
- /// does not inspect the bits of any of its arguments (so is essentially just a constructor
- /// function)
+ /// This is either because the function is e.g., a tuple-struct or tuple-variant
+ /// constructor, or because it has the `#[rustc_promotable]` attribute. The attribute should
+ /// be removed in the future in favour of some form of check which figures out whether the
+ /// function does not inspect the bits of any of its arguments (so is essentially just a
+ /// constructor function).
[] fn is_promotable_const_fn: IsPromotableConstFn(DefId) -> bool,
/// True if this is a foreign item (i.e., linked via `extern { ... }`).
[] fn all_crate_nums: all_crate_nums_node(CrateNum) -> Lrc<Vec<CrateNum>>,
/// A vector of every trait accessible in the whole crate
- /// (i.e. including those from subcrates). This is used only for
+ /// (i.e., including those from subcrates). This is used only for
/// error reporting.
[] fn all_traits: all_traits_node(CrateNum) -> Lrc<Vec<DefId>>,
},
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Generalized type relating mechanism. A type relation R relates a
-//! pair of values (A, B). A and B are usually types or regions but
-//! can be other things. Examples of type relations are subtyping,
-//! type equality, etc.
+//! Generalized type relating mechanism.
+//!
+//! A type relation `R` relates a pair of values `(A, B)`. `A and B` are usually
+//! types or regions but can be other things. Examples of type relations are
+//! subtyping, type equality, etc.
use hir::def_id::DefId;
use mir::interpret::ConstValue;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! This module contains TyKind and its major components
+//! This module contains `TyKind` and its major components.
+use hir;
use hir::def_id::DefId;
use infer::canonical::Canonical;
use mir::interpret::ConstValue;
use syntax::symbol::{keywords, InternedString};
use serialize;
-
-use hir;
-
use self::InferTy::*;
use self::TyKind::*;
}
}
-/// N.B., If you change this, you'll probably want to change the corresponding
+/// N.B., if you change this, you'll probably want to change the corresponding
/// AST structure in `libsyntax/ast.rs` as well.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
pub enum TyKind<'tcx> {
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum ExistentialPredicate<'tcx> {
- /// e.g. Iterator
+ /// e.g., Iterator
Trait(ExistentialTraitRef<'tcx>),
- /// e.g. Iterator::Item = T
+ /// e.g., Iterator::Item = T
Projection(ExistentialProjection<'tcx>),
- /// e.g. Send
+ /// e.g., Send
AutoTrait(DefId),
}
/// Binder<TraitRef>`). Note that when we instantiate,
/// erase, or otherwise "discharge" these bound vars, we change the
/// type from `Binder<T>` to just `T` (see
-/// e.g. `liberate_late_bound_regions`).
+/// e.g., `liberate_late_bound_regions`).
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct Binder<T>(T);
/// with some concrete region before being used. There are 2 kind of
/// bound regions: early-bound, which are bound in an item's Generics,
/// and are substituted by a Substs, and late-bound, which are part of
-/// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by
+/// higher-ranked types (e.g., `for<'a> fn(&'a ())`) and are substituted by
/// the likes of `liberate_late_bound_regions`. The distinction exists
/// because higher-ranked lifetimes aren't supported in all places. See [1][2].
///
/// Unlike Param-s, bound regions are not supposed to exist "in the wild"
-/// outside their binder, e.g. in types passed to type inference, and
+/// outside their binder, e.g., in types passed to type inference, and
/// should first be substituted (by placeholder regions, free regions,
/// or region variables).
///
ReFree(FreeRegion),
/// A concrete region naming some statically determined scope
- /// (e.g. an expression or sequence of statements) within the
+ /// (e.g., an expression or sequence of statements) within the
/// current function.
ReScope(region::Scope),
impl DebruijnIndex {
/// Returns the resulting index when this value is moved into
- /// `amount` number of new binders. So e.g. if you had
+ /// `amount` number of new binders. So e.g., if you had
///
/// for<'a> fn(&'a x)
///
///
/// for<'a> fn(for<'b> fn(&'a x))
///
- /// you would need to shift the index for `'a` into 1 new binder.
+ /// you would need to shift the index for `'a` into a new binder.
#[must_use]
pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
DebruijnIndex::from_u32(self.as_u32() + amount)
}
}
- /// Returns the type and mutability of *ty.
+ /// Returns the type and mutability of `*ty`.
///
/// The parameter `explicit` indicates if this is an *explicit* dereference.
- /// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
+ /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
match self.sty {
Adt(def, _) if def.is_box() => {
}
/// Transform from substitutions for a child of `source_ancestor`
- /// (e.g. a trait or impl) to substitutions for the same child
+ /// (e.g., a trait or impl) to substitutions for the same child
/// in a different item, with `target_substs` as the base for
/// the target impl/trait, with the source child-specific
- /// parameters (e.g. method parameters) on top of that base.
+ /// parameters (e.g., method parameters) on top of that base.
pub fn rebase_onto(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
source_ancestor: DefId,
target_substs: &Substs<'tcx>)
/// themselves. This should really be a unique type; `FreshTy(0)` is a
/// popular choice.
///
- /// NB: in some cases, particularly around higher-ranked bounds,
+ /// N.B., in some cases, particularly around higher-ranked bounds,
/// this function returns a kind of conservative approximation.
/// That is, all regions returned by this function are definitely
/// required, but there may be other region bounds that are not
// destructor will not access borrowed data,
// even if such data is otherwise reachable.
//
- // Such access can be in plain sight (e.g. dereferencing
+ // Such access can be in plain sight (e.g., dereferencing
// `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
- // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
+ // (e.g., calling `foo.0.clone()` of `Foo<T:Clone>`).
if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
debug!("destructor_constraint({:?}) - blind", def.did);
return vec![];
/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
/// non-copy and *might* have a destructor attached; if it returns
- /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
+ /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
///
/// (Note that this implies that if `ty` has a destructor attached,
/// then `needs_drop` will definitely return `true` for `ty`.)
/// If `key` is present in the map, return the value,
/// otherwise invoke `op` and store the value in the map.
///
- /// NB: if the receiver is a `DepTrackingMap`, special care is
+ /// N.B., if the receiver is a `DepTrackingMap`, special care is
/// needed in the `op` to ensure that the correct edges are
/// added into the dep graph. See the `DepTrackingMap` impl for
/// more details!
// In case MSB resides at the left-hand side of radix point, shift the
// mantissa right by some amount to make sure the MSB reside right before
- // the radix point (i.e. "MSB . rest-significant-bits").
+ // the radix point (i.e., "MSB . rest-significant-bits").
if omsb > S::PRECISION {
let bits = omsb - S::PRECISION;
loss = sig::shift_right(&mut wide_sig, &mut self.exp, bits).combine(loss);
// In case MSB resides at the left-hand side of radix point, shift the
// mantissa right by some amount to make sure the MSB reside right before
- // the radix point (i.e. "MSB . rest-significant-bits").
+ // the radix point (i.e., "MSB . rest-significant-bits").
//
// Note that the result is not normalized when "omsb < precision". So, the
// caller needs to call IeeeFloat::normalize() if normalized value is
//! Comments have been preserved where possible, only slightly adapted.
//!
//! Instead of keeping a pointer to a configuration struct and inspecting it
-//! dynamically on every operation, types (e.g. `ieee::Double`), traits
-//! (e.g. `ieee::Semantics`) and associated constants are employed for
+//! dynamically on every operation, types (e.g., `ieee::Double`), traits
+//! (e.g., `ieee::Semantics`) and associated constants are employed for
//! increased type safety and performance.
//!
//! On-heap bigints are replaced everywhere (except in decimal conversion),
/// implemented operations. Currently implemented operations are add, subtract,
/// multiply, divide, fused-multiply-add, conversion-to-float,
/// conversion-to-integer and conversion-from-integer. New rounding modes
-/// (e.g. away from zero) can be added with three or four lines of code.
+/// (e.g., away from zero) can be added with three or four lines of code.
///
/// Four formats are built-in: IEEE single precision, double precision,
/// quadruple precision, and x87 80-bit extended double (when operating with
pub trait FloatConvert<T: Float>: Float {
/// Convert a value of one floating point type to another.
/// The return value corresponds to the IEEE754 exceptions. *loses_info
- /// records whether the transformation lost information, i.e. whether
+ /// records whether the transformation lost information, i.e., whether
/// converting the result back to the original type will produce the
/// original value (this is almost the same as return value==Status::OK,
/// but there are edge cases where this is not so).
// \ /
// Normal
//
- // e.g. NaN * NaN = NaN
+ // e.g., NaN * NaN = NaN
// Zero * Inf = NaN
// Normal * Zero = Zero
// Normal * Inf = Inf
lp);
}
None => {
- // This can occur with e.g. `*foo() = 5`. In such
+ // This can occur with e.g., `*foo() = 5`. In such
// cases, there is no need to check for conflicts
// with moves etc, just ignore.
}
}
/// Accessor for introspective clients inspecting `AnalysisData` and
-/// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer.
+/// the `BorrowckCtxt` itself , e.g., the flowgraph visualizer.
pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
body_id: hir::BodyId,
scope_kills: Vec<usize>,
/// bits killed as we exit the cfg node directly; if it is jumped
- /// over, e.g. via `break`, the kills are not reflected in the
+ /// over, e.g., via `break`, the kills are not reflected in the
/// jump's effects. Updated by `add_kill(KillFrom::Execution)`.
action_kills: Vec<usize>,
let mut index = FxHashMap::default();
// FIXME(#15020) Would it be better to fold formals from decl
- // into cfg itself? i.e. introduce a fn-based flow-graph in
+ // into cfg itself? i.e., introduce a fn-based flow-graph in
// addition to the current block-based flow-graph, rather than
// have to put traversals like this here?
if let Some(body) = body {
for offset in 0..usize_bits {
let bit = 1 << offset;
if (word & bit) != 0 {
- // NB: we round up the total number of bits
+ // N.B., we round up the total number of bits
// that we store in any given bit set so that
// it is an even multiple of usize::BITS. This
// means that there may be some stray bits at
impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
/// Get the LLVM type for a place of the original Rust type of
- /// this argument/return, i.e. the result of `type_of::type_of`.
+ /// this argument/return, i.e., the result of `type_of::type_of`.
fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
self.layout.llvm_type(cx)
}
Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
}
-/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
+/// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
#[inline]
pub fn naked(val: &'ll Value, is_naked: bool) {
Attribute::Naked.toggle_llfn(Function, val, is_naked);
}
}
-/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
+/// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
/// attributes.
pub fn from_fn_attrs(
cx: &CodegenCx<'ll, '_>,
//
// The rationale behind this ordering is that those items lower down in the
// list can't depend on items higher up in the list. For example nothing can
- // depend on what we just generated (e.g. that'd be a circular dependency).
+ // depend on what we just generated (e.g., that'd be a circular dependency).
// Upstream rust libraries are not allowed to depend on our local native
// libraries as that would violate the structure of the DAG, in that
// scenario they are required to link to them as well in a shared fashion.
// well, but they also can't depend on what we just started to add to the
// link line. And finally upstream native libraries can't depend on anything
// in this DAG so far because they're only dylibs and dylibs can only depend
- // on other dylibs (e.g. other native deps).
+ // on other dylibs (e.g., other native deps).
add_local_native_libraries(cmd, sess, codegen_results);
add_upstream_rust_crates(cmd, sess, codegen_results, crate_type, tmpdir);
add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
// compiler-builtins are always placed last to ensure that they're
// linked correctly.
// We must always link the `compiler_builtins` crate statically. Even if it
- // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
+ // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
// is used)
if let Some(cnum) = compiler_builtins {
add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
// because a `dylib` can be reused as an intermediate artifact.
//
// Note, though, that we don't want to include the whole of a
- // compiler-builtins crate (e.g. compiler-rt) because it'll get
+ // compiler-builtins crate (e.g., compiler-rt) because it'll get
// repeatedly linked anyway.
if crate_type == config::CrateType::Dylib &&
codegen_results.crate_info.compiler_builtins != Some(cnum) {
}
// The x86 ABI seems to require that leading underscores are added to symbol
// names, so we need an extra underscore on 32-bit. There's also a leading
- // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
+ // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
// underscores added in front).
let prefix = if cgcx.target_pointer_width == "32" {
"\x01__imp__"
///
/// Each `Block` may contain an instance of this, indicating whether the block
/// is part of a landing pad or not. This is used to make decision about whether
-/// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
+/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
/// use `invoke`) and also about various function call metadata.
///
/// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
self.tcx.sess.opts.cg.prefer_dynamic));
if needs_dll_storage_attr {
- // This item is external but not foreign, i.e. it originates from an external Rust
+ // This item is external but not foreign, i.e., it originates from an external Rust
// crate. Since we don't know whether this crate will be linked dynamically or
// statically in the final application, we always mark such symbols as 'dllimport'.
// If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
//
// By default a global's alignment can be freely increased.
// This allows LLVM to generate more performant instructions
- // e.g. using load-aligned into a SIMD register.
+ // e.g., using load-aligned into a SIMD register.
//
// However, on macOS 10.10 or below, the dynamic linker does not
// respect any alignment given on the TLS (radar 24221680).
// they're not available to be linked against. This poses a few problems
// for the compiler, some of which are somewhat fundamental, but we use
// the `use_dll_storage_attrs` variable below to attach the `dllexport`
- // attribute to all LLVM functions that are exported e.g. they're
+ // attribute to all LLVM functions that are exported e.g., they're
// already tagged with external linkage). This is suboptimal for a few
// reasons:
//
//!
//! (3) Tuple-, pointer and function types are structurally identified, which
//! means that they are equivalent if their component types are equivalent
-//! (i.e. (i32, i32) is the same regardless in which crate it is used).
+//! (i.e., (i32, i32) is the same regardless in which crate it is used).
//!
//! This algorithm also provides a stable ID for types that are defined in one
//! crate but instantiated from metadata within another crate. We just have to
},
None => {
// The Ty is not in the TypeMap but maybe we have already seen
- // an equivalent type (e.g. only differing in region arguments).
+ // an equivalent type (e.g., only differing in region arguments).
// In order to find out, generate the unique type id and look
// that up.
let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
);
// Only "class" methods are generally understood by LLVM,
- // so avoid methods on other types (e.g. `<*mut T>::null`).
+ // so avoid methods on other types (e.g., `<*mut T>::null`).
match impl_self_ty.sty {
ty::Adt(def, ..) if !def.is_box() => {
Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
use rustc::hir;
// Compute the name of the type as it should be stored in debuginfo. Does not do
-// any caching, i.e. calling the function twice with the same type will also do
+// any caching, i.e., calling the function twice with the same type will also do
// the work twice. The `qualified` parameter only affects the first level of the
-// type name, further levels (i.e. type parameters) are always fully qualified.
+// type name, further levels (i.e., type parameters) are always fully qualified.
pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
t: Ty<'tcx>,
qualified: bool)
pub fn is_node_local_to_unit(cx: &CodegenCx, def_id: DefId) -> bool
{
// The is_local_to_unit flag indicates whether a function is local to the
- // current compilation unit (i.e. if it is *static* in the C-sense). The
+ // current compilation unit (i.e., if it is *static* in the C-sense). The
// *reachable* set should provide a good approximation of this, as it
// contains everything that might leak out of the current crate (by being
// externally visible or by being inlined into something externally
// We found a tuple that needs squishing! So
// run over the tuple and load each field.
//
- // This assumes the type is "simple", i.e. no
+ // This assumes the type is "simple", i.e., no
// destructors, and the contents are SIMD
// etc.
assert!(!bx.type_needs_drop(arg.layout.ty));
}
// Definition of the standard "try" function for Rust using the GNU-like model
-// of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
+// of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
// instructions).
//
// This codegen is a little surprising because we always call a shim
// example happen for generics when using multiple codegen units. This function simply uses the
// value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
// function.
-// For more details on COMDAT sections see e.g. http://www.airs.com/blog/archives/52
+// For more details on COMDAT sections see e.g., http://www.airs.com/blog/archives/52
pub fn SetUniqueComdat(llmod: &Module, val: &'a Value) {
unsafe {
LLVMRustSetComdat(llmod, val, LLVMGetValueName(val));
llvm::SetUniqueComdat(self.llmod, lldecl);
}
- // If we're compiling the compiler-builtins crate, e.g. the equivalent of
+ // If we're compiling the compiler-builtins crate, e.g., the equivalent of
// compiler-rt, then we want to implicitly compile everything with hidden
// visibility as we're going to link this object all over the place but
// don't want the symbols to get exported.
}
}
- // Creates an integer type with the given number of bits, e.g. i24
+ // Creates an integer type with the given number of bits, e.g., i24
pub fn ix_llcx(
llcx: &llvm::Context,
num_bits: u64
use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
use rustc_target::abi::FloatTy;
use rustc_mir::monomorphize::item::DefPathBasedNames;
-use type_::Type;
use rustc_codegen_ssa::traits::*;
+use type_::Type;
use std::fmt::Write;
let packed = false;
match name {
None => {
- cx.type_struct( &[fill], packed)
+ cx.type_struct(&[fill], packed)
}
Some(ref name) => {
- let llty = cx.type_named_struct( name);
+ let llty = cx.type_named_struct(name);
cx.set_struct_body(llty, &[fill], packed);
llty
}
}
}
- /// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.
+ /// Get the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
/// The pointee type of the pointer in `PlaceRef` is always this type.
/// For sized types, it is also the right LLVM type for an `alloca`
/// containing a value of that type, and most immediates (except `bool`).
// (according to its type), or null (which the
// niche field's scalar validity range encodes).
// This allows using `dereferenceable_or_null`
- // for e.g. `Option<&T>`, and this will continue
+ // for e.g., `Option<&T>`, and this will continue
// to work as long as we don't start using more
- // niches than just null (e.g. the first page
+ // niches than just null (e.g., the first page
// of the address space, or unaligned pointers).
if self.fields.offset(0) == offset {
Some(self.for_variant(cx, dataful_variant))
/// This trait is the total list of requirements needed by `back::link` and
/// represents the meaning of each option being passed down. This trait is then
/// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
-/// MSVC linker (e.g. `link.exe`) is being used.
+/// MSVC linker (e.g., `link.exe`) is being used.
pub trait Linker {
fn link_dylib(&mut self, lib: &str);
fn link_rust_dylib(&mut self, lib: &str, path: &Path);
// categories:
//
// 1. Those that are included statically via a static library
- // 2. Those included otherwise (e.g. dynamically or via a framework)
+ // 2. Those included otherwise (e.g., dynamically or via a framework)
//
// Although our LLVM module is not literally emitting code for the
// statically included symbols, it's an export of our library which
let (base, info) = match bx.load_operand(src).val {
OperandValue::Pair(base, info) => {
// fat-ptr to fat-ptr unsize preserves the vtable
- // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
+ // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
// So we need to pointercast the base to ensure
// the types match up.
let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
}
// To avoid UB from LLVM, these two functions mask RHS with an
-// appropriate mask unconditionally (i.e. the fallback behavior for
+// appropriate mask unconditionally (i.e., the fallback behavior for
// all shifts). For 32- and 64-bit types, this matches the semantics
// of Java. (See related discussion on #1877 and #10183.)
use rustc::middle::cstore::{LibSource, CrateSource, NativeLibrary};
use syntax_pos::symbol::Symbol;
-// NB: This module needs to be declared first so diagnostics are
+// N.B., this module needs to be declared first so diagnostics are
// registered before they are used.
mod diagnostics;
// These sorts of types require an alloca. Note that
// is_llvm_immediate() may *still* be true, particularly
// for newtypes, but we currently force some types
- // (e.g. structs) into an alloca unconditionally, just so
+ // (e.g., structs) into an alloca unconditionally, just so
// that we don't have to deal with having two pathways
// (gep vs extractvalue etc).
analyzer.not_ssa(mir::Local::new(index));
PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) => {
- // Reads from uninitialized variables (e.g. in dead code, after
+ // Reads from uninitialized variables (e.g., in dead code, after
// optimizations) require locals to be in (uninitialized) memory.
- // NB: there can be uninitialized reads of a local visited after
+ // N.B., there can be uninitialized reads of a local visited after
// an assignment to that local, if they happen on disjoint paths.
let ssa_read = match self.first_assignment(local) {
Some(assignment_location) => {
};
if Some(local) == mir.spread_arg {
- // This argument (e.g. the last argument in the "rust-call" ABI)
+ // This argument (e.g., the last argument in the "rust-call" ABI)
// is a tuple that was spread at the ABI level and now we have
// to reconstruct it into a tuple local variable, from multiple
// individual LLVM function arguments.
// because that's what the llvm.dbg.declare intrinsic expects.
// FIXME(eddyb) this shouldn't be necessary but SROA seems to
- // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
+ // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e., it
// doesn't actually strip the offset when splitting the closure
// environment into its components so it ends up out of bounds.
// (cuviper) It seems to be fine without the alloca on LLVM 6 and later.
layout::Variants::Tagged { ref tag, .. } => {
let signed = match tag.value {
// We use `i1` for bytes that are always `0` or `1`,
- // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
+ // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
// let LLVM interpret the `i1` as signed, because
- // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
+ // then `i1 1` (i.e., E::B) is effectively `i8 -1`.
layout::Int(_, signed) => !tag.is_bool() && signed,
_ => false
};
if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
if let layout::Int(_, s) = scalar.value {
// We use `i1` for bytes that are always `0` or `1`,
- // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
+ // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
// let LLVM interpret the `i1` as signed, because
- // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
+ // then `i1 1` (i.e., E::B) is effectively `i8 -1`.
signed = !scalar.is_bool() && s;
let er = scalar.valid_range_exclusive(bx.cx());
/// Use this function when you intend to define a global. This function will
/// return None if the name already has a definition associated with it. In that
/// case an error should be reported to the user, because it usually happens due
- /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
+ /// to user’s fault (e.g., misuse of #[no_mangle] or #[export_name] attributes).
fn define_global(&self, name: &str, ty: Self::Type) -> Option<Self::Value>;
/// Declare a private global
fn type_i64(&self) -> Self::Type;
fn type_i128(&self) -> Self::Type;
- // Creates an integer type with the given number of bits, e.g. i24
+ // Creates an integer type with the given number of bits, e.g., i24
fn type_ix(&self, num_bits: u64) -> Self::Type;
fn type_isize(&self) -> Self::Type;
//! order to also avoid inter-crate conflicts two more measures are taken:
//!
//! - The name of the crate containing the symbol is prepended to the symbol
-//! name, i.e. symbols are "crate qualified". For example, a function `foo` in
+//! name, i.e., symbols are "crate qualified". For example, a function `foo` in
//! module `bar` in crate `baz` would get a symbol name like
//! `baz::bar::foo::{hash}` instead of just `bar::foo::{hash}`. This avoids
//! simple conflicts between functions from different crates.
/// indices. Cannot be used during a transaction.
///
/// Beforehand, all nodes must be marked as `Done` and no cycles
- /// on these nodes may be present. This is done by e.g. `process_cycles`.
+ /// on these nodes may be present. This is done by e.g., `process_cycles`.
#[inline(never)]
fn compress(&mut self, do_completed: DoCompleted) -> Option<Vec<O>> {
let nodes_len = self.nodes.len();
## Mutable reference
When the owned container implements `DerefMut`, it is also possible to make
-a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`)
+a _mutable owning reference_. (e.g., with `Box`, `RefMut`, `MutexGuard`)
```
extern crate owning_ref;
/// use owning_ref::{OwningRef, Erased};
///
/// fn main() {
- /// // NB: Using the concrete types here for explicitness.
+ /// // N.B., using the concrete types here for explicitness.
/// // For less verbose code type aliases like `BoxRef` are provided.
///
/// let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]>
/// use owning_ref::{OwningRefMut, Erased};
///
/// fn main() {
- /// // NB: Using the concrete types here for explicitness.
+ /// // N.B., using the concrete types here for explicitness.
/// // For less verbose code type aliases like `BoxRef` are provided.
///
/// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]>
unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
}
-// NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision
-// about which handle creation to use (i.e. read() vs try_read()) as well as
+// N.B., implementing ToHandle{,Mut} for Mutex and RwLock requires a decision
+// about which handle creation to use (i.e., read() vs try_read()) as well as
// what to do with error results.
/// Typedef of a owning reference that uses a `Box` as the owner.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-/// A vector type optimized for cases where this size is usually 0 (c.f. `SmallVector`).
+/// A vector type optimized for cases where this size is usually 0 (cf. `SmallVector`).
/// The `Option<Box<..>>` wrapping allows us to represent a zero sized vector with `None`,
/// which uses only a single (null) pointer.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
///
/// The intuition is that this moves "one step up" through a lattice
/// (where the relation is encoding the `<=` relation for the lattice).
- /// So e.g. if the relation is `->` and we have
+ /// So e.g., if the relation is `->` and we have
///
/// ```
/// a -> b -> d -> f
// except according to those terms.
use rustc::dep_graph::DepGraph;
-use rustc::hir::{self, map as hir_map};
+use rustc::hir;
use rustc::hir::lowering::lower_crate;
-use rustc_data_structures::fingerprint::Fingerprint;
-use rustc_data_structures::stable_hasher::StableHasher;
-use rustc_mir as mir;
-use rustc::session::{CompileResult, CrateDisambiguator, Session};
-use rustc::session::CompileIncomplete;
-use rustc::session::config::{self, Input, OutputFilenames, OutputType};
-use rustc::session::search_paths::PathKind;
+use rustc::hir::map as hir_map;
use rustc::lint;
use rustc::middle::{self, reachable, resolve_lifetime, stability};
use rustc::middle::privacy::AccessLevels;
use rustc::traits;
use rustc::util::common::{install_panic_hook, time, ErrorReported};
use rustc::util::profiling::ProfileCategory;
+use rustc::session::{CompileResult, CrateDisambiguator, Session};
+use rustc::session::CompileIncomplete;
+use rustc::session::config::{self, Input, OutputFilenames, OutputType};
+use rustc::session::search_paths::PathKind;
use rustc_allocator as allocator;
use rustc_borrowck as borrowck;
+use rustc_codegen_utils::codegen_backend::CodegenBackend;
+use rustc_data_structures::fingerprint::Fingerprint;
+use rustc_data_structures::stable_hasher::StableHasher;
+use rustc_data_structures::sync::{self, Lrc, Lock};
use rustc_incremental;
-use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
use rustc_metadata::creader::CrateLoader;
use rustc_metadata::cstore::{self, CStore};
+use rustc_mir as mir;
+use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion};
+use rustc_plugin as plugin;
+use rustc_plugin::registry::Registry;
+use rustc_privacy;
+use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
use rustc_traits;
-use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_typeck as typeck;
-use rustc_privacy;
-use rustc_plugin::registry::Registry;
-use rustc_plugin as plugin;
-use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion};
-use super::Compilation;
+use syntax::{self, ast, attr, diagnostics, visit};
+use syntax::early_buffered_lints::BufferedEarlyLint;
+use syntax::ext::base::ExtCtxt;
+use syntax::fold::Folder;
+use syntax::parse::{self, PResult};
+use syntax::util::node_count::NodeCounter;
+use syntax::util::lev_distance::find_best_match_for_name;
+use syntax::symbol::Symbol;
+use syntax_pos::{FileName, hygiene};
+use syntax_ext;
use serialize::json;
use std::io::{self, Write};
use std::iter;
use std::path::{Path, PathBuf};
-use rustc_data_structures::sync::{self, Lrc, Lock};
use std::sync::mpsc;
-use syntax::{self, ast, attr, diagnostics, visit};
-use syntax::early_buffered_lints::BufferedEarlyLint;
-use syntax::ext::base::ExtCtxt;
-use syntax::fold::Folder;
-use syntax::parse::{self, PResult};
-use syntax::util::node_count::NodeCounter;
-use syntax::util::lev_distance::find_best_match_for_name;
-use syntax::symbol::Symbol;
-use syntax_pos::{FileName, hygiene};
-use syntax_ext;
-use proc_macro_decls;
use pretty::ReplaceBodyWithLoop;
-
+use proc_macro_decls;
use profile;
+use super::Compilation;
#[cfg(not(parallel_queries))]
pub fn spawn_thread_pool<F: FnOnce(config::Options) -> R + sync::Send, R: sync::Send>(
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! The various pretty print routines.
+//! The various pretty-printing routines.
-pub use self::UserIdentifiedItem::*;
-pub use self::PpSourceMode::*;
-pub use self::PpMode::*;
-use self::NodesMatchingUII::*;
-
-use {abort_on_err, driver};
-
-use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
use rustc::cfg;
use rustc::cfg::graphviz::LabelledCFG;
+use rustc::hir;
+use rustc::hir::map as hir_map;
+use rustc::hir::map::blocks;
+use rustc::hir::print as pprust_hir;
use rustc::session::Session;
use rustc::session::config::{Input, OutputFilenames};
+use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
use rustc_borrowck as borrowck;
use rustc_borrowck::graphviz as borrowck_dot;
use rustc_data_structures::thin_vec::ThinVec;
use rustc_metadata::cstore::CStore;
-
use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
use syntax::ast::{self, BlockCheckMode};
use std::str::FromStr;
use std::mem;
-use rustc::hir::map as hir_map;
-use rustc::hir::map::blocks;
-use rustc::hir;
-use rustc::hir::print as pprust_hir;
+pub use self::UserIdentifiedItem::*;
+pub use self::PpSourceMode::*;
+pub use self::PpMode::*;
+use self::NodesMatchingUII::*;
+use {abort_on_err, driver};
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum PpSourceMode {
//! # Standalone Tests for the Inference Module
-use std::path::PathBuf;
-use std::sync::mpsc;
-
use driver;
use errors;
use errors::emitter::Emitter;
use errors::{DiagnosticBuilder, Level};
+use rustc::hir;
use rustc::hir::map as hir_map;
use rustc::infer::outlives::env::OutlivesEnvironment;
use rustc::infer::type_variable::TypeVariableOrigin;
use syntax::symbol::Symbol;
use syntax_pos::DUMMY_SP;
-use rustc::hir;
+use std::path::PathBuf;
+use std::sync::mpsc;
struct Env<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
infcx: &'a infer::InferCtxt<'a, 'gcx, 'tcx>,
let arenas = ty::AllArenas::new();
let hir_map = hir_map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
- // run just enough stuff to build a tcx:
+ // Run just enough stuff to build a tcx.
let (tx, _rx) = mpsc::channel();
let outputs = OutputFilenames {
out_directory: PathBuf::new(),
}
pub fn create_simple_region_hierarchy(&mut self) {
- // creates a region hierarchy where 1 is root, 10 and 11 are
- // children of 1, etc
+ // Creates a region hierarchy where 1 is root, 10 and 11 are
+ // children of 1, etc.
let dscope = region::Scope {
id: hir::ItemLocalId::from_u32(1),
obligations,
value: (),
}) => {
- // None of these tests should require nested obligations:
+ // None of these tests should require nested obligations.
assert!(obligations.is_empty());
}
Err(ref e) => {
env.assert_eq(t_rptr1, t_rptr1);
env.assert_eq(t_rptr10, t_rptr10);
- // will cause an error when regions are resolved
+ // This will cause an error when regions are resolved.
env.make_subtype(t_rptr10, t_rptr1);
})
}
//!
//! fn(&'a isize) <: for<'b> fn(&'b isize)
//!
- //! does NOT hold.
+ //! *does not* hold.
test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
env.create_simple_region_hierarchy();
//!
//! for<'a> fn(&'a isize) <: fn(&'b isize)
//!
- //! DOES hold.
+ //! *does* hold.
test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
env.create_simple_region_hierarchy();
fn subst_ty_renumber_some_bounds() {
test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
// Situation:
- // Theta = [A -> &'a foo]
+ // `Theta = [A -> &'a foo]`
let t_rptr_bound1 = env.t_rptr_late_bound(1);
- // t_source = (A, fn(A))
+ // `t_source = (A, fn(A))`
let t_source = {
let t_param = env.t_param(0);
env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil()))
let substs = env.infcx.tcx.intern_substs(&[t_rptr_bound1.into()]);
let t_substituted = t_source.subst(env.infcx.tcx, substs);
- // t_expected = (&'a isize, fn(&'a isize))
+ // `t_expected = (&'a isize, fn(&'a isize))`
//
- // but not that the Debruijn index is different in the different cases.
+ // However, note that the Debruijn index is different in the different cases.
let t_expected = {
let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, d2());
env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil()))
fn escaping() {
test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
// Situation:
- // Theta = [A -> &'a foo]
+ // `Theta = [A -> &'a foo]`
env.create_simple_region_hierarchy();
assert!(!env.t_nil().has_escaping_bound_vars());
let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, d2());
assert!(t_rptr_bound2.has_escaping_bound_vars());
- // t_fn = fn(A)
+ // `t_fn = fn(A)`
let t_param = env.t_param(0);
assert!(!t_param.has_escaping_bound_vars());
let t_fn = env.t_fn(&[t_param], env.t_nil());
test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
let re_bound1 = env.re_late_bound_with_debruijn(1, d1());
- // type t_source<'a> = fn(&'a isize)
+ // `type t_source<'a> = fn(&'a isize)`
let t_source = {
let re_early = env.re_early_bound(0, "'a");
env.t_fn(&[env.t_rptr(re_early)], env.t_nil())
let substs = env.infcx.tcx.intern_substs(&[re_bound1.into()]);
let t_substituted = t_source.subst(env.infcx.tcx, substs);
- // t_expected = fn(&'a isize)
+ // `t_expected = fn(&'a isize)`
//
// but not that the Debruijn index is different in the different cases.
let t_expected = {
];
/// DepNodes for MirValidated/Optimized, which is relevant in "executable"
-/// code, i.e. functions+methods
+/// code, i.e., functions+methods
const BASE_MIR: &[&str] = &[
label_strs::MirOptimized,
label_strs::MirValidated,
// Module-level inline assembly (from global_asm!)
HirItem::GlobalAsm(..) => ("ItemGlobalAsm", LABELS_HIR_ONLY),
- // A type alias, e.g. `type Foo = Bar<u8>`
+ // A type alias, e.g., `type Foo = Bar<u8>`
HirItem::Ty(..) => ("ItemTy", LABELS_HIR_ONLY),
- // An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
+ // An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
HirItem::Enum(..) => ("ItemEnum", LABELS_ADT),
- // A struct definition, e.g. `struct Foo<A> {x: A}`
+ // A struct definition, e.g., `struct Foo<A> {x: A}`
HirItem::Struct(..) => ("ItemStruct", LABELS_ADT),
- // A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
+ // A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
HirItem::Union(..) => ("ItemUnion", LABELS_ADT),
// Represents a Trait Declaration
}
}
- // no new keywords yet for 2018 edition and beyond
+ // There are no new keywords yet for the 2018 edition and beyond.
// However, `await` is a "false" keyword in the 2018 edition,
// and can only be used if the `async_await` feature is enabled.
// Otherwise, we emit an error.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Lints in the Rust compiler.
+//! # Lints in the Rust compiler
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc_plugin` respectively.
//!
-//! # Note
+//! ## Note
//!
//! This API is completely unstable and subject to change.
extern crate syntax_pos;
extern crate rustc_data_structures;
+mod diagnostics;
+mod nonstandard_style;
+pub mod builtin;
+mod types;
+mod unused;
+
use rustc::lint;
use rustc::lint::{LateContext, LateLintPass, LintPass, LintArray};
use rustc::lint::builtin::{
use rustc::hir;
use syntax::ast;
+use syntax::edition::Edition;
use syntax_pos::Span;
use session::Session;
-use syntax::edition::Edition;
use lint::LintId;
use lint::FutureIncompatibleInfo;
-mod diagnostics;
-mod nonstandard_style;
-pub mod builtin;
-mod types;
-mod unused;
-
use nonstandard_style::*;
use builtin::*;
use types::*;
// and include the full URL, sort items in ascending order of issue numbers.
// - Later, change lint to error
// - Eventually, remove lint
- store.register_future_incompatible(sess,
- vec![
+ store.register_future_incompatible(sess, vec![
FutureIncompatibleInfo {
id: LintId::of(PRIVATE_IN_PUBLIC),
reference: "issue #34537 <https://github.com/rust-lang/rust/issues/34537>",
},
]);
- // Register renamed and removed lints
+ // Register renamed and removed lints.
store.register_renamed("single_use_lifetime", "single_use_lifetimes");
store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths");
store.register_renamed("bare_trait_object", "bare_trait_objects");
store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
store.register_removed("negate_unsigned", "cast a signed value instead");
store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
- // Register lint group aliases
+ // Register lint group aliases.
store.register_group_alias("nonstandard_style", "bad_style");
- // This was renamed to raw_pointer_derive, which was then removed,
- // so it is also considered removed
+ // This was renamed to `raw_pointer_derive`, which was then removed,
+ // so it is also considered removed.
store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
store.register_removed("drop_with_repr_extern", "drop flags have been removed");
store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use rustc::hir::{self, GenericParamKind, PatKind};
use rustc::hir::def::Def;
+use rustc::hir::intravisit::FnKind;
use rustc::ty;
+use rustc_target::spec::abi::Abi;
use lint::{LateContext, LintContext, LintArray};
use lint::{LintPass, LateLintPass};
-
-use rustc_target::spec::abi::Abi;
use syntax::ast;
use syntax::attr;
use syntax_pos::Span;
-use rustc::hir::{self, GenericParamKind, PatKind};
-use rustc::hir::intravisit::FnKind;
-
#[derive(PartialEq)]
pub enum MethodLateContext {
TraitAutoImpl,
// NOTE: This crate only exists to allow linking on mingw targets.
/// Initialize targets enabled by the build script via `cfg(llvm_component = "...")`.
-/// NB: this function can't be moved to `rustc_codegen_llvm` because of the `cfg`s.
+/// N.B., this function can't be moved to `rustc_codegen_llvm` because of the `cfg`s.
pub fn initialize_available_targets() {
macro_rules! init_target(
($cfg:meta, $($method:ident),*) => { {
/// Original name of the crate.
pub name: Symbol,
- /// Name of the crate as imported. I.e. if imported with
+ /// Name of the crate as imported. I.e., if imported with
/// `extern crate foo as bar;` this will be `bar`.
pub imported_name: Symbol,
Lrc::new(link_args::collect(tcx))
},
- // Returns a map from a sufficiently visible external item (i.e. an
+ // Returns a map from a sufficiently visible external item (i.e., an
// external item that is visible from at least one local module) to a
// sufficiently visible parent (considering modules that re-export the
// external item to be parents).
// Ok so at this point we've determined that `(lib, kind)` above is
// a candidate crate to load, and that `slot` is either none (this
// is the first crate of its kind) or if some the previous path has
- // the exact same hash (e.g. it's the exact same crate).
+ // the exact same hash (e.g., it's the exact same crate).
//
// In principle these two candidate crates are exactly the same so
// we can choose either of them to link. As a stupidly gross hack,
}
/// Metadata encoding version.
-/// NB: increment this if you change the format of metadata such that
+/// N.B., increment this if you change the format of metadata such that
/// the rustc version can't be found to compare with `rustc_version()`.
pub const METADATA_VERSION: u8 = 4;
/// (part of) a non-`mut` local that occurs potentially after that
/// local has already been initialized. `place` is the path being
/// assigned; `err_place` is a place providing a reason why
- /// `place` is not mutable (e.g. the non-`mut` local `x` in an
+ /// `place` is not mutable (e.g., the non-`mut` local `x` in an
/// assignment to `x.f`).
pub(super) fn report_illegal_reassignment(
&mut self,
// ancestors; dataflow recurs on children when parents
// move (to support partial (re)inits).
//
- // (I.e. querying parents breaks scenario 7; but may want
+ // (I.e., querying parents breaks scenario 7; but may want
// to do such a query based on partial-init feature-gate.)
}
}
//
// (Distinct from handling of scenarios 1+2+4 above because
// `place` does not interfere with suffixes of its prefixes,
- // e.g. `a.b.c` does not interfere with `a.b.d`)
+ // e.g., `a.b.c` does not interfere with `a.b.d`)
//
// This code covers scenario 1.
//
// This does not use check_if_path_or_subpath_is_moved,
// because we want to *allow* reinitializations of fields:
- // e.g. want to allow
+ // e.g., want to allow
//
// `let mut s = ...; drop(s.x); s.x=Val;`
//
/// `u.a.x` and `a.b.y` are.
Arbitrary,
/// The places have the same type, and are either completely disjoint
- /// or equal - i.e. they can't "partially" overlap as can occur with
+ /// or equal - i.e., they can't "partially" overlap as can occur with
/// unions. This is the "base case" on which we recur for extensions
/// of the place.
EqualOrDisjoint,
#[derive(Debug)]
enum GroupedMoveError<'tcx> {
// Place expression can't be moved from,
- // e.g. match x[0] { s => (), } where x: &[String]
+ // e.g., match x[0] { s => (), } where x: &[String]
MovesFromPlace {
original_path: Place<'tcx>,
span: Span,
binds_to: Vec<Local>,
},
// Part of a value expression can't be moved from,
- // e.g. match &String::new() { &x => (), }
+ // e.g., match &String::new() { &x => (), }
MovesFromValue {
original_path: Place<'tcx>,
span: Span,
/// Constructs a "normal" graph from the constraint set; the graph makes it
/// easy to find the constraints affecting a particular region.
///
- /// NB: This graph contains a "frozen" view of the current
+ /// N.B., this graph contains a "frozen" view of the current
/// constraints. any new constraints added to the `ConstraintSet`
/// after the graph is built will not be present in the graph.
crate fn graph(&self, num_region_vars: usize) -> graph::NormalConstraintGraph {
/// Search the argument types for one that references fr (which should be a free region).
/// Returns Some(_) with the index of the input if one is found.
///
- /// NB: In the case of a closure, the index is indexing into the signature as seen by the
+ /// N.B., in the case of a closure, the index is indexing into the signature as seen by the
/// user - in particular, index 0 is not the implicit self parameter.
crate fn get_argument_index_for_region(
&self,
external_name: Option<ty::Region<'tcx>>,
}
-/// NB: The variants in `Cause` are intentionally ordered. Lower
+/// N.B., the variants in `Cause` are intentionally ordered. Lower
/// values are preferred when it comes to error messages. Do not
/// reorder willy nilly.
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
.buffer(errors_buffer);
} else {
// FIXME. We should handle this case better. It
- // indicates that we have e.g. some region variable
+ // indicates that we have e.g., some region variable
// whose value is like `'a+'b` where `'a` and `'b` are
// distinct unrelated univesal regions that are not
// known to outlive one another. It'd be nice to have
self.points.insert_all_into_row(r);
}
- /// Add all elements in `r_from` to `r_to` (because e.g. `r_to:
+ /// Add all elements in `r_from` to `r_to` (because e.g., `r_to:
/// r_from`).
crate fn add_region(&mut self, r_to: N, r_from: N) -> bool {
self.points.union_rows(r_from, r_to)
// If the user explicitly annotated the input types, extract
// those.
//
- // e.g. `|x: FxHashMap<_, &'static u32>| ...`
+ // e.g., `|x: FxHashMap<_, &'static u32>| ...`
let user_provided_sig;
if !self.tcx().is_closure(self.mir_def_id) {
user_provided_sig = None;
None => None,
Some(user_provided_poly_sig) => {
// Instantiate the canonicalized variables from
- // user-provided signature (e.g. the `_` in the code
+ // user-provided signature (e.g., the `_` in the code
// above) with fresh variables.
let (poly_sig, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
mir.span,
liveness_map: &'me NllLivenessMap,
/// Head of a linked list of **definitions** of each variable --
- /// definition in this context means assignment, e.g. `x` is
+ /// definition in this context means assignment, e.g., `x` is
/// defined in `x = y` but not `y`; that first def is the head of
/// a linked list that lets you enumerate all places the variable
/// is assigned.
// except according to those terms.
//! This pass type-checks the MIR to ensure it is not broken.
+
#![allow(unreachable_code)]
use borrow_check::borrow_set::BorrowSet;
//
// There is no *easy* way of comparing the fields
// further on, because they might have different types
- // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
+ // (e.g., borrows of `u.a.0` and `u.b.y` where `.0` and
// `.y` come from different structs).
//
- // We could try to do some things here - e.g. count
+ // We could try to do some things here - e.g., count
// dereferences - but that's probably not a good
// idea, at least for now, so just give up and
// report a conflict. This is unsafe code anyway so
// borrowed place (at least in MIR as it is
// currently.)
//
- // e.g. a (mutable) borrow of `a[5]` while we read the
+ // e.g., a (mutable) borrow of `a[5]` while we read the
// array length of `a`.
debug!("borrow_conflicts_with_place: implicit field");
return false;
}
(ProjectionElem::Deref, _, Shallow(None)) => {
- // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
+ // e.g., a borrow of `*x.y` while we shallowly access `x.y` or some
// prefix thereof - the shallow access can't touch anything behind
// the pointer.
debug!("borrow_conflicts_with_place: shallow access behind ptr");
| (ProjectionElem::Downcast { .. }, _, _) => {
// Recursive case. This can still be disjoint on a
// further iteration if this a shallow access and
- // there's a deref later on, e.g. a borrow
+ // there's a deref later on, e.g., a borrow
// of `*x.y` while accessing `x`.
}
}
/// the place `a` with a "next" pointer to `a.b`). Created by
/// `unroll_place`.
///
-/// NB: This particular impl strategy is not the most obvious. It was
+/// N.B., this particular impl strategy is not the most obvious. It was
/// chosen because it makes a measurable difference to NLL
/// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
struct PlaceComponents<'p, 'tcx: 'p> {
/// Iterator over components; see `PlaceComponents::iter` for more
/// information.
///
-/// NB: This is not a *true* Rust iterator -- the code above just
+/// N.B., this is not a *true* Rust iterator -- the code above just
/// manually invokes `next`. This is because we (sometimes) want to
/// keep executing even after `None` has been returned.
struct PlaceComponentsIter<'p, 'tcx: 'p> {
(Place::Projection(pi1), Place::Projection(pi2)) => {
match (&pi1.elem, &pi2.elem) {
(ProjectionElem::Deref, ProjectionElem::Deref) => {
- // derefs (e.g. `*x` vs. `*x`) - recur.
+ // derefs (e.g., `*x` vs. `*x`) - recur.
debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
Overlap::EqualOrDisjoint
}
(ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
if f1 == f2 {
- // same field (e.g. `a.y` vs. `a.y`) - recur.
+ // same field (e.g., `a.y` vs. `a.y`) - recur.
debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
Overlap::EqualOrDisjoint
} else {
// Post-processing `place`: Enqueue any remaining
// work. Also, `place` may not be a prefix itself, but
- // may hold one further down (e.g. we never return
+ // may hold one further down (e.g., we never return
// downcasts here, but may return a base of a downcast).
'cursor: loop {
};
this.block_context.push(BlockFrame::Statement { ignores_expr_result });
- // Enter the remainder scope, i.e. the bindings' destruction scope.
+ // Enter the remainder scope, i.e., the bindings' destruction scope.
this.push_scope((remainder_scope, source_info));
let_scope_stack.push(remainder_scope);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! See docs in build/expr/mod.rs
+//! See docs in `build/expr/mod.rs`.
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::indexed_vec::Idx;
// must be handled above or else we get an
// infinite loop in the builder; see
- // e.g. `ExprKind::VarRef` above
+ // e.g., `ExprKind::VarRef` above
Category::Place => false,
_ => true,
impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
/// Builds a block of MIR statements to evaluate the HAIR `expr`.
/// If the original expression was an AST statement,
- /// (e.g. `some().code(&here());`) then `opt_stmt_span` is the
+ /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the
/// span of that statement (including its semicolon, if any).
/// Diagnostics use this span (which may be larger than that of
/// `expr`) to identify when statement temporaries are dropped.
//! In general, there are a number of things for which it's convenient
//! to just call `builder.into` and have it emit its result into a
//! given location. This is basically for expressions or things that can be
-//! wrapped up as expressions (e.g. blocks). To make this ergonomic, we use this
+//! wrapped up as expressions (e.g., blocks). To make this ergonomic, we use this
//! latter `EvalInto` trait.
use build::{BlockAnd, Builder};
// pattern, which means there may be more than one candidate
// *per arm*. These candidates are kept sorted such that the
// highest priority candidate comes first in the list.
- // (i.e. same order as in source)
+ // (i.e., same order as in source)
let candidates: Vec<_> = arms.iter()
.enumerate()
// Tricky business: For `ref id` and `ref mut id`
// patterns, we want `id` within the guard to
// correspond to a temp of type `& &T` or `& &mut
- // T` (i.e. a "borrow of a borrow") that is
+ // T` (i.e., a "borrow of a borrow") that is
// implicitly dereferenced.
//
// To borrow a borrow, we need that inner borrow
/// Add a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
- /// NB: **No cleanup is scheduled for this temporary.** You should
+ /// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_drop` once the temporary is initialized.
pub fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> {
let temp = self.local_decls.push(LocalDecl::new_temp(ty, span));
pub(crate) struct CachedBlock {
/// The cached block for the cleanups-on-diverge path. This block
/// contains code to run the current drop and all the preceding
- /// drops (i.e. those having lower index in Drop’s Scope drop
+ /// drops (i.e., those having lower index in Drop’s Scope drop
/// array)
unwind: Option<BasicBlock>,
/// Block to branch into when the loop or block terminates (either by being `break`-en out
/// from, or by having its condition to become false)
pub break_block: BasicBlock,
- /// The destination of the loop/block expression itself (i.e. where to put the result of a
+ /// The destination of the loop/block expression itself (i.e., where to put the result of a
/// `break` expression)
pub break_destination: Place<'tcx>,
}
//
// Note that this code iterates scopes from the inner-most to the outer-most,
// invalidating caches of each scope visited. This way bare minimum of the
- // caches gets invalidated. i.e. if a new drop is added into the middle scope, the
+ // caches gets invalidated. i.e., if a new drop is added into the middle scope, the
// cache of outer scpoe stays intact.
scope.invalidate_cache(!needs_drop, this_scope);
if this_scope {
/// effects at any point in the control-flow graph by starting with
/// the state at the start of the basic block (`reset_to_entry_of`)
/// and then replaying the effects of statements and terminators
-/// (e.g. via `reconstruct_statement_effect` and
+/// (e.g., via `reconstruct_statement_effect` and
/// `reconstruct_terminator_effect`; don't forget to call
/// `apply_local_effect`).
pub struct FlowAtLocation<BD>
Place::Local(..) | Place::Static(..) => {} // okay
Place::Projection(..) => {
// ... can assign into projections,
- // e.g. `box (&mut _)`. Current
+ // e.g., `box (&mut _)`. Current
// conservative solution: force
// immediate activation here.
sets.gen(*index);
//
// FIXME(#46525): We *need* to do this for StorageLive as well as
// StorageDead, because lifetimes of match bindings with guards are
- // weird - i.e. this code
+ // weird - i.e., this code
//
// ```
// fn main() {
/// It abstracts over the FlowState and also completely hides the
/// underlying flow analysis results, because it needs to handle cases
/// where we are combining the results of *multiple* flow analyses
-/// (e.g. borrows + inits + uninits).
+/// (e.g., borrows + inits + uninits).
pub(crate) trait DataflowResultsConsumer<'a, 'tcx: 'a> {
type FlowState: FlowsAtLocation;
/// Parameterization for the precise form of data flow that is used.
/// `InitialFlow` handles initializing the bitvectors before any
/// code is inspected by the analysis. Analyses that need more nuanced
-/// initialization (e.g. they need to consult the results of some other
+/// initialization (e.g., they need to consult the results of some other
/// dataflow analysis to set up the initial bitvectors) should not
/// implement this.
pub trait InitialFlow {
/// A name describing the dataflow analysis that this
/// BitDenotation is supporting. The name should be something
- /// suitable for plugging in as part of a filename e.g. avoid
+ /// suitable for plugging in as part of a filename e.g., avoid
/// space-characters or other things that tend to look bad on a
/// file system, like slashes or periods. It is also better for
/// the name to be reasonably short, again because it will be
/// To reflect this, the `propagate_call_return` method of the
/// `BitDenotation` mutates `in_out` when propagating `in_out` via
/// a call terminator; such mutation is performed *last*, to
- /// ensure its side-effects do not leak elsewhere (e.g. into
+ /// ensure its side-effects do not leak elsewhere (e.g., into
/// unwind target).
fn propagate_bits_into_graph_successors_of(
&mut self,
//! The move-analysis portion of borrowck needs to work in an abstract
//! domain of lifted Places. Most of the Place variants fall into a
-//! one-to-one mapping between the concrete and abstract (e.g. a
+//! one-to-one mapping between the concrete and abstract (e.g., a
//! field-deref on a local-variable, `x.field`, has the same meaning
//! in both domains). Indexed-Projections are the exception: `a[x]`
//! needs to be treated as mapping to the same move path as `a[y]` as
// To ensure that both implicit and explicit coercions are
// handled the same way, we insert an extra layer of indirection here.
- // For explicit casts (e.g. 'foo as *const T'), the source of the 'Use'
+ // For explicit casts (e.g., 'foo as *const T'), the source of the 'Use'
// will be an ExprKind::Hair with the appropriate cast expression. Here,
// we make our Use source the generated Cast from the original coercion.
//
}
}
-/// Converts a list of named fields (i.e. for struct-like struct/enum ADTs) into FieldExprRef.
+/// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
fn field_refs<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
fields: &'tcx [hir::Field])
-> Vec<FieldExprRef<'tcx>> {
///
/// If we have this predicate, then we can easily compute both exhaustiveness of an
/// entire set of patterns and the individual usefulness of each one.
-/// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e. adding a wildcard
+/// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard
/// match doesn't increase the number of values we're matching)
-/// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e. adding a
+/// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e., adding a
/// pattern to those that have come before it doesn't increase the number of values
/// we're matching).
///
///
/// The algorithm for computing `U`
/// -------------------------------
-/// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns).
+/// The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
/// That means we're going to check the components from left-to-right, so the algorithm
/// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
/// This algorithm is realised in the `is_useful` function.
///
-/// Base case. (`n = 0`, i.e. an empty tuple pattern)
-/// - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`),
+/// Base case. (`n = 0`, i.e., an empty tuple pattern)
+/// - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`),
/// then `U(P, p_{m + 1})` is false.
/// - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
///
-/// Inductive step. (`n > 0`, i.e. whether there's at least one column
+/// Inductive step. (`n > 0`, i.e., whether there's at least one column
/// [which may then be expanded into further columns later])
/// We're going to match on the new pattern, `p_{m + 1}`.
/// - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
/// + All the constructors of the first component of the type exist within
/// all the rows (after having expanded OR-patterns). In this case:
/// `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
-/// I.e. the pattern `p_{m + 1}` is only useful when all the constructors are
+/// I.e., the pattern `p_{m + 1}` is only useful when all the constructors are
/// present *if* its later components are useful for the respective constructors
/// covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
/// + Some constructors are not present in the existing rows (after having expanded
/// - When we're testing for usefulness of a pattern and the pattern's first component is a
/// wildcard.
/// + If all the constructors appear in the matrix, we have a slight complication. By default,
-/// the behaviour (i.e. a disjunction over specialised matrices for each constructor) is
+/// the behaviour (i.e., a disjunction over specialised matrices for each constructor) is
/// invalid, because we want a disjunction over every *integer* in each range, not just a
/// disjunction over every range. This is a bit more tricky to deal with: essentially we need
/// to form equivalence classes of subranges of the constructor range for which the behaviour
/// of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more
/// detail in `split_grouped_constructors`.
/// + If some constructors are missing from the matrix, it turns out we don't need to do
-/// anything special (because we know none of the integers are actually wildcards: i.e. we
+/// anything special (because we know none of the integers are actually wildcards: i.e., we
/// can't span wildcards using ranges).
use self::Constructor::*;
#[derive(Clone, Debug, PartialEq)]
pub enum Constructor<'tcx> {
/// The constructor of all patterns that don't vary by constructor,
- /// e.g. struct patterns and fixed-length arrays.
+ /// e.g., struct patterns and fixed-length arrays.
Single,
/// Enum variants.
Variant(DefId),
/// patterns expanded by the specialization step.
///
/// When a pattern P is discovered to be useful, this function is used bottom-up
- /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
+ /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
/// of values, V, where each value in that set is not covered by any previously
/// used patterns and is covered by the pattern P'. Examples:
///
/// straightforward. See `signed_bias` for details.
///
/// `IntRange` is never used to encode an empty range or a "range" that wraps
-/// around the (offset) space: i.e. `range.lo <= range.hi`.
+/// around the (offset) space: i.e., `range.lo <= range.hi`.
#[derive(Clone)]
struct IntRange<'tcx> {
pub range: RangeInclusive<u128>,
}
/// Return a collection of ranges that spans the values covered by `ranges`, subtracted
- /// by the values covered by `self`: i.e. `ranges \ self` (in set notation).
+ /// by the values covered by `self`: i.e., `ranges \ self` (in set notation).
fn subtract_from(self,
tcx: TyCtxt<'_, 'tcx, 'tcx>,
ranges: Vec<Constructor<'tcx>>)
//
// There are 2 ways we can report a witness here.
// Commonly, we can report all the "free"
- // constructors as witnesses, e.g. if we have:
+ // constructors as witnesses, e.g., if we have:
//
// ```
// enum Direction { N, S, E, W }
// 1) If the user is matching against a non-exhaustive
// enum, there is no point in enumerating all possible
// variants, because the user can't actually match
- // against them himself, e.g. in an example like:
+ // against them himself, e.g., in an example like:
// ```
// let err: io::ErrorKind = ...;
// match err {
// case).
//
// 2) If the user didn't actually specify a constructor
- // in this arm, e.g. in
+ // in this arm, e.g., in
// ```
// let x: (Direction, Direction, bool) = ...;
// let (_, _, false) = x;
}
}
-/// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e. `is_useful` applied
+/// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied
/// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
cx: &mut MatchCheckCtxt<'a, 'tcx>,
/// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
/// mean creating a separate constructor for every single value in the range, which is clearly
/// impractical. However, observe that for some ranges of integers, the specialisation will be
-/// identical across all values in that range (i.e. there are equivalence classes of ranges of
+/// identical across all values in that range (i.e., there are equivalence classes of ranges of
/// constructors based on their `is_useful_specialized` outcome). These classes are grouped by
/// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
/// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
/// the group of intersecting patterns changes (using the method described below).
/// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
/// on actual integers. The nice thing about this is that the number of subranges is linear in the
-/// number of rows in the matrix (i.e. the number of cases in the `match` statement), so we don't
+/// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
/// need to be worried about matching over gargantuan ranges.
///
/// Essentially, given the first column of a matrix representing ranges, looking like the following:
// Third, perform some lints.
for pat in &arm.pats {
- check_for_bindings_named_the_same_as_variants(self, pat);
+ check_for_bindings_named_same_as_variants(self, pat);
}
}
}
}
-fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
+fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
pat.walk(|p| {
if let PatKind::Binding(_, _, ident, None) = p.node {
if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
/// matches against a slice, checking the length and extracting elements.
/// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
- /// e.g. `&[ref xs..]`.
+ /// e.g., `&[ref xs..]`.
Slice {
prefix: Vec<Pattern<'tcx>>,
slice: Option<Pattern<'tcx>>,
type FrameExtra;
/// Extra data stored in memory. A reference to this is available when `AllocExtra`
- /// gets initialized, so you can e.g. have an `Rc` here if there is global state you
+ /// gets initialized, so you can e.g., have an `Rc` here if there is global state you
/// need access to in the `AllocExtra` hooks.
type MemoryExtra: Default;
}
// `Memory` has to depend on the `Machine` because some of its operations
-// (e.g. `get`) call a `Machine` hook.
+// (e.g., `get`) call a `Machine` hook.
pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
/// Allocations local to this instance of the miri engine. The kind
/// helps ensure that the same mechanism is used for allocation and
pub align: Align,
/// Metadata for unsized places. Interpretation is up to the type.
/// Must not be present for sized types, but can be missing for unsized types
- /// (e.g. `extern type`).
+ /// (e.g., `extern type`).
pub meta: Option<Scalar<Tag, Id>>,
}
}
} else {
// Go through the layout. There are lots of types that support a length,
- // e.g. SIMD types.
+ // e.g., SIMD types.
match self.layout.fields {
layout::FieldPlacement::Array { count, .. } => Ok(count),
_ => bug!("len not supported on sized type {:?}", self.layout.ty),
// a fake pointer? Are we even called for ZST?
// We need the layout of the local. We can NOT use the layout we got,
- // that might e.g. be an inner field of a struct with `Scalar` layout,
+ // that might e.g., be an inner field of a struct with `Scalar` layout,
// that has different alignment than the outer field.
let local_layout = self.layout_of_local(&self.stack[frame], local)?;
let ptr = self.allocate(local_layout, MemoryKind::Stack)?;
use super::{EvalContext, Machine};
-/// Classify whether an operator is "left-homogeneous", i.e. the LHS has the
+/// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
/// same type as the result.
#[inline]
fn binop_left_homogeneous(op: mir::BinOp) -> bool {
false,
}
}
-/// Classify whether an operator is "right-homogeneous", i.e. the RHS has the
+/// Classify whether an operator is "right-homogeneous", i.e., the RHS has the
/// same type as the LHS.
#[inline]
fn binop_right_homogeneous(op: mir::BinOp) -> bool {
use rustc::mir::StatementKind::*;
- // Some statements (e.g. box) push new stack frames.
+ // Some statements (e.g., box) push new stack frames.
// We have to record the stack frame number *before* executing the statement.
let frame_idx = self.cur_frame();
self.tcx.span = stmt.source_info.span;
return err!(FunctionAbiMismatch(caller_abi, Abi::RustIntrinsic));
}
// The intrinsic itself cannot diverge, so if we got here without a return
- // place... (can happen e.g. for transmute returning `!`)
+ // place... (can happen e.g., for transmute returning `!`)
let dest = match dest {
Some(dest) => dest,
None => return err!(Unreachable)
// Check if we have encountered this pointer+layout combination
// before. Proceed recursively even for integer pointers, no
// reason to skip them! They are (recursively) valid for some ZST,
- // but not for others (e.g. `!` is a ZST).
+ // but not for others (e.g., `!` is a ZST).
let op = place.into();
if ref_tracking.seen.insert(op) {
trace!("Recursing below ptr {:#?}", *op);
// NOTE: Keep this in sync with the handling of integer and float
// types above, in `visit_primitive`.
// In run-time mode, we accept pointers in here. This is actually more
- // permissive than a per-element check would be, e.g. we accept
+ // permissive than a per-element check would be, e.g., we accept
// an &[u8] that contains a pointer even though bytewise checking would
// reject it. However, that's good: We don't inherently want
// to reject those pointers, we just do not have the machinery to
// is very relevant for `NonNull` and similar structs: We need to visit them
// at their scalar layout *before* descending into their fields.
// FIXME: We could avoid some redundant checks here. For newtypes wrapping
- // scalars, we do the same check on every "level" (e.g. first we check
+ // scalars, we do the same check on every "level" (e.g., first we check
// MyNewtype and then the scalar in there).
match v.layout().abi {
layout::Abi::Uninhabited => {
//FIXME(#54444) rewrite this lint to use the dataflow framework
// Walk through this function (say `f`) looking to see if
- // every possible path references itself, i.e. the function is
+ // every possible path references itself, i.e., the function is
// called recursively unconditionally. This is done by trying
// to find a path from the entry node to the exit node that
// *doesn't* call `f` by traversing from the entry while
- // pretending that calls of `f` are sinks (i.e. ignoring any
+ // pretending that calls of `f` are sinks (i.e., ignoring any
// exit edges from them).
//
// NB. this has an edge case with non-returning statements,
// considers this to be an error for two reasons, (a) it is
// easier to implement, and (b) it seems rare to actually want
// to have behaviour like the above, rather than
- // e.g. accidentally recursing after an assert.
+ // e.g., accidentally recursing after an assert.
let basic_blocks = mir.basic_blocks();
let mut reachable_without_self_call_queue = vec![mir::START_BLOCK];
}
// Check the number of self calls because a function that
- // doesn't return (e.g. calls a `-> !` function or `loop { /*
+ // doesn't return (e.g., calls a `-> !` function or `loop { /*
// no break */ }`) shouldn't be linted unless it actually
// recurs.
if !reached_exit_without_self_call && !self_call_locations.is_empty() {
/// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
/// `(SomeStruct, SomeTrait)`.
///
-/// Finally, there is also the case of custom unsizing coercions, e.g. for
+/// Finally, there is also the case of custom unsizing coercions, e.g., for
/// smart pointers such as `Rc` and `Arc`.
fn find_vtable_types_for_unsizing<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
source_ty: Ty<'tcx>,
//!
//! - There are two codegen units for every source-level module:
//! - One for "stable", that is non-generic, code
-//! - One for more "volatile" code, i.e. monomorphized instances of functions
+//! - One for more "volatile" code, i.e., monomorphized instances of functions
//! defined in that module
//!
//! In order to see why this heuristic makes sense, let's take a look at when a
{
debug!("unsafety_violations({:?})", def_id);
- // NB: this borrow is valid because all the consumers of
+ // N.B., this borrow is valid because all the consumers of
// `mir_built` force this.
let mir = &tcx.mir_built(def_id).borrow();
})?;
Some((res, span))
},
- // We could get more projections by using e.g. `operand_projection`,
+ // We could get more projections by using e.g., `operand_projection`,
// but we do not even have the stack frame set up properly so
// an `Index` projection would throw us off-track.
_ => None,
// The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
let tuple_tmp_args =
tuple_tys.iter().enumerate().map(|(i, ty)| {
- // This is e.g. `tuple_tmp.0` in our example above.
+ // This is e.g., `tuple_tmp.0` in our example above.
let tuple_field = Operand::Move(tuple.clone().field(Field::new(i), ty));
- // Spill to a local to make e.g. `tmp0`.
+ // Spill to a local to make e.g., `tmp0`.
self.create_temp_if_necessary(tuple_field, callsite, caller_mir)
});
}
} else if let TempState::Defined { ref mut uses, .. } = *temp {
// We always allow borrows, even mutable ones, as we need
- // to promote mutable borrows of some ZSTs e.g. `&mut []`.
+ // to promote mutable borrows of some ZSTs e.g., `&mut []`.
let allowed_use = context.is_borrow() || context.is_nonmutating_use();
debug!("visit_local: allowed_use={:?}", allowed_use);
if allowed_use {
use rustc_data_structures::bit_set::BitSet;
use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::sync::Lrc;
+use rustc_target::spec::abi::Abi;
use rustc::hir;
use rustc::hir::def_id::DefId;
use rustc::mir::interpret::ConstValue;
use rustc::mir::traversal::ReversePostorder;
use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
use rustc::middle::lang_items;
-use rustc_target::spec::abi::Abi;
+use rustc::session::config::nightly_options;
use syntax::ast::LitKind;
use syntax::feature_gate::{UnstableFeatures, feature_err, emit_feature_err, GateIssue};
use syntax_pos::{Span, DUMMY_SP};
use std::fmt;
-use rustc_data_structures::sync::Lrc;
use std::usize;
use transform::{MirPass, MirSource};
self.add(qualif);
// Just in case the type is more specific than
- // the definition, e.g. impl associated const
+ // the definition, e.g., impl associated const
// with type parameters, take it into account.
self.qualif.restrict(constant.literal.ty, self.tcx, self.param_env);
}
}
}
_ => {
- // in normal functions we only care about promotion
+ // In normal functions we only care about promotion.
if self.mode == Mode::Fn {
- // never promote const fn calls of
- // functions without #[rustc_promotable]
+ // Never promote const fn calls of
+ // functions without `#[rustc_promotable]`.
if self.tcx.is_promotable_const_fn(def_id) {
is_const_fn = true;
is_promotable_const_fn = true;
is_const_fn = true;
}
} else {
- // stable const fn or unstable const fns with their feature gate
+ // stable const fns or unstable const fns with their feature gate
// active
if self.tcx.is_const_fn(def_id) {
is_const_fn = true;
} else if self.is_const_panic_fn(def_id) {
- // check the const_panic feature gate
+ // Check the const_panic feature gate.
// FIXME: cannot allow this inside `allow_internal_unstable`
// because that would make `panic!` insta stable in constants,
- // since the macro is marked with the attr
+ // since the macro is marked with the attribute.
if self.tcx.features().const_panic {
is_const_fn = true;
} else {
- // don't allow panics in constants without the feature gate
+ // Don't allow panics in constants without the feature gate.
emit_feature_err(
&self.tcx.sess.parse_sess,
"const_panic",
&format!("panicking in {}s is unstable", self.mode),
);
}
- } else if let Some(feat) = self.tcx.is_unstable_const_fn(def_id) {
- // check `#[unstable]` const fns or `#[rustc_const_unstable]`
- // functions without the feature gate active in this crate to
- // report a better error message than the one below
+ } else if let Some(feature)
+ = self.tcx.is_unstable_const_fn(def_id) {
+ // Check `#[unstable]` const fns or `#[rustc_const_unstable]`
+ // functions without the feature gate active in this crate in
+ // order to report a better error message than the one below.
if self.span.allows_unstable() {
- // `allow_internal_unstable` can make such calls stable
+ // `allow_internal_unstable` can make such calls stable.
is_const_fn = true;
} else {
let mut err = self.tcx.sess.struct_span_err(self.span,
&format!("`{}` is not yet stable as a const fn",
self.tcx.item_path_str(def_id)));
- help!(&mut err,
- "in Nightly builds, add `#![feature({})]` \
- to the crate attributes to enable",
- feat);
+ if nightly_options::is_nightly_build() {
+ help!(&mut err,
+ "add `#![feature({})]` to the \
+ crate attributes to enable",
+ feature);
+ }
err.emit();
}
} else {
- // FIXME(#24111) Remove this check when const fn stabilizes
+ // FIXME(#24111): remove this check when const fn stabilizes.
let (msg, note) = if let UnstableFeatures::Disallow =
self.tcx.sess.opts.unstable_features {
(format!("calls in {}s are limited to \
// we care about constness, not promotability.
// If we checked for promotability, we'd miss out on
// the results of function calls (which are never promoted
- // in runtime code)
+ // in runtime code).
// This is not a problem, because the argument explicitly
// requests constness, in contrast to regular promotion
// which happens even without the user requesting it.
});
}
- // non-const fn calls.
+ // non-const fn calls
if !is_const_fn {
self.qualif = Qualif::NOT_CONST;
if self.mode != Mode::Fn {
// Deny *any* live drops anywhere other than functions.
if self.mode != Mode::Fn {
- // HACK(eddyb) Emulate a bit of dataflow analysis,
+ // HACK(eddyb): emulate a bit of dataflow analysis,
// conservatively, that drop elaboration will do.
let needs_drop = if let Place::Local(local) = *place {
if self.local_qualif[local].map_or(true, |q| q.contains(Qualif::NEEDS_DROP)) {
fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
-> (u8, Lrc<BitSet<Local>>) {
- // NB: This `borrow()` is guaranteed to be valid (i.e., the value
+ // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
// cannot yet be stolen), because `mir_validated()`, which steals
// from `mir_const(), forces this query to execute before
// performing the steal.
}
StatementKind::Assign(Place::Local(_), box Rvalue::Use(_)) => {
- // Writing to a local (e.g. a drop flag) does not
+ // Writing to a local (e.g., a drop flag) does not
// turn a landing pad to a non-nop
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DropFlagState {
- Present, // i.e. initialized
- Absent, // i.e. deinitialized or "moved"
+ Present, // i.e., initialized
+ Absent, // i.e., deinitialized or "moved"
}
impl DropFlagState {
//! ```
//!
//! This means that users of this analysis still have to check whether
-//! pre-existing references can be used to access the value (e.g. at movable
+//! pre-existing references can be used to access the value (e.g., at movable
//! generator yield points, all pre-existing references are invalidated, so this
//! doesn't matter).
}
}
ItemKind::Mod(_) => {
- // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
+ // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
attr::first_attr_value_str_by_name(&item.attrs, "path");
if attr::contains_name(&item.attrs, "warn_directory_ownership") {
let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
}
}
-// Bans nested `impl Trait`, e.g. `impl Into<impl Debug>`.
+// Bans nested `impl Trait`, e.g., `impl Into<impl Debug>`.
// Nested `impl Trait` _is_ allowed in associated type position,
// e.g `impl Iterator<Item=impl Debug>`
struct NestedImplTraitVisitor<'a> {
NotPromotable
};
// Just in case the type is more specific than the definition,
- // e.g. impl associated const with type parameters, check it.
+ // e.g., impl associated const with type parameters, check it.
// Also, trait associated consts are relaxed by this.
promotable | v.type_promotability(node_ty)
}
// Intentionally leak the dynamic library. We can't ever unload it
// since the library can make things that will live arbitrarily long
- // (e.g. an @-box cycle or a thread).
+ // (e.g., an @-box cycle or a thread).
mem::forget(lib);
registrar
extern crate syntax_pos;
extern crate rustc_data_structures;
-use rustc::hir::{self, PatKind};
-use hir::Node;
+use rustc::hir::{self, Node, PatKind};
use rustc::hir::def::Def;
use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::ty::query::Providers;
use rustc::ty::subst::UnpackedKind;
use rustc::util::nodemap::NodeSet;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::sync::Lrc;
use syntax::ast::{self, CRATE_NODE_ID, Ident};
use syntax::symbol::keywords;
use syntax_pos::Span;
use std::cmp;
use std::mem::replace;
-use rustc_data_structures::fx::FxHashSet;
-use rustc_data_structures::sync::Lrc;
mod diagnostics;
struct EmbargoVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
- // Accessibility levels for reachable nodes
+ // Accessibility levels for reachable nodes.
access_levels: AccessLevels,
- // Previous accessibility level, None means unreachable
+ // Previous accessibility level; `None` means unreachable.
prev_level: Option<AccessLevel>,
- // Have something changed in the level map?
+ // Has something changed in the level map?
changed: bool,
}
self.access_levels.map.get(&id).cloned()
}
- // Updates node level and returns the updated level
+ // Updates node level and returns the updated level.
fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
let old_level = self.get(id);
- // Accessibility levels can only grow
+ // Accessibility levels can only grow.
if level > old_level {
self.access_levels.map.insert(id, level.unwrap());
self.changed = true;
fn visit_item(&mut self, item: &'tcx hir::Item) {
let inherited_item_level = match item.node {
- // Impls inherit level from their types and traits
+ // Impls inherit level from their types and traits.
hir::ItemKind::Impl(..) => {
let def_id = self.tcx.hir().local_def_id(item.id);
cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
}
- // Foreign mods inherit level from parents
+ // Foreign modules inherit level from parents.
hir::ItemKind::ForeignMod(..) => {
self.prev_level
}
- // Other `pub` items inherit levels from parents
+ // Other `pub` items inherit levels from parents.
hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
}
};
- // Update level of the item itself
+ // Update level of the item itself.
let item_level = self.update(item.id, inherited_item_level);
- // Update levels of nested things
+ // Update levels of nested things.
match item.node {
hir::ItemKind::Enum(ref def, _) => {
for variant in &def.variants {
// reachability level through interfaces and children.
let orig_level = replace(&mut self.prev_level, item_level);
- // Mark all items in interfaces of reachable items as reachable
+ // Mark all items in interfaces of reachable items as reachable.
match item.node {
- // The interface is empty
+ // The interface is empty.
hir::ItemKind::ExternCrate(..) => {}
- // All nested items are checked by visit_item
+ // All nested items are checked by `visit_item`.
hir::ItemKind::Mod(..) => {}
- // Re-exports are handled in visit_mod
+ // Re-exports are handled in `visit_mod`.
hir::ItemKind::Use(..) => {}
- // The interface is empty
+ // The interface is empty.
hir::ItemKind::GlobalAsm(..) => {}
hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
if item_level.is_some() {
- // Reach the (potentially private) type and the API being exposed
+ // Reach the (potentially private) type and the API being exposed.
self.reach(item.id).ty().predicates();
}
}
- // Visit everything
+ // Visit everything.
hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
hir::ItemKind::Existential(..) |
hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
self.reach(item.id).generics().predicates();
}
}
- // Visit everything except for private impl items
+ // Visit everything except for private impl items.
hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates().impl_trait_ref();
}
}
- // Visit everything, but enum variants have their own levels
+ // Visit everything, but enum variants have their own levels.
hir::ItemKind::Enum(ref def, _) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates();
}
}
}
- // Visit everything, but foreign items have their own levels
+ // Visit everything, but foreign items have their own levels.
hir::ItemKind::ForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
if self.get(foreign_item.id).is_some() {
}
}
}
- // Visit everything except for private fields
+ // Visit everything except for private fields.
hir::ItemKind::Struct(ref struct_def, _) |
hir::ItemKind::Union(ref struct_def, _) => {
if item_level.is_some() {
// Blocks can have public items, for example impls, but they always
// start as completely private regardless of publicity of a function,
- // constant, type, field, etc. in which this block resides
+ // constant, type, field, etc., in which this block resides.
intravisit::walk_block(self, b);
self.prev_level = orig_level;
impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
// Checks that a field in a struct constructor (expression or pattern) is accessible.
fn check_field(&mut self,
- use_ctxt: Span, // Syntax context of the field name at the use site
- span: Span, // Span of the field pattern, e.g. `x: 0`
- def: &'tcx ty::AdtDef, // Definition of the struct or enum
- field: &'tcx ty::FieldDef) { // Definition of the field
+ use_ctxt: Span, // syntax context of the field name at the use site
+ span: Span, // span of the field pattern, e.g., `x: 0`
+ def: &'tcx ty::AdtDef, // definition of the struct or enum
+ field: &'tcx ty::FieldDef) { // definition of the field
let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
}
}
-// Set the correct TypeckTables for the given `item_id` (or an empty table if
-// there is no TypeckTables for the item).
+// Set the correct `TypeckTables` for the given `item_id` (or an empty table if
+// there is no `TypeckTables` for the item).
fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
item_id: ast::NodeId,
tables: &mut &'a ty::TypeckTables<'tcx>,
self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
}
- // Take node ID of an expression or pattern and check its type for privacy.
+ // Take node-id of an expression or pattern and check its type for privacy.
fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
self.span = span;
if self.tables.node_id_to_type(id).visit_with(self) {
intravisit::walk_qpath(self, qpath, id, span);
}
- // Check types of patterns
+ // Check types of patterns.
fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
// Do not check nested patterns if the error already happened.
intravisit::walk_local(self, local);
}
- // Check types in item interfaces
+ // Check types in item interfaces.
fn visit_item(&mut self, item: &'tcx hir::Item) {
let orig_current_item = self.current_item;
let orig_tables = update_tables(self.tcx,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
access_levels: &'a AccessLevels,
in_variant: bool,
- // set of errors produced by this obsolete visitor
+ // Set of errors produced by this obsolete visitor.
old_error_set: NodeSet,
}
struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
- /// whether the type refers to private types.
+ /// Whether the type refers to private types.
contains_private: bool,
- /// whether we've recurred at all (i.e. if we're pointing at the
- /// first type on which visit_ty was called).
+ /// Whether we've recurred at all (i.e., if we're pointing at the
+ /// first type on which `visit_ty` was called).
at_outer_type: bool,
- // whether that first type is a public path.
+ /// Whether that first type is a public path.
outer_type_is_public_path: bool,
}
// it's in this crate...
if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
// .. and it corresponds to a private type in the AST (this returns
- // None for type parameters)
+ // `None` for type parameters).
match self.tcx.hir().find(node_id) {
Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
Some(_) | None => false,
fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
// FIXME: this would preferably be using `exported_items`, but all
- // traits are exported currently (see `EmbargoVisitor.exported_trait`)
+ // traits are exported currently (see `EmbargoVisitor.exported_trait`).
self.access_levels.is_public(trait_id)
}
if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
if self.inner.path_is_private_type(path) {
self.contains_private = true;
- // found what we're looking for so let's stop
- // working.
+ // Found what we're looking for, so let's stop working.
return
}
}
intravisit::walk_ty(self, ty)
}
- // don't want to recurse into [, .. expr]
+ // Don't want to recurse into `[, .. expr]`.
fn visit_expr(&mut self, _: &hir::Expr) {}
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
match item.node {
- // contents of a private mod can be re-exported, so we need
+ // Contents of a private mod can be re-exported, so we need
// to check internals.
hir::ItemKind::Mod(_) => {}
}
}
- // impls need some special handling to try to offer useful
+ // Impls need some special handling to try to offer useful
// error messages without (too many) false positives
- // (i.e. we could just return here to not check them at
+ // (i.e., we could just return here to not check them at
// all, or some worse estimation of whether an impl is
// publicly visible).
hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
// `impl [... for] Private` is never visible.
let self_contains_private;
- // impl [... for] Public<...>, but not `impl [... for]
- // Vec<Public>` or `(Public,)` etc.
+ // `impl [... for] Public<...>`, but not `impl [... for]
+ // Vec<Public>` or `(Public,)`, etc.
let self_is_public_path;
- // check the properties of the Self type:
+ // Check the properties of the `Self` type:
{
let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
inner: self,
self_is_public_path = visitor.outer_type_is_public_path;
}
- // miscellaneous info about the impl
+ // Miscellaneous info about the impl:
// `true` iff this is `impl Private for ...`.
let not_private_trait =
}
}
} else if trait_ref.is_none() && self_is_public_path {
- // impl Public<Private> { ... }. Any public static
+ // `impl Public<Private> { ... }`. Any public static
// methods will be visible as `Public::foo`.
let mut found_pub_static = false;
for impl_item_ref in impl_item_refs {
// we're introducing a new name.
hir::ItemKind::Ty(..) => return,
- // not at all public, so we don't care
+ // Not at all public, so we don't care.
_ if !self.item_is_public(&item.id, &item.vis) => {
return;
}
// We've carefully constructed it so that if we're here, then
// any `visit_ty`'s will be called on things that are in
- // public signatures, i.e. things that we're interested in for
+ // public signatures, i.e., things that we're interested in for
// this visitor.
intravisit::walk_item(self, item);
}
}
}
- // we don't need to introspect into these at all: an
+ // We don't need to introspect into these at all: an
// expression/block context can't possibly contain exported things.
// (Making them no-ops stops us from traversing the whole AST without
// having to be super careful about our `walk_...` calls above.)
tcx: TyCtxt<'a, 'tcx, 'tcx>,
item_def_id: DefId,
span: Span,
- /// The visitor checks that each component type is at least this visible
+ /// The visitor checks that each component type is at least this visible.
required_visibility: ty::Visibility,
- /// The visibility of the least visible component that has been visited
+ /// The visibility of the least visible component that has been visited.
min_visibility: ty::Visibility,
has_pub_restricted: bool,
has_old_errors: bool,
}
fn predicates(&mut self) -> &mut Self {
- // NB: We use `explicit_predicates_of` and not `predicates_of`
+ // N.B., we use `explicit_predicates_of` and not `predicates_of`
// because we don't want to report privacy errors due to where
// clauses that the compiler inferred. We only want to
// consider the ones that the user wrote. This is important
}
fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
- // Non-local means public (private items can't leave their crate, modulo bugs)
+ // Non-local means public (private items can't leave their crate, modulo bugs).
if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) {
let item = self.tcx.hir().expect_item(node_id);
let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
};
if let Some(def_id) = ty_def_id {
- // Non-local means public (private items can't leave their crate, modulo bugs)
+ // Non-local means public (private items can't leave their crate, modulo bugs).
if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
let hir_vis = match self.tcx.hir().find(node_id) {
Some(Node::Item(item)) => &item.vis,
let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
match item.node {
- // Crates are always public
+ // Crates are always public.
hir::ItemKind::ExternCrate(..) => {}
- // All nested items are checked by visit_item
+ // All nested items are checked by `visit_item`.
hir::ItemKind::Mod(..) => {}
- // Checked in resolve
+ // Checked in resolve.
hir::ItemKind::Use(..) => {}
- // No subitems
+ // No subitems.
hir::ItemKind::GlobalAsm(..) => {}
hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
// Check the traits being exposed, as they're separate,
- // e.g. `impl Iterator<Item=T>` has two predicates,
+ // e.g., `impl Iterator<Item=T>` has two predicates,
// `X: Iterator` and `<X as Iterator>::Item == T`,
// where `X` is the `impl Iterator<Item=T>` itself,
// stored in `predicates_of`, not in the `Ty` itself.
-
self.check(item.id, item_visibility).predicates();
}
- // Subitems of these items have inherited publicity
+ // Subitems of these items have inherited publicity.
hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Fn(..) |
hir::ItemKind::Existential(..) |
hir::ItemKind::Ty(..) => {
self.check(item.id, item_visibility).generics().predicates().ty();
- // Recurse for e.g. `impl Trait` (see `visit_ty`).
+ // Recurse for e.g., `impl Trait` (see `visit_ty`).
self.inner_visibility = item_visibility;
intravisit::walk_item(self, item);
}
}
}
}
- // Subitems of foreign modules have their own publicity
+ // Subitems of foreign modules have their own publicity.
hir::ItemKind::ForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
self.check(foreign_item.id, vis).generics().predicates().ty();
}
}
- // Subitems of structs and unions have their own publicity
+ // Subitems of structs and unions have their own publicity.
hir::ItemKind::Struct(ref struct_def, _) |
hir::ItemKind::Union(ref struct_def, _) => {
self.check(item.id, item_visibility).generics().predicates();
}
}
// An inherent impl is public when its type is public
- // Subitems of inherent impls have their own publicity
+ // Subitems of inherent impls have their own publicity.
hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
let ty_vis =
self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
check.generics().predicates().ty();
- // Recurse for e.g. `impl Trait` (see `visit_ty`).
+ // Recurse for e.g., `impl Trait` (see `visit_ty`).
self.inner_visibility = impl_item_vis;
intravisit::walk_impl_item(self, impl_item);
}
}
// A trait impl is public when both its type and its trait are public
- // Subitems of trait impls have inherited publicity
+ // Subitems of trait impls have inherited publicity.
hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
let vis = self.check(item.id, ty::Visibility::Invisible)
.ty().impl_trait_ref().min_visibility;
check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
check.generics().predicates().ty();
- // Recurse for e.g. `impl Trait` (see `visit_ty`).
+ // Recurse for e.g., `impl Trait` (see `visit_ty`).
self.inner_visibility = vis;
intravisit::walk_impl_item(self, impl_item);
}
}
fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
- // handled in `visit_item` above
+ // Handled in `visit_item` above.
}
- // Don't recurse into expressions in array sizes or const initializers
+ // Don't recurse into expressions in array sizes or const initializers.
fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
- // Don't recurse into patterns in function arguments
+ // Don't recurse into patterns in function arguments.
fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
}
pub_restricted_visitor.has_pub_restricted
};
- // Check for private types and traits in public interfaces
+ // Check for private types and traits in public interfaces.
let mut visitor = PrivateItemsInPublicInterfacesVisitor {
tcx,
has_pub_restricted,
use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
use macros::{InvocationData, LegacyBinding, ParentScope};
-// NB: This module needs to be declared first so diagnostics are
+// N.B., this module needs to be declared first so diagnostics are
// registered before they are used.
mod diagnostics;
mod error_reporting;
// A minimal representation of a path segment. We use this in resolve because
// we synthesize 'path segments' which don't have the rest of an AST or HIR
-// PathSegment.
+// `PathSegment`.
#[derive(Clone, Copy, Debug)]
pub struct Segment {
ident: Ident,
result
}
- /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`)
+ /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`)
fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
where F: FnOnce(&mut Resolver, Option<DefId>) -> T
{
self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
}
- // This has to happen *after* we determine which pat_idents are variants
+ // This has to happen *after* we determine which pat_idents are variants.
self.check_consistent_bindings(&arm.pats);
if let Some(ast::Guard::If(ref expr)) = arm.guard {
Def::StructCtor(..) | Def::VariantCtor(..) |
Def::Const(..) | Def::Static(..) => {
// This is unambiguously a fresh binding, either syntactically
- // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
- // to something unusable as a pattern (e.g. constructor function),
+ // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
+ // to something unusable as a pattern (e.g., constructor function),
// but we still conservatively report an error, see
// issues/33118#issuecomment-233962221 for one reason why.
resolve_error(
for (sp, variant_path, enum_path) in enum_candidates {
if sp.is_dummy() {
let msg = format!("there is an enum variant `{}`, \
- try using `{}`?",
- variant_path,
- enum_path);
+ try using `{}`?",
+ variant_path,
+ enum_path);
err.help(&msg);
} else {
err.span_suggestion_with_applicability(
let mut levenshtein_worked = false;
- // Try Levenshtein.
+ // Try Levenshtein algorithm.
if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
err.span_label(ident_span, format!("did you mean `{}`?", candidate));
levenshtein_worked = true;
for pat in pats {
this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
}
- // This has to happen *after* we determine which pat_idents are variants
+ // This has to happen *after* we determine which pat_idents are variants.
this.check_consistent_bindings(pats);
this.visit_block(block);
this.ribs[ValueNS].pop();
/// When name resolution fails, this method can be used to look up candidate
/// entities with the expected name. It allows filtering them using the
/// supplied predicate (which should be used to only accept the types of
- /// definitions expected e.g. traits). The lookup spans across all crates.
+ /// definitions expected e.g., traits). The lookup spans across all crates.
///
/// NOTE: The method does not look into imports, but this is not a problem,
/// since we report the definitions (thus, the de-aliased imports).
}
} else {
// Not only attributes, but anything in macro namespace can result in
- // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
+ // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report
// an error for those cases.
let msg = format!("expected a macro, found {}", def.kind_name());
self.session.span_err(path.span, &msg);
// Resolve an identifier in lexical scope.
// This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
// expansion and import resolution (perhaps they can be merged in the future).
- // The function is used for resolving initial segments of macro paths (e.g. `foo` in
+ // The function is used for resolving initial segments of macro paths (e.g., `foo` in
// `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
crate fn early_resolve_ident_in_lexical_scope(
&mut self,
crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
-> &'a NameBinding<'a> {
let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
- // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
+ // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
!directive.is_glob() && binding.is_extern_crate() {
directive.vis.get()
} else {
NameBindingKind::Import { binding, .. } => {
match binding.kind {
// Never suggest the name that has binding error
- // i.e. the name that cannot be previously resolved
+ // i.e., the name that cannot be previously resolved
NameBindingKind::Def(Def::Err, _) => return None,
_ => Some(&i.name),
}
}
}
- // Returns path to the compilation output (e.g. libfoo-12345678.rmeta)
+ // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
let sess = &self.tcx.sess;
// Save-analysis is emitted per whole session, not per each crate type
}
/// An argument passed entirely registers with the
-/// same kind (e.g. HFA / HVA on PPC64 and AArch64).
+/// same kind (e.g., HFA / HVA on PPC64 and AArch64).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Uniform {
pub unit: Reg,
/// * equal to `unit.size` (one scalar/vector)
/// * a multiple of `unit.size` (an array of scalar/vectors)
/// * if `unit.kind` is `Integer`, the last element
- /// can be shorter, i.e. `{ i64, i64, i32 }` for
+ /// can be shorter, i.e., `{ i64, i64, i32 }` for
/// 64-bit integers with a total size of 20 bytes
pub total: Size,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// FIXME: The assumes we're using the non-vector ABI, i.e. compiling
+// FIXME: The assumes we're using the non-vector ABI, i.e., compiling
// for a pre-z13 machine or using -mno-vx.
use abi::call::{FnType, ArgType, Reg};
use abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods};
/// Classification of "eightbyte" components.
-// NB: the order of the variants is from general to specific,
+// N.B., the order of the variants is from general to specific,
// such that `unify(a, b)` is the "smaller" of `a` and `b`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum Class {
/// Compute the best alignment possible for the given offset
/// (the largest power of two that the offset is a multiple of).
///
- /// NB: for an offset of `0`, this happens to return `2^64`.
+ /// N.B., for an offset of `0`, this happens to return `2^64`.
pub fn max_for_offset(offset: Size) -> Align {
Align {
pow2: offset.bytes().trailing_zeros() as u8,
///
/// This is intended specifically to mirror LLVM’s `!range` metadata,
/// semantics.
- // FIXME(eddyb) always use the shortest range, e.g. by finding
+ // FIXME(eddyb) always use the shortest range, e.g., by finding
// the largest space between two consecutive valid values and
// taking everything else as the (shortest) valid range.
pub valid_range: RangeInclusive<u128>,
}
/// The details of the layout of a type, alongside the type itself.
-/// Provides various type traversal APIs (e.g. recursing into fields).
+/// Provides various type traversal APIs (e.g., recursing into fields).
///
/// Note that the details are NOT guaranteed to always be identical
/// to those obtained from `layout_of(ty)`, as we need to produce
/// layouts for which Rust types do not exist, such as enum variants
-/// or synthetic fields of enums (i.e. discriminants) and fat pointers.
+/// or synthetic fields of enums (i.e., discriminants) and fat pointers.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct TyLayout<'a, Ty> {
pub ty: Ty,
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Debug)]
pub enum Abi {
- // NB: This ordering MUST match the AbiDatas array below.
+ // N.B., this ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
// Single platform ABIs
/// `eh_unwind_resume` lang item.
pub custom_unwind_resume: bool,
- /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
+ /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
/// this target.
pub has_elf_tls: bool,
// This is mainly for easy compatibility with emscripten.
// - Cortex-M23
// - Cortex-M33
//
-// We have opted for these instead of one target per processor (e.g. `cortex-m0`, `cortex-m3`,
+// We have opted for these instead of one target per processor (e.g., `cortex-m0`, `cortex-m3`,
// etc) because the differences between some processors like the cortex-m0 and cortex-m1 are almost
// non-existent from the POV of codegen so it doesn't make sense to have separate targets for them.
// And if differences exist between two processors under the same target, rustc flags can be used to
let obligations =
wf::obligations(infcx, param_env, DUMMY_NODE_ID, ty, DUMMY_SP).unwrap_or(vec![]);
- // NB: All of these predicates *ought* to be easily proven
+ // N.B., all of these predicates *ought* to be easily proven
// true. In fact, their correctness is (mostly) implied by
// other parts of the program. However, in #42552, we had
// an annoying scenario where:
}
crate trait Lower<T> {
- /// Lower a rustc construct (e.g. `ty::TraitPredicate`) to a chalk-like type.
+ /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk-like type.
fn lower(&self) -> T;
}
}
/// `ty::Binder` is used for wrapping a rustc construction possibly containing generic
-/// lifetimes, e.g. `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things
-/// in that leaf-form (i.e. `Holds(Implemented(Binder<TraitPredicate>))` in the previous
-/// example), we model them with quantified domain goals, e.g. as for the previous example:
+/// lifetimes, e.g., `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things
+/// in that leaf-form (i.e., `Holds(Implemented(Binder<TraitPredicate>))` in the previous
+/// example), we model them with quantified domain goals, e.g., as for the previous example:
/// `forall<'a> { T: Fn(&'a i32) }` which corresponds to something like
/// `Binder<Holds(Implemented(TraitPredicate))>`.
impl<'tcx, T> Lower<PolyDomainGoal<'tcx>> for ty::Binder<T>
// and that named bound regions have a def-id, it is safe
// to just inject `hypotheses` (which contains named vars bound at index `0`)
// into this binding level. This may change if we ever allow where clauses
- // to bind types (e.g. for GATs things), because bound types only use a `BoundVar`
+ // to bind types (e.g., for GATs things), because bound types only use a `BoundVar`
// index (no def-id).
hypotheses,
// ```
//
// FIXME: For the moment, we don't account for where clauses written on the associated
- // ty definition (i.e. in the trait def, as in `type AssocType<T> where T: Sized`).
+ // ty definition (i.e., in the trait def, as in `type AssocType<T> where T: Sized`).
// ```
// forall<P0..Pm> {
// forall<Pn+1..Pm> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Conversion from AST representation of types to the `ty.rs`
-//! representation. The main routine here is `ast_ty_to_ty()`: each use
-//! is parameterized by an instance of `AstConv`.
+//! Conversion from AST representation of types to the `ty.rs` representation.
+//! The main routine here is `ast_ty_to_ty()`; each use is is parameterized by
+//! an instance of `AstConv`.
-use smallvec::SmallVec;
+use errors::{Applicability, FatalError, DiagnosticId};
use hir::{self, GenericArg, GenericArgs};
use hir::def::Def;
use hir::def_id::DefId;
use hir::HirVec;
+use lint;
use middle::resolve_lifetime as rl;
use namespace::Namespace;
-use rustc::ty::subst::{Kind, Subst, Substs};
-use rustc::traits;
+use rustc::traits::{self, TraitRefExpansionInfoDignosticBuilder};
use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
use rustc::ty::{GenericParamDef, GenericParamDefKind};
+use rustc::ty::subst::{Kind, Subst, Substs};
use rustc::ty::wf::object_region_bounds;
use rustc_data_structures::sync::Lrc;
use rustc_target::spec::abi;
-use std::collections::BTreeSet;
-use std::slice;
use require_c_abi_if_variadic;
-use util::common::ErrorReported;
-use util::nodemap::FxHashMap;
-use errors::{Applicability, FatalError, DiagnosticId};
-use lint;
-
-use std::iter;
+use smallvec::SmallVec;
use syntax::ast;
use syntax::feature_gate::{GateIssue, emit_feature_err};
use syntax::ptr::P;
use syntax::util::lev_distance::find_best_match_for_name;
use syntax_pos::{DUMMY_SP, Span, MultiSpan};
+use util::common::ErrorReported;
+use util::nodemap::FxHashMap;
+
+use std::collections::BTreeSet;
+use std::iter;
+use std::ops::Range;
+use std::slice;
pub trait AstConv<'gcx, 'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
/// Invoked when we encounter an error from some prior pass
- /// (e.g. resolve) that is translated into a ty-error. This is
+ /// (e.g., resolve) that is translated into a ty-error. This is
/// used to help suppress derived errors typeck might otherwise
/// report.
fn set_tainted_by_errors(&self);
#[derive(PartialEq)]
enum GenericArgPosition {
Type,
- Value, // e.g. functions
+ Value, // e.g., functions
MethodCall,
}
/// This type must not appear anywhere in other converted types.
const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
-impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o {
+impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
pub fn ast_region_to_region(&self,
lifetime: &hir::Lifetime,
def: Option<&ty::GenericParamDef>)
provided,
offset| {
// We enforce the following: `required` <= `provided` <= `permitted`.
- // For kinds without defaults (i.e. lifetimes), `required == permitted`.
- // For other kinds (i.e. types), `permitted` may be greater than `required`.
+ // For kinds without defaults (i.e., lifetimes), `required == permitted`.
+ // For other kinds (i.e., types), `permitted` may be greater than `required`.
if required <= provided && provided <= permitted {
return (false, None);
}
/// creating the substitutions for, and a partial set of
/// substitutions `parent_substs`. In general, the substitutions
/// for an item begin with substitutions for all the "parents" of
- /// that item -- so e.g. for a method it might include the
+ /// that item -- e.g., for a method it might include the
/// parameters from the impl.
///
/// Therefore, the method begins by walking down these parents,
/// starting with the outermost parent and proceed inwards until
- /// it reaches `def_id`. For each parent P, it will check `parent_substs`
+ /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
/// first to see if the parent's substitutions are listed in there. If so,
/// we can append those and move on. Otherwise, it invokes the
/// three callback functions:
///
- /// - `args_for_def_id`: given the def-id P, supplies back the
+ /// - `args_for_def_id`: given the def-id `P`, supplies back the
/// generic arguments that were given to that parent from within
- /// the path; so e.g. if you have `<T as Foo>::Bar`, the def-id
+ /// the path; so e.g., if you have `<T as Foo>::Bar`, the def-id
/// might refer to the trait `Foo`, and the arguments might be
/// `[T]`. The boolean value indicates whether to infer values
/// for arguments whose values were not explicitly provided.
/// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
- /// instantiate a `Kind`
+ /// instantiate a `Kind`.
/// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
/// creates a suitable inference variable.
pub fn create_substs_for_generic_args<'a, 'b>(
provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
) -> &'tcx Substs<'tcx> {
- // Collect the segments of the path: we need to substitute arguments
+ // Collect the segments of the path; we need to substitute arguments
// for parameters throughout the entire path (wherever there are
// generic parameters).
let mut parent_defs = tcx.generics_of(def_id);
}
// We manually build up the substitution, rather than using convenience
- // methods in `subst.rs` so that we can iterate over the arguments and
- // parameters in lock-step linearly, rather than trying to match each pair.
+ // methods in `subst.rs`, so that we can iterate over the arguments and
+ // parameters in lock-step linearly, instead of trying to match each pair.
let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
// Iterate over each segment of the path.
}
}
if !suggestions.is_empty() {
- let msg = if suggestions.len() == 1 {
- "if you meant to specify the associated type, write"
- } else {
- "if you meant to specify the associated types, write"
- };
+ let msg = format!("if you meant to specify the associated {}, write",
+ if suggestions.len() == 1 { "type" } else { "types" });
err.multipart_suggestion_with_applicability(
- msg,
+ &msg,
suggestions,
Applicability::MaybeIncorrect,
);
}
}
-/// Divides a list of general trait bounds into two groups: auto traits (e.g. Sync and Send) and the
-/// remaining general trait bounds.
+/// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
+/// the remaining general trait bounds.
fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
trait_bounds: &'b [hir::PolyTraitRef])
-> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
-> Vec<(ty::Predicate<'tcx>, Span)>
{
- // If it could be sized, and is, add the sized predicate
+ // If it could be sized, and is, add the sized predicate.
let sized_predicate = self.implicitly_sized.and_then(|span| {
tcx.lang_items().sized_trait().map(|sized| {
let trait_ref = ty::TraitRef {
sized_predicate.into_iter().chain(
self.region_bounds.iter().map(|&(region_bound, span)| {
- // account for the binder being introduced below; no need to shift `param_ty`
- // because, at present at least, it can only refer to early-bound regions
+ // Account for the binder being introduced below; no need to shift `param_ty`
+ // because, at present at least, it can only refer to early-bound regions.
let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
let outlives = ty::OutlivesPredicate(param_ty, region_bound);
(ty::Binder::dummy(outlives).to_predicate(), span)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use check::{FnCtxt, Expectation, Diverges, Needs};
+use check::coercion::CoerceMany;
use rustc::hir::{self, PatKind};
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::pat_util::EnumerateAndAdjustIterator;
use rustc::infer::type_variable::TypeVariableOrigin;
use rustc::traits::ObligationCauseCode;
use rustc::ty::{self, Ty, TypeFoldable};
-use check::{FnCtxt, Expectation, Diverges, Needs};
-use check::coercion::CoerceMany;
-use util::nodemap::FxHashMap;
-
-use std::collections::hash_map::Entry::{Occupied, Vacant};
-use std::cmp;
use syntax::ast;
use syntax::source_map::Spanned;
use syntax::ptr::P;
use syntax::util::lev_distance::find_best_match_for_name;
use syntax_pos::Span;
+use util::nodemap::FxHashMap;
+
+use std::collections::hash_map::Entry::{Occupied, Vacant};
+use std::cmp;
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
/// The `is_arg` argument indicates whether this pattern is the
// the "discriminant type" (issue #23116).
//
// arielb1 [writes here in this comment thread][c] that there
- // is certainly *some* potential danger, e.g. for an example
+ // is certainly *some* potential danger, e.g., for an example
// like:
//
// [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
return self.tcx.types.err;
};
- // Type check the path.
+ // Type-check the path.
self.demand_eqtype(pat.span, expected, pat_ty);
- // Type check subpatterns.
+ // Type-check subpatterns.
if self.check_struct_pat_fields(pat_ty, pat.id, pat.span, variant, fields, etc, def_bm) {
pat_ty
} else {
_ => bug!("unexpected pattern definition: {:?}", def)
}
- // Type check the path.
+ // Type-check the path.
let pat_ty = self.instantiate_value_path(segments, opt_ty, def, pat.span, pat.id).0;
self.demand_suptype(pat.span, expected, pat_ty);
pat_ty
return self.tcx.types.err;
}
- // Type check the path.
+ // Type-check the path.
let (pat_ty, def) = self.instantiate_value_path(segments, opt_ty, def, pat.span, pat.id);
if !pat_ty.is_fn() {
report_unexpected_def(def);
self.demand_eqtype(pat.span, expected, pat_ty);
- // Type check subpatterns.
+ // Type-check subpatterns.
if subpats.len() == variant.fields.len() ||
subpats.len() < variant.fields.len() && ddpos.is_some() {
let substs = match pat_ty.sty {
}
/// also dereference through raw pointer types
- /// e.g. assuming ptr_to_Foo is the type `*const Foo`
+ /// e.g., assuming ptr_to_Foo is the type `*const Foo`
/// fcx.autoderef(span, ptr_to_Foo) => [*const Foo]
/// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo]
pub fn include_raw_pointers(mut self) -> Self {
enum CallStep<'tcx> {
Builtin(Ty<'tcx>),
DeferredClosure(ty::FnSig<'tcx>),
- /// e.g. enum variant constructors
+ /// e.g., enum variant constructors
Overloaded(MethodCallee<'tcx>),
}
//!
//! where `&.T` and `*T` are references of either mutability,
//! and where pointer_kind(`T`) is the kind of the unsize info
-//! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or
+//! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or
//! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
//!
//! Note that lengths are not adjusted when casting raw slices -
ty::Predicate::ObjectSafe(..) => None,
ty::Predicate::ConstEvaluatable(..) => None,
- // NB: This predicate is created by breaking down a
+ // N.B., this predicate is created by breaking down a
// `ClosureType: FnFoo()` predicate, where
// `ClosureType` represents some `Closure`. It can't
// possibly be referring to the current closure,
// the decision to region inference (and regionck, which will add
// some more edges to this variable). However, this can wind up
// creating a crippling number of variables in some cases --
- // e.g. #32278 -- so we optimize one particular case [3].
+ // e.g., #32278 -- so we optimize one particular case [3].
// Let me try to explain with some examples:
// - The "running example" above represents the simple case,
// where we have one `&` reference at the outer level and
// Special-case that coercion alone cannot handle:
// Two function item types of differing IDs or Substs.
if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) {
- // Don't reify if the function types have a LUB, i.e. they
+ // Don't reify if the function types have a LUB, i.e., they
// are the same function and their parameters have a LUB.
let lub_ty = self.commit_if_ok(|_| {
self.at(cause, self.param_env)
// Checks that the type of `expr` can be coerced to `expected`.
//
- // NB: This code relies on `self.diverges` to be accurate. In
+ // N.B., this code relies on `self.diverges` to be accurate. In
// particular, assignments to `!` will be permitted if the
// diverges flag is currently "always".
pub fn demand_coerce_diag(&self,
/// coherence),
///
/// 2. The generic region/type parameters of the impl's self-type must
-/// all be parameters of the Drop impl itself (i.e. no
+/// all be parameters of the Drop impl itself (i.e., no
/// specialization like `impl Drop for Foo<i32>`), and,
///
/// 3. Any bounds on the generic parameters must be reflected in the
//
// self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
//
- // Applying this to the predicates (i.e. assumptions) provided by the item
+ // Applying this to the predicates (i.e., assumptions) provided by the item
// definition yields the instantiated assumptions:
//
// ['y : 'z]
}
// walk the expected type and the actual type in lock step, checking they're
-// the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
+// the same, in a kinda-structural way, i.e., `Vector`s have to be simd structs with
// exactly the right element type
fn match_intrinsic_type_to_type<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
// Instantiate late-bound regions and substitute the trait
// parameters into the method type to get the actual method type.
//
- // NB: Instantiate late-bound regions first so that
+ // N.B., instantiate late-bound regions first so that
// `instantiate_type_scheme` can normalize associated types that
// may reference those regions.
let method_sig = self.replace_bound_vars_with_fresh_vars(&sig);
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/method-lookup.html
+mod confirm;
+pub mod probe;
+mod suggest;
+
+pub use self::MethodError::*;
+pub use self::CandidateSource::*;
+pub use self::suggest::TraitInfo;
+
use check::FnCtxt;
-use hir::def::Def;
-use hir::def_id::DefId;
use namespace::Namespace;
-use rustc::ty::subst::Substs;
+use rustc_data_structures::sync::Lrc;
+use rustc::hir;
+use rustc::hir::def::Def;
+use rustc::hir::def_id::DefId;
use rustc::traits;
+use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable};
use rustc::ty::GenericParamDefKind;
use rustc::ty::subst::Subst;
use rustc::infer::{self, InferOk};
-
use syntax::ast;
use syntax_pos::Span;
-use rustc::hir;
-
-use rustc_data_structures::sync::Lrc;
-
-pub use self::MethodError::*;
-pub use self::CandidateSource::*;
-pub use self::suggest::TraitInfo;
-
-mod confirm;
-pub mod probe;
-mod suggest;
-
use self::probe::{IsSuggestion, ProbeScope};
pub fn provide(providers: &mut ty::query::Providers) {
pub def_id: DefId,
pub substs: &'tcx Substs<'tcx>,
- /// Instantiated method signature, i.e. it has been
+ /// Instantiated method signature, i.e., it has been
/// substituted, normalized, and has had late-bound
/// lifetimes replaced with inference variables.
pub sig: ty::FnSig<'tcx>,
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum CandidateSource {
ImplSource(DefId),
- TraitSource(// trait id
- DefId),
+ TraitSource(DefId /* trait id */),
}
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
let import_def_id = self.tcx.hir().local_def_id(import_id);
debug!("used_trait_import: {:?}", import_def_id);
Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
- .unwrap().insert(import_def_id);
+ .unwrap().insert(import_def_id);
}
self.tcx.check_stability(pick.item.def_id, Some(call_expr.id), span);
/// an obligation for a particular trait with the given self-type and checks
/// whether that trait is implemented.
///
- /// FIXME(#18741) -- It seems likely that we can consolidate some of this
+ /// FIXME(#18741): it seems likely that we can consolidate some of this
/// code with the other method-lookup code. In particular, the second half
/// of this method is basically the same as confirmation.
pub fn lookup_method_in_trait(&self,
// Instantiate late-bound regions and substitute the trait
// parameters into the method type to get the actual method type.
//
- // NB: Instantiate late-bound regions first so that
+ // N.B., instantiate late-bound regions first so that
// `instantiate_type_scheme` can normalize associated types that
// may reference those regions.
let fn_sig = tcx.fn_sig(def_id);
}
};
- // Register obligations for the parameters. This will include the
+ // Register obligations for the parameters. This will include the
// `Self` parameter, which in turn has a bound of the main trait,
// so this also effectively registers `obligation` as well. (We
// used to register `obligation` explicitly, but that resulted in
pub use self::PickKind::*;
/// Boolean flag used to indicate if this search is for a suggestion
-/// or not. If true, we can allow ambiguity and so forth.
+/// or not. If true, we can allow ambiguity and so forth.
#[derive(Clone, Copy)]
pub struct IsSuggestion(pub bool);
//! found or is otherwise invalid.
use check::FnCtxt;
-use rustc::hir::map as hir_map;
-use hir::Node;
-use rustc_data_structures::sync::Lrc;
-use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
-use rustc::ty::item_path::with_crate_prefix;
-use hir::def::Def;
-use hir::def_id::{CRATE_DEF_INDEX, DefId};
+use errors::{Applicability, DiagnosticBuilder};
use middle::lang_items::FnOnceTraitLangItem;
use namespace::Namespace;
+use rustc_data_structures::sync::Lrc;
+use rustc::hir::{self, Node};
+use rustc::hir::def::Def;
+use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
+use rustc::hir::map as hir_map;
+use rustc::hir::print;
+use rustc::infer::type_variable::TypeVariableOrigin;
use rustc::traits::Obligation;
+use rustc::ty::{self, Adt, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
+use rustc::ty::item_path::with_crate_prefix;
use util::nodemap::FxHashSet;
-
+use syntax_pos::{Span, FileName};
use syntax::ast;
use syntax::util::lev_distance::find_best_match_for_name;
-use errors::{Applicability, DiagnosticBuilder};
-use syntax_pos::{Span, FileName};
-
-
-use rustc::hir::def_id::LOCAL_CRATE;
-use rustc::hir;
-use rustc::hir::print;
-use rustc::infer::type_variable::TypeVariableOrigin;
-use rustc::ty::Adt;
use std::cmp::Ordering;
fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
let tcx = self.tcx;
match ty.sty {
- // Not all of these (e.g. unsafe fns) implement FnOnce
- // so we look for these beforehand
+ // Not all of these (e.g., unsafe fns) implement `FnOnce`,
+ // so we look for these beforehand.
ty::Closure(..) |
ty::FnDef(..) |
ty::FnPtr(_) => true,
- // If it's not a simple function, look for things which implement FnOnce
+ // If it's not a simple function, look for things which implement `FnOnce`.
_ => {
let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) {
Ok(fn_once) => fn_once,
rcvr_expr: Option<&hir::Expr>,
error: MethodError<'tcx>,
args: Option<&'gcx [hir::Expr]>) {
- // avoid suggestions when we don't know what's going on.
+ // Avoid suggestions when we don't know what's going on.
if rcvr_ty.references_error() {
return;
}
let tcx = self.tcx;
let actual = self.resolve_type_vars_if_possible(&rcvr_ty);
- let ty_string = self.ty_to_string(actual);
+ let ty_str = self.ty_to_string(actual);
let is_method = mode == Mode::MethodCall;
let mut suggestion = None;
let item_kind = if is_method {
"can't call {} `{}` on ambiguous numeric type `{}`",
item_kind,
item_name,
- ty_string
+ ty_str
);
let concrete_type = if actual.is_integral() {
"i32"
"f32"
};
match expr.node {
- hir::ExprKind::Lit(ref lit) => { // numeric literal
+ hir::ExprKind::Lit(ref lit) => {
+ // numeric literal
let snippet = tcx.sess.source_map().span_to_snippet(lit.span)
.unwrap_or_else(|_| "<numeric literal>".to_owned());
Applicability::MaybeIncorrect,
);
}
- hir::ExprKind::Path(ref qpath) => { // local binding
+ hir::ExprKind::Path(ref qpath) => {
+ // local binding
if let &hir::QPath::Resolved(_, ref path) = &qpath {
if let hir::def::Def::Local(node_id) = path.def {
let span = tcx.hir().span(node_id);
}
// If the method name is the name of a field with a function or closure type,
- // give a helping note that it has to be called as (x.f)(...).
+ // give a helping note that it has to be called as `(x.f)(...)`.
if let Some(expr) = rcvr_expr {
for (ty, _) in self.autoderef(span, rcvr_ty) {
if let ty::Adt(def, substs) = ty.sty {
let expr_string = match snippet {
Ok(expr_string) => expr_string,
_ => "s".into(), // Default to a generic placeholder for the
- // expression when we can't generate a
- // string snippet
+ // expression when we can't generate a
+ // string snippet.
};
let field_ty = field.ty(tcx, substs);
}
}
} else {
- err.span_label(span, format!("{} not found in `{}`", item_kind, ty_string));
+ err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str));
}
if self.is_fn_ty(&rcvr_ty, span) {
report_candidates(&mut err, static_sources);
} else if static_sources.len() > 1 {
-
report_candidates(&mut err, static_sources);
}
let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
if let Some(span) = span {
let path_strings = candidates.iter().map(|did| {
- // produce an additional newline to separate the new use statement
+ // Produce an additional newline to separate the new use statement
// from the directly following item.
let additional_newline = if found_use {
""
let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
- // there's no implemented traits, so lets suggest some traits to
+ // There are no traits implemented, so lets suggest some traits to
// implement, by finding ones that have the item name, and are
// legal to implement.
let mut candidates = all_traits(self.tcx)
.into_iter()
.filter(|info| {
- // we approximate the coherence rules to only suggest
+ // We approximate the coherence rules to only suggest
// traits that are legal to implement by requiring that
- // either the type or trait is local. Multidispatch means
+ // either the type or trait is local. Multi-dispatch means
// this isn't perfect (that is, there are cases when
// implementing a trait would be legal but is rejected
// here).
.collect::<Vec<_>>();
if !candidates.is_empty() {
- // sort from most relevant to least relevant
+ // Sort from most relevant to least relevant.
candidates.sort_by(|a, b| a.cmp(b).reverse());
candidates.dedup();
- // FIXME #21673 this help message could be tuned to the case
+ // FIXME #21673: this help message could be tuned to the case
// of a type parameter: suggest adding a trait bound rather
// than implementing.
err.help("items from traits can only be used if the trait is implemented and in scope");
fn type_derefs_to_local(&self,
span: Span,
rcvr_ty: Ty<'tcx>,
- rcvr_expr: Option<&hir::Expr>)
- -> bool {
+ source: SelfSource) -> bool {
fn is_local(ty: Ty) -> bool {
match ty.sty {
ty::Adt(def, _) => def.did.is_local(),
ty::Param(_) => true,
- // everything else (primitive types etc.) is effectively
- // non-local (there are "edge" cases, e.g. (LocalType,), but
+ // Everything else (primitive types, etc.) is effectively
+ // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
// the noise from these sort of types is usually just really
// annoying, rather than any sort of help).
_ => false,
}
impl Ord for TraitInfo {
fn cmp(&self, other: &TraitInfo) -> Ordering {
- // local crates are more important than remote ones (local:
- // cnum == 0), and otherwise we throw in the defid for totality
+ // Local crates are more important than remote ones (local:
+ // `cnum == 0`), and otherwise we throw in the defid for totality.
let lhs = (other.def_id.krate, other.def_id);
let rhs = (self.def_id.krate, self.def_id);
/// Compute all traits in this crate and any dependent crates.
fn compute_all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<DefId> {
- use rustc::hir::itemlikevisit;
+ use hir::itemlikevisit;
- let mut traits = vec![];
+ let mut traits = vec![];
- // Crate-local:
- //
- // meh.
- struct Visitor<'a, 'tcx: 'a> {
- map: &'a hir_map::Map<'tcx>,
- traits: &'a mut Vec<DefId>,
- }
- impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
- fn visit_item(&mut self, i: &'v hir::Item) {
- if let hir::ItemKind::Trait(..) = i.node {
- let def_id = self.map.local_def_id(i.id);
- self.traits.push(def_id);
- }
- }
+ // Crate-local:
- fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
- }
+ struct Visitor<'a, 'tcx: 'a> {
+ map: &'a hir_map::Map<'tcx>,
+ traits: &'a mut Vec<DefId>,
+ }
- fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
+ impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
+ fn visit_item(&mut self, i: &'v hir::Item) {
+ if let hir::ItemKind::Trait(..) = i.node {
+ let def_id = self.map.local_def_id(i.id);
+ self.traits.push(def_id);
}
}
- tcx.hir().krate().visit_all_item_likes(&mut Visitor {
- map: &tcx.hir(),
- traits: &mut traits,
- });
-
- // Cross-crate:
- let mut external_mods = FxHashSet::default();
- fn handle_external_def(tcx: TyCtxt,
- traits: &mut Vec<DefId>,
- external_mods: &mut FxHashSet<DefId>,
- def: Def) {
- let def_id = def.def_id();
- match def {
- Def::Trait(..) => {
- traits.push(def_id);
+
+ fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
+
+ fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {}
+ }
+
+ tcx.hir().krate().visit_all_item_likes(&mut Visitor {
+ map: &tcx.hir(),
+ traits: &mut traits,
+ });
+
+ // Cross-crate:
+
+ let mut external_mods = FxHashSet::default();
+ fn handle_external_def(tcx: TyCtxt,
+ traits: &mut Vec<DefId>,
+ external_mods: &mut FxHashSet<DefId>,
+ def: Def) {
+ let def_id = def.def_id();
+ match def {
+ Def::Trait(..) => {
+ traits.push(def_id);
+ }
+ Def::Mod(..) => {
+ if !external_mods.insert(def_id) {
+ return;
}
- Def::Mod(..) => {
- if !external_mods.insert(def_id) {
- return;
- }
- for child in tcx.item_children(def_id).iter() {
- handle_external_def(tcx, traits, external_mods, child.def)
- }
+ for child in tcx.item_children(def_id).iter() {
+ handle_external_def(tcx, traits, external_mods, child.def)
}
- _ => {}
}
+ _ => {}
}
- for &cnum in tcx.crates().iter() {
- let def_id = DefId {
- krate: cnum,
- index: CRATE_DEF_INDEX,
- };
- handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
- }
+ }
+ for &cnum in tcx.crates().iter() {
+ let def_id = DefId {
+ krate: cnum,
+ index: CRATE_DEF_INDEX,
+ };
+ handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
+ }
traits
}
hir::intravisit::walk_mod(self, module, node_id);
return;
}
- // find a use statement
+ // Find a `use` statement.
for item_id in &module.item_ids {
let item = self.tcx.hir().expect_item(item_id.id);
match item.node {
hir::ItemKind::Use(..) => {
- // don't suggest placing a use before the prelude
- // import or other generated ones
+ // Don't suggest placing a `use` before the prelude
+ // import or other generated ones.
if item.span.ctxt().outer().expn_info().is_none() {
self.span = Some(item.span.shrink_to_lo());
self.found_use = true;
return;
}
},
- // don't place use before extern crate
+ // Don't place `use` before `extern crate`...
hir::ItemKind::ExternCrate(_) => {}
- // but place them before the first other item
+ // ...but do place them before the first other item.
_ => if self.span.map_or(true, |span| item.span < span ) {
if item.span.ctxt().outer().expn_info().is_none() {
- // don't insert between attributes and an item
+ // Don't insert between attributes and an item.
if item.attrs.is_empty() {
self.span = Some(item.span.shrink_to_lo());
} else {
- // find the first attribute on the item
+ // Find the first attribute on the item.
for attr in &item.attrs {
if self.span.map_or(true, |span| attr.span < span) {
self.span = Some(attr.span.shrink_to_lo());
}
}
}
+
fn nested_visit_map<'this>(
&'this mut self
) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-/*
+/*!
# check.rs
Within the check phase of type check, we check each item one at a time
(bodies of function expressions are checked as part of the containing
-function). Inference is used to supply types wherever they are
-unknown.
+function). Inference is used to supply types wherever they are unknown.
By far the most complex case is checking the body of a function. This
can be broken down into several distinct phases:
The types of top-level items, which never contain unbound type
variables, are stored directly into the `tcx` tables.
-N.B.: A type variable is not the same thing as a type parameter. A
+N.B., a type variable is not the same thing as a type parameter. A
type variable is rather an "instance" of a type parameter: that is,
given a generic function `fn foo<T>(t: T)`: while checking the
function `foo`, the type `ty_param(0)` refers to the type `T`, which
*/
-pub use self::Expectation::*;
-use self::autoderef::Autoderef;
-use self::callee::DeferredCallResolution;
-use self::coercion::{CoerceMany, DynamicCoerceMany};
-pub use self::compare_method::{compare_impl_method, compare_const_impl};
-use self::method::MethodCallee;
-use self::TupleArgumentsFlag::*;
+mod autoderef;
+pub mod dropck;
+pub mod _match;
+pub mod writeback;
+mod regionck;
+pub mod coercion;
+pub mod demand;
+pub mod method;
+mod upvar;
+mod wfcheck;
+mod cast;
+mod closure;
+mod callee;
+mod compare_method;
+mod generator_interior;
+mod intrinsic;
+mod op;
use astconv::AstConv;
-use hir::GenericArg;
-use hir::def::Def;
-use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
-use std::slice;
+use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
+use rustc::hir::{self, GenericArg, Node, ItemKind, PatKind};
+use rustc::hir::def::Def;
+use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
+use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
+use rustc::hir::itemlikevisit::ItemLikeVisitor;
+use middle::lang_items;
use namespace::Namespace;
+use rustc_data_structures::indexed_vec::Idx;
+use rustc_data_structures::sync::Lrc;
+use rustc_target::spec::abi::Abi;
use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
use rustc::infer::opaque_types::OpaqueTypeDecl;
use rustc::infer::type_variable::{TypeVariableOrigin};
use rustc::ty::query::Providers;
use rustc::ty::util::{Representability, IntTypeExt, Discr};
use rustc::ty::layout::VariantIdx;
-use rustc_data_structures::indexed_vec::Idx;
-use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
-
-use require_c_abi_if_variadic;
-use session::{CompileIncomplete, config, Session};
-use TypeAndSubsts;
-use lint;
-use util::common::{ErrorReported, indenter};
-use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, FxHashSet, NodeMap};
+use syntax_pos::{self, BytePos, Span, MultiSpan};
+use syntax::ast;
+use syntax::attr;
+use syntax::feature_gate::{GateIssue, emit_feature_err};
+use syntax::ptr::P;
+use syntax::source_map::{DUMMY_SP, original_sp};
+use syntax::symbol::{Symbol, LocalInternedString, keywords};
+use syntax::util::lev_distance::find_best_match_for_name;
use std::cell::{Cell, RefCell, Ref, RefMut};
-use rustc_data_structures::sync::Lrc;
use std::collections::hash_map::Entry;
use std::cmp;
use std::fmt::Display;
use std::iter;
use std::mem::replace;
use std::ops::{self, Deref};
-use rustc_target::spec::abi::Abi;
-use syntax::ast;
-use syntax::attr;
-use syntax::source_map::DUMMY_SP;
-use syntax::source_map::original_sp;
-use syntax::feature_gate::{GateIssue, emit_feature_err};
-use syntax::ptr::P;
-use syntax::symbol::{Symbol, LocalInternedString, keywords};
-use syntax::util::lev_distance::find_best_match_for_name;
-use syntax_pos::{self, BytePos, Span, MultiSpan};
+use std::slice;
-use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
-use rustc::hir::itemlikevisit::ItemLikeVisitor;
-use rustc::hir::Node;
-use rustc::hir::{self, PatKind, ItemKind};
-use rustc::middle::lang_items;
+use require_c_abi_if_variadic;
+use session::{CompileIncomplete, config, Session};
+use TypeAndSubsts;
+use lint;
+use util::common::{ErrorReported, indenter};
+use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, FxHashSet, NodeMap};
-mod autoderef;
-pub mod dropck;
-pub mod _match;
-pub mod writeback;
-mod regionck;
-pub mod coercion;
-pub mod demand;
-pub mod method;
-mod upvar;
-mod wfcheck;
-mod cast;
-mod closure;
-mod callee;
-mod compare_method;
-mod generator_interior;
-mod intrinsic;
-mod op;
+pub use self::Expectation::*;
+use self::autoderef::Autoderef;
+use self::callee::DeferredCallResolution;
+use self::coercion::{CoerceMany, DynamicCoerceMany};
+pub use self::compare_method::{compare_impl_method, compare_const_impl};
+use self::method::MethodCallee;
+use self::TupleArgumentsFlag::*;
/// The type of a local binding, including the revealed type for anon types.
#[derive(Copy, Clone)]
formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
// Check the arguments.
- // We do this in a pretty awful way: first we typecheck any arguments
- // that are not closures, then we typecheck the closures. This is so
+ // We do this in a pretty awful way: first we type-check any arguments
+ // that are not closures, then we type-check the closures. This is so
// that we have more information about the types of arguments when we
- // typecheck the functions. This isn't really the right way to do this.
+ // type-check the functions. This isn't really the right way to do this.
for &check_closures in &[false, true] {
debug!("check_closures={}", check_closures);
for (i, arg) in args.iter().take(t).enumerate() {
// Warn only for the first loop (the "no closures" one).
// Closure arguments themselves can't be diverging, but
- // a previous argument can, e.g. `foo(panic!(), || {})`.
+ // a previous argument can, e.g., `foo(panic!(), || {})`.
if !check_closures {
self.warn_if_unreachable(arg.id, arg.span, "expression");
}
self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
}
- // determine the `self` type, using fresh variables for all variables
+ // Determine the `Self` type, using fresh variables for all variables
// declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
- // would return ($0, $1) where $0 and $1 are freshly instantiated type
+ // would return `($0, $1)` where `$0` and `$1` are freshly instantiated type
// variables.
pub fn impl_self_ty(&self,
span: Span, // (potential) receiver for this impl
let mut error_happened = false;
- // Typecheck each field.
+ // Type-check each field.
for field in ast_fields {
let ident = tcx.adjust_ident(field.ident, variant.did, self.body_id).0;
let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
seen_fields.insert(ident, field.span);
self.write_field_index(field.id, i);
- // we don't look at stability attributes on
+ // We don't look at stability attributes on
// struct-like enums (yet...), but it's definitely not
- // a bug to have construct one.
+ // a bug to have constructed one.
if adt_kind != ty::AdtKind::Enum {
tcx.check_stability(v_field.did, Some(expr_id), field.span);
}
};
// Make sure to give a type to the field even if there's
- // an error, so we can continue typechecking
+ // an error, so we can continue type-checking.
self.check_expr_coercable_to_type(&field.expr, field_type);
}
hir::QPath::TypeRelative(ref qself, _) => qself.span
};
- // Prohibit struct expressions when non exhaustive flag is set.
+ // Prohibit struct expressions when non-exhaustive flag is set.
let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
span_err!(self.tcx.sess, expr.span, E0639,
expr: &'gcx hir::Expr,
expected: Expectation<'tcx>,
needs: Needs) -> Ty<'tcx> {
- debug!(">> typechecking: expr={:?} expected={:?}",
+ debug!(">> type-checking: expr={:?} expected={:?}",
expr, expected);
// Warn for expressions after diverging siblings.
if !tcx.features().unsized_locals {
// We want to remove some Sized bounds from std functions,
// but don't want to expose the removal to stable Rust.
- // i.e. we don't want to allow
+ // i.e., we don't want to allow
//
// ```rust
// drop as fn(str);
}
}
}
- // There was an error, make typecheck fail
+ // There was an error; make type-check fail.
tcx.types.err
}
if destination.target_id.is_ok() {
tcx.types.never
} else {
- // There was an error, make typecheck fail
+ // There was an error; make type-check fail.
tcx.types.err
}
}
}
if needs_note {
err.help("to access tuple elements, use tuple indexing \
- syntax (e.g. `tuple.0`)");
+ syntax (e.g., `tuple.0`)");
}
}
err.emit();
assert!(!substs.has_escaping_bound_vars());
assert!(!ty.has_escaping_bound_vars());
- // Write the "user substs" down first thing for later.
+ // First, store the "user substs" for later.
let hir_id = self.tcx.hir().node_to_hir_id(node_id);
self.write_user_substs_from_substs(hir_id, substs, user_self_ty);
// Find a suitable supertype of the LHS expression's type, by coercing to
// a type variable, to pass as the `Self` to the trait, avoiding invariant
// trait matching creating lifetime constraints that are too strict.
- // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
+ // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
// in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None);
let fresh_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span));
};
let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
- // NB: As we have not yet type-checked the RHS, we don't have the
+ // N.B., as we have not yet type-checked the RHS, we don't have the
// type at hand. Make a variable to represent it. The whole reason
// for this indirection is so that, below, we can check the expr
// using this variable as the expected type, which sometimes lets
self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
rhs_ty, &mut err, true) {
// This has nothing here because it means we did string
- // concatenation (e.g. "Hello " += "World!"). This means
+ // concatenation (e.g., "Hello " += "World!"). This means
// we don't want the note in the else clause to be emitted
} else if let ty::Param(_) = lhs_ty.sty {
// FIXME: point to span of param
self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
rhs_ty, &mut err, false) {
// This has nothing here because it means we did string
- // concatenation (e.g. "Hello " + "World!"). This means
+ // concatenation (e.g., "Hello " + "World!"). This means
// we don't want the note in the else clause to be emitted
} else if let ty::Param(_) = lhs_ty.sty {
// FIXME: point to span of param
Unary(hir::UnOp, Span),
}
-/// Returns true if this is a built-in arithmetic operation (e.g. u32
+/// Returns true if this is a built-in arithmetic operation (e.g., u32
/// + u32, i16x4 == i16x4) and false if these types would have to be
/// overloaded to be legal. There are two reasons that we distinguish
/// builtin operations from overloaded ones (vs trying to drive
// variance where possible. (This is because
// we may have to evaluate constraint
// expressions in the course of execution.)
- // See e.g. #41936.
+ // See e.g., #41936.
if let Ok(ok) = infcx.at(&cause, param_env).eq(a, b) {
if ok.obligations.is_empty() {
return None;
}
// Collect up all fields that were significantly changed
- // i.e. those that contain T in coerce_unsized T -> U
+ // i.e., those that contain T in coerce_unsized T -> U
Some((i, a, b))
})
.collect::<Vec<_>>();
tcx.item_path_str(impl_def_id));
// Skip impls where one of the self type is an error type.
- // This occurs with e.g. resolve failures (#30589).
+ // This occurs with e.g., resolve failures (#30589).
if trait_ref.references_error() {
return;
}
sp,
E0210,
"type parameter `{}` must be used as the type parameter \
- for some local type (e.g. `MyStruct<{}>`)",
+ for some local type (e.g., `MyStruct<{}>`)",
param_ty,
param_ty)
.span_label(sp,
/// AstConv. It has information about the predicates that are defined
/// on the trait. Unfortunately, this predicate information is
/// available in various different forms at various points in the
-/// process. So we can't just store a pointer to e.g. the AST or the
+/// process. So we can't just store a pointer to e.g., the AST or the
/// parsed ty form, we have to be more flexible. To this end, the
/// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
/// `get_type_parameter_bounds` requests, drawing the information from
let icx = ItemCtxt::new(tcx, trait_def_id);
- // Convert the bounds that follow the colon, e.g. `Bar + Zed` in `trait Foo : Bar + Zed`.
+ // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo : Bar + Zed`.
let self_param_ty = tcx.mk_self_type();
let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
// Convert any explicit superbounds in the where clause,
- // e.g. `trait Foo where Self : Bar`.
+ // e.g., `trait Foo where Self : Bar`.
// In the case of trait aliases, however, we include all bounds in the where clause,
- // so e.g. `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
+ // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
// as one of its "superpredicates".
let is_trait_alias = ty::is_trait_alias(tcx, trait_def_id);
let superbounds2 = icx.type_parameter_bounds_in_generics(
let substs = Substs::identity_for_item(tcx, def_id);
let opaque_ty = tcx.mk_opaque(def_id, substs);
- // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
+ // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
let bounds = compute_bounds(
&icx,
opaque_ty,
let substs = Substs::identity_for_item(tcx, def_id);
let opaque_ty = tcx.mk_opaque(def_id, substs);
- // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
+ // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
let bounds = compute_bounds(
&icx,
opaque_ty,
}
/// If `include_projections` is false, returns the list of parameters that are
-/// constrained by `t` - i.e. the value of each parameter in the list is
+/// constrained by `t` - i.e., the value of each parameter in the list is
/// uniquely determined by `t` (see RFC 447). If it is true, return the list
/// of parameters whose values are needed in order to constrain `ty` - these
/// differ, with the latter being a superset, in the presence of projections.
fn f(a: u16, b: &str) {}
```
-Must always be called with exactly two arguments, e.g. `f(2, "test")`.
+Must always be called with exactly two arguments, e.g., `f(2, "test")`.
Note that Rust does not have a notion of optional function arguments or
variadic functions (except for its C-FFI).
E0185: r##"
An associated function for a trait was defined to be static, but an
-implementation of the trait declared the same function to be a method (i.e. to
+implementation of the trait declared the same function to be a method (i.e., to
take a `self` parameter).
Here's an example of this error:
"##,
E0186: r##"
-An associated function for a trait was defined to be a method (i.e. to take a
+An associated function for a trait was defined to be a method (i.e., to take a
`self` parameter), but an implementation of the trait declared the same function
to be static.
/*!
-typeck.rs, an introduction
+# typeck.rs
The type checker is responsible for:
-1. Determining the type of each expression
-2. Resolving methods and traits
-3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
+1. Determining the type of each expression.
+2. Resolving methods and traits.
+3. Guaranteeing that most type rules are met. ("Most?", you say, "why most?"
Well, dear reader, read on)
-The main entry point is `check_crate()`. Type checking operates in
+The main entry point is `check_crate()`. Type checking operates in
several major phases:
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
-2. Variance inference then runs to compute the variance of each parameter
+2. Variance inference then runs to compute the variance of each parameter.
-3. Coherence checks for overlapping or orphaned impls
+3. Coherence checks for overlapping or orphaned impls.
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
independently:
- astconv: converts the AST representation of types
- into the `ty` representation
+ into the `ty` representation.
- collect: computes the types of each top-level item and enters them into
- the `tcx.types` table for later use
+ the `tcx.types` table for later use.
-- coherence: enforces coherence rules, builds some tables
+- coherence: enforces coherence rules, builds some tables.
- variance: variance inference
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
-# Note
+## Note
This API is completely unstable and subject to change.
extern crate rustc_target;
extern crate smallvec;
-use rustc::hir;
-use rustc::lint;
-use rustc::middle;
-use rustc::session;
-use rustc::util;
-
-use hir::Node;
-use rustc::infer::InferOk;
-use rustc::ty::subst::Substs;
-use rustc::ty::{self, Ty, TyCtxt};
-use rustc::ty::query::Providers;
-use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt};
-use rustc::util::profiling::ProfileCategory;
-use session::{CompileIncomplete, config};
-use util::common::time;
-
-use syntax::ast;
-use rustc_target::spec::abi::Abi;
-use syntax_pos::Span;
-
-use std::iter;
-
-// NB: This module needs to be declared first so diagnostics are
+// N.B., this module needs to be declared first so diagnostics are
// registered before they are used.
mod diagnostics;
mod outlives;
mod variance;
+use hir::Node;
+use rustc_target::spec::abi::Abi;
+use rustc::hir;
+use rustc::infer::InferOk;
+use rustc::lint;
+use rustc::middle;
+use rustc::session;
+use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt};
+use rustc::ty::subst::Substs;
+use rustc::ty::{self, Ty, TyCtxt};
+use rustc::ty::query::Providers;
+use rustc::util;
+use rustc::util::profiling::ProfileCategory;
+use session::{CompileIncomplete, config};
+use syntax_pos::Span;
+use syntax::ast;
+use util::common::time;
+
+use std::iter;
+
pub struct TypeAndSubsts<'tcx> {
substs: &'tcx Substs<'tcx>,
ty: Ty<'tcx>,
// case that `substs` come from a `dyn Trait` type, our caller will have
// included `Self = usize` as the value for `Self`. If we were
// to apply the substs, and not filter this predicate, we might then falsely
- // conclude that e.g. `X: 'x` was a reasonable inferred requirement.
+ // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
//
// Another similar case is where we have a inferred
// requirement like `<Self as Trait>::Foo: 'b`. We presently
}
/// To build constraints, we visit one item (type, trait) at a time
-/// and look at its contents. So e.g. if we have
+/// and look at its contents. So e.g., if we have
///
/// struct Foo<T> {
/// b: Bar<T>
let newly_added = self.inferred_starts.insert(id, InferredIndex(start)).is_none();
assert!(newly_added);
- // NB: In the code below for writing the results back into the
+ // N.B., in the code below for writing the results back into the
// `CrateVariancesMap`, we rely on the fact that all inferreds
// for a particular item are assigned continuous indices.
// handle_lifetimes determines what *needs be* true in order for an impl to hold.
// lexical_region_resolve, along with much of the rest of the compiler, is concerned
// with determining if a given set up constraints/predicates *are* met, given some
- // starting conditions (e.g. user-provided code). For this reason, it's easier
+ // starting conditions (e.g., user-provided code). For this reason, it's easier
// to perform the calculations we need on our own, rather than trying to make
// existing inference/solver code do what we want.
fn handle_lifetimes<'cx>(
// Flattening is done in two parts. First, we insert all of the constraints
// into a map. Each RegionTarget (either a RegionVid or a Region) maps
// to its smaller and larger regions. Note that 'larger' regions correspond
- // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region).
+ // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region).
for constraint in regions.constraints.keys() {
match constraint {
&Constraint::VarSubVar(r1, r2) => {
// display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's,
// so we fix them up:
//
- // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug'
+ // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug'
// becomes 'T: Copy + Debug'
// * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), <T as Fn::Output> =
// K', we use the dedicated syntax 'T: Fn() -> K'
);
// The `Sized` trait must be handled specially, since we only only display it when
- // it is *not* required (i.e. '?Sized')
+ // it is *not* required (i.e., '?Sized')
let sized_trait = self.cx
.tcx
.require_lang_item(lang_items::SizedTraitLangItem);
let is_fn = match &mut b {
&mut GenericBound::TraitBound(ref mut p, _) => {
// Insert regions into the for_generics hash map first, to ensure
- // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
+ // that we don't end up with duplicate bounds (e.g., for<'b, 'b>)
for_generics.extend(p.generic_params.clone());
p.generic_params = for_generics.into_iter().collect();
self.is_fn_ty(&tcx, &p.trait_)
hir::TraitBoundModifier::None,
));
- // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so
+ // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so
// that we don't see a
// duplicate bound like `T: Iterator + Iterator<Item=u8>`
// on the docs page.
// auto-trait impls always render in exactly the same way.
//
// Using the Debug implementation for sorting prevents us from needing to
- // write quite a bit of almost entirely useless code (e.g. how should two
+ // write quite a bit of almost entirely useless code (e.g., how should two
// Types be sorted relative to each other). It also allows us to solve the
// problem for both WherePredicates and GenericBounds at the same time. This
// approach is probably somewhat slower, but the small number of items
True,
/// Denies all configurations.
False,
- /// A generic configuration option, e.g. `test` or `target_os = "linux"`.
+ /// A generic configuration option, e.g., `test` or `target_os = "linux"`.
Cfg(Symbol, Option<Symbol>),
- /// Negate a configuration requirement, i.e. `not(x)`.
+ /// Negate a configuration requirement, i.e., `not(x)`.
Not(Box<Cfg>),
- /// Union of a list of configuration requirements, i.e. `any(...)`.
+ /// Union of a list of configuration requirements, i.e., `any(...)`.
Any(Vec<Cfg>),
- /// Intersection of a list of configuration requirements, i.e. `all(...)`.
+ /// Intersection of a list of configuration requirements, i.e., `all(...)`.
All(Vec<Cfg>),
}
/// Parses a `MetaItem` into a `Cfg`.
///
- /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g. `unix` or
+ /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g., `unix` or
/// `target_os = "redox"`.
///
/// If the content is not properly formatted, it will return an error indicating what and where
//! This module contains the "cleaned" pieces of the AST, and the functions
//! that clean them.
-pub use self::Type::*;
-pub use self::Mutability::*;
-pub use self::ItemEnum::*;
-pub use self::SelfTy::*;
-pub use self::FunctionRetTy::*;
-pub use self::Visibility::{Public, Inherited};
+pub mod inline;
+pub mod cfg;
+mod simplify;
+mod auto_trait;
+mod blanket_impl;
+pub mod def_ctor;
+use rustc_data_structures::indexed_vec::{IndexVec, Idx};
+use rustc_data_structures::sync::Lrc;
use rustc_target::spec::abi::Abi;
-use syntax::ast::{self, AttrStyle, Ident};
-use syntax::attr;
-use syntax::ext::base::MacroKind;
-use syntax::source_map::{dummy_spanned, Spanned};
-use syntax::ptr::P;
-use syntax::symbol::keywords::{self, Keyword};
-use syntax::symbol::InternedString;
-use syntax_pos::{self, DUMMY_SP, Pos, FileName};
-
+use rustc_typeck::hir_ty_to_ty;
+use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
use rustc::mir::interpret::ConstValue;
use rustc::middle::resolve_lifetime as rl;
-use rustc::ty::fold::TypeFolder;
use rustc::middle::lang_items;
+use rustc::middle::stability;
use rustc::mir::interpret::GlobalId;
use rustc::hir::{self, GenericArg, HirVec};
use rustc::hir::def::{self, Def, CtorKind};
use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc::ty::subst::Substs;
use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind};
+use rustc::ty::fold::TypeFolder;
use rustc::ty::layout::VariantIdx;
-use rustc::middle::stability;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
-use rustc_typeck::hir_ty_to_ty;
-use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
-use rustc_data_structures::indexed_vec::{IndexVec, Idx};
+use syntax::ast::{self, AttrStyle, Ident};
+use syntax::attr;
+use syntax::ext::base::MacroKind;
+use syntax::source_map::{dummy_spanned, Spanned};
+use syntax::ptr::P;
+use syntax::symbol::keywords::{self, Keyword};
+use syntax::symbol::InternedString;
+use syntax_pos::{self, DUMMY_SP, Pos, FileName};
use std::collections::hash_map::Entry;
use std::fmt;
use std::default::Default;
use std::{mem, slice, vec};
use std::iter::{FromIterator, once};
-use rustc_data_structures::sync::Lrc;
use std::rc::Rc;
use std::str::FromStr;
use std::cell::RefCell;
use html::render::{cache, ExternalLocation};
use html::item_type::ItemType;
-pub mod inline;
-pub mod cfg;
-mod simplify;
-mod auto_trait;
-mod blanket_impl;
-pub mod def_ctor;
-
use self::cfg::Cfg;
use self::auto_trait::AutoTraitFinder;
use self::blanket_impl::BlanketImplFinder;
+pub use self::Type::*;
+pub use self::Mutability::*;
+pub use self::ItemEnum::*;
+pub use self::SelfTy::*;
+pub use self::FunctionRetTy::*;
+pub use self::Visibility::{Public, Inherited};
+
thread_local!(pub static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = Default::default());
const FN_OUTPUT_NAME: &'static str = "Output";
}
// It would be nice to collect all of the bounds on a type and recombine
- // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
+ // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
// and instead see `where T: Foo + Bar + Sized + 'a`
Generics {
}
}
-/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
+/// An equality constraint on an associated type, e.g., `A=Bar` in `Foo<A=Bar>`
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug, Hash)]
pub struct TypeBinding {
pub name: String,
//! more canonical form.
//!
//! Currently all cross-crate-inlined function use `rustc::ty` to reconstruct
-//! the AST (e.g. see all of `clean::inline`), but this is not always a
+//! the AST (e.g., see all of `clean::inline`), but this is not always a
//! non-lossy transformation. The current format of storage for where clauses
//! for functions and such is simply a list of predicates. One example of this
//! is that the AST predicate of: `where T: Trait<Foo=Bar>` is encoded as:
<div class=\"infos\">\
<h2>Search Tricks</h2>\
<p>\
- Prefix searches with a type followed by a colon (e.g. \
+ Prefix searches with a type followed by a colon (e.g., \
<code>fn:</code>) to restrict the search to a given type.\
</p>\
<p>\
and <code>const</code>.\
</p>\
<p>\
- Search functions by type signature (e.g. \
+ Search functions by type signature (e.g., \
<code>vec -> usize</code> or <code>* -> vec</code>)\
</p>\
<p>\
- Search multiple things at once by splitting your query with comma (e.g. \
+ Search multiple things at once by splitting your query with comma (e.g., \
<code>str,u8</code> or <code>String,struct:Vec,test</code>)\
</p>\
</div>\
fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
where F: FnMut(&mut Context, clean::Item),
{
- // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
+ // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
// if they contain impls for public types. These modules can also
// contain items such as publicly re-exported structures.
//
pub struct TocBuilder {
top_level: Toc,
/// The current hierarchy of parent headings, the levels are
- /// strictly increasing (i.e. chain[0].level < chain[1].level <
+ /// strictly increasing (i.e., chain[0].level < chain[1].level <
/// ...) with each entry being the most recent occurrence of a
/// heading with that level (it doesn't include the most recent
/// occurrences of every level, just, if it *is* in `chain` then
}
/// Collapse the chain until the first heading more important than
- /// `level` (i.e. lower level)
+ /// `level` (i.e., lower level)
///
/// Example:
///
/// ### H
/// ```
///
- /// If we are considering H (i.e. level 3), then A and B are in
+ /// If we are considering H (i.e., level 3), then A and B are in
/// self.top_level, D is in C.children, and C, E, F, G are in
/// self.chain.
///
///
/// This leaves us looking at E, which does have a smaller level,
/// and, by construction, it's the most recent thing with smaller
- /// level, i.e. it's the immediate parent of H.
+ /// level, i.e., it's the immediate parent of H.
fn fold_until(&mut self, level: u32) {
let mut this = None;
loop {
assert!(level >= 1);
// collapse all previous sections into their parents until we
- // get to relevant heading (i.e. the first one with a smaller
+ // get to relevant heading (i.e., the first one with a smaller
// level than us)
self.fold_until(level);
(entry.level, &entry.children)
}
};
- // fill in any missing zeros, e.g. for
+ // fill in any missing zeros, e.g., for
// # Foo (1)
// ### Bar (1.0.1)
for _ in toc_level..level - 1 {
unstable("resource-suffix", |o| {
o.optopt("",
"resource-suffix",
- "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
+ "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \
\"light-suffix.css\"",
"PATH")
}),
(metadata, "")
}
-/// Render `input` (e.g. "foo.md") into an HTML file in `output`
-/// (e.g. output = "bar" => "bar/foo.html").
+/// Render `input` (e.g., "foo.md") into an HTML file in `output`
+/// (e.g., output = "bar" => "bar/foo.html").
pub fn render(input: PathBuf, options: RenderOptions, diag: &errors::Handler) -> isize {
let mut output = options.output;
output.push(input.file_stem().unwrap());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use clean::*;
-
use rustc::lint as lint;
use rustc::hir;
use rustc::hir::def::Def;
use fold::DocFolder;
use html::markdown::markdown_links;
+use clean::*;
use passes::{look_for_tests, Pass};
pub const COLLECT_INTRA_DOC_LINKS: Pass =
#[derive(Debug)]
enum PathKind {
- /// can be either value or type, not a macro
+ /// Either a value or type, but not a macro
Unknown,
- /// macro
+ /// Macro
Macro,
- /// values, functions, consts, statics, everything in the value namespace
+ /// Values, functions, consts, statics (everything in the value namespace)
Value,
- /// types, traits, everything in the type namespace
+ /// Types, traits (everything in the type namespace)
Type,
}
/// Resolve a given string as a path, along with whether or not it is
/// in the value namespace. Also returns an optional URL fragment in the case
- /// of variants and methods
+ /// of variants and methods.
fn resolve(&self,
path_str: &str,
is_val: bool,
let cx = self.cx;
// In case we're in a module, try to resolve the relative
- // path
+ // path.
if let Some(id) = parent_id.or(self.mod_ids.last().cloned()) {
- // FIXME: `with_scope` requires the NodeId of a module
+ // FIXME: `with_scope` requires the `NodeId` of a module.
let result = cx.resolver.borrow_mut()
.with_scope(id,
|resolver| {
if let Ok(result) = result {
// In case this is a trait item, skip the
- // early return and try looking for the trait
+ // early return and try looking for the trait.
let value = match result.def {
Def::Method(_) | Def::AssociatedConst(_) => true,
Def::AssociatedTy(_) => false,
Def::Variant(_) => return handle_variant(cx, result.def),
- // not a trait item, just return what we found
+ // Not a trait item; just return what we found.
_ => return Ok((result.def, None))
};
} else {
// If resolution failed, it may still be a method
// because methods are not handled by the resolver
- // If so, bail when we're not looking for a value
+ // If so, bail when we're not looking for a value.
if !is_val {
return Err(())
}
}
- // Try looking for methods and associated items
+ // Try looking for methods and associated items.
let mut split = path_str.rsplitn(2, "::");
let item_name = if let Some(first) = split.next() {
first
}
}
- // FIXME: `with_scope` requires the NodeId of a module
+ // FIXME: `with_scope` requires the `NodeId` of a module.
let ty = cx.resolver.borrow_mut()
.with_scope(id,
|resolver| {
None
};
- // FIXME: get the resolver to work with non-local resolve scopes
+ // FIXME: get the resolver to work with non-local resolve scopes.
let parent_node = self.cx.as_local_node_id(item.def_id).and_then(|node_id| {
// FIXME: this fails hard for impls in non-module scope, but is necessary for the
- // current resolve() implementation
+ // current `resolve()` implementation.
match self.cx.tcx.hir().get_module_parent_node(node_id) {
id if id != node_id => Some(id),
_ => None,
} else {
match parent_node.or(self.mod_ids.last().cloned()) {
Some(parent) if parent != NodeId::from_u32(0) => {
- //FIXME: can we pull the parent module's name from elsewhere?
+ // FIXME: can we pull the parent module's name from elsewhere?
Some(self.cx.tcx.hir().name(parent).to_string())
}
_ => None,
ImplItem(Impl { ref for_, .. }) => {
for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
}
- // we don't display docs on `extern crate` items anyway, so don't process them
+ // we don't display docs on `extern crate` items anyway, so don't process them.
ExternCrateItem(..) => return self.fold_item_recur(item),
ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
MacroItem(..) => None,
}
for (ori_link, link_range) in markdown_links(&dox) {
- // bail early for real links
+ // Bail early for real links.
if ori_link.contains('/') {
continue;
}
def
} else {
resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
- // this could just be a normal link or a broken link
+ // This could just be a normal link or a broken link
// we could potentially check if something is
- // "intra-doc-link-like" and warn in that case
+ // "intra-doc-link-like" and warn in that case.
continue;
}
}
def
} else {
resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
- // this could just be a normal link
+ // This could just be a normal link.
continue;
}
}
PathKind::Unknown => {
- // try everything!
+ // Try everything!
if let Some(macro_def) = macro_resolve(cx, path_str) {
if let Ok(type_def) =
self.resolve(path_str, false, ¤t_item, parent_node)
{
// It is imperative we search for not-a-value first
// Otherwise we will find struct ctors for when we are looking
- // for structs, and the link won't work.
- // if there is something in both namespaces
+ // for structs, and the link won't work if there is something in
+ // both namespaces.
if let Ok(value_def) =
self.resolve(path_str, true, ¤t_item, parent_node)
{
}
}
-/// Resolve a string as a macro
+/// Resolve a string as a macro.
fn macro_resolve(cx: &DocContext, path_str: &str) -> Option<Def> {
use syntax::ext::base::{MacroKind, SyntaxExtension};
let segment = ast::PathSegment::from_ident(Ident::from_str(path_str));
let mut diag;
if dox.lines().count() == code_dox.lines().count() {
let line_offset = dox[..link_range.start].lines().count();
- // The span starts in the `///`, so we don't have to account for the leading whitespace
+ // The span starts in the `///`, so we don't have to account for the leading whitespace.
let code_dox_len = if line_offset <= 1 {
doc_comment_padding
} else {
- // The first `///`
+ // The first `///`.
doc_comment_padding +
- // Each subsequent leading whitespace and `///`
+ // Each subsequent leading whitespace and `///`.
code_dox.lines().skip(1).take(line_offset - 1).fold(0, |sum, line| {
sum + doc_comment_padding + line.len() - line.trim_start().len()
})
};
- // Extract the specific span
+ // Extract the specific span.
let sp = sp.from_inner_byte_pos(
link_range.start + code_dox_len,
link_range.end + code_dox_len,
let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
- // Print the line containing the `link_range` and manually mark it with '^'s
+ // Print the line containing the `link_range` and manually mark it with '^'s.
diag.note(&format!(
"the link appears in this line:\n\n{line}\n\
{indicator: <before$}{indicator:^<found$}",
}
/// Given a def, returns its name and disambiguator
-/// for a value namespace
+/// for a value namespace.
///
-/// Returns None for things which cannot be ambiguous since
-/// they exist in both namespaces (structs and modules)
+/// Returns `None` for things which cannot be ambiguous since
+/// they exist in both namespaces (structs and modules).
fn value_ns_kind(def: Def, path_str: &str) -> Option<(&'static str, String)> {
match def {
- // structs, variants, and mods exist in both namespaces. skip them
+ // Structs, variants, and mods exist in both namespaces; skip them.
Def::StructCtor(..) | Def::Mod(..) | Def::Variant(..) |
Def::VariantCtor(..) | Def::SelfCtor(..)
=> None,
}
/// Given a def, returns its name, the article to be used, and a disambiguator
-/// for the type namespace
+/// for the type namespace.
fn type_ns_kind(def: Def, path_str: &str) -> (&'static str, &'static str, String) {
let (kind, article) = match def {
- // we can still have non-tuple structs
+ // We can still have non-tuple structs.
Def::Struct(..) => ("struct", "a"),
Def::Enum(..) => ("enum", "an"),
Def::Trait(..) => ("trait", "a"),
(kind, article, format!("{}@{}", kind, path_str))
}
-/// Given an enum variant's def, return the def of its enum and the associated fragment
+/// Given an enum variant's def, return the def of its enum and the associated fragment.
fn handle_variant(cx: &DocContext, def: Def) -> Result<(Def, Option<String>), ()> {
use rustc::ty::DefIdTree;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::env;
-use std::ffi::OsString;
-use std::io::prelude::*;
-use std::io;
-use std::path::PathBuf;
-use std::panic::{self, AssertUnwindSafe};
-use std::process::Command;
-use std::str;
+use errors;
+use errors::emitter::ColorConfig;
use rustc_data_structures::sync::Lrc;
-use std::sync::{Arc, Mutex};
-
-use testing;
use rustc_lint;
+use rustc_driver::{self, driver, target_features, Compilation};
+use rustc_driver::driver::phase_2_configure_and_expand;
+use rustc_metadata::cstore::CStore;
+use rustc_metadata::dynamic_lib::DynamicLibrary;
+use rustc_resolve::MakeGlobMap;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::session::{self, CompileIncomplete, config};
use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
use rustc::session::search_paths::{SearchPaths, PathKind};
-use rustc_metadata::dynamic_lib::DynamicLibrary;
-use tempfile::Builder as TempFileBuilder;
-use rustc_driver::{self, driver, target_features, Compilation};
-use rustc_driver::driver::phase_2_configure_and_expand;
-use rustc_metadata::cstore::CStore;
-use rustc_resolve::MakeGlobMap;
use syntax::ast;
use syntax::source_map::SourceMap;
use syntax::edition::Edition;
use syntax::feature_gate::UnstableFeatures;
use syntax::with_globals;
use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
-use errors;
-use errors::emitter::ColorConfig;
+use tempfile::Builder as TempFileBuilder;
+use testing;
+
+use std::env;
+use std::ffi::OsString;
+use std::io::prelude::*;
+use std::io;
+use std::path::PathBuf;
+use std::panic::{self, AssertUnwindSafe};
+use std::process::Command;
+use std::str;
+use std::sync::{Arc, Mutex};
use clean::Attributes;
use config::Options;
})
}
-// Look for #![doc(test(no_crate_inject))], used by crates in the std facade
+// Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
use syntax::print::pprust;
should_panic: bool, no_run: bool, as_test_harness: bool,
compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) {
- // the test harness wants its own `main` & top level functions, so
- // never wrap the test in `fn main() { ... }`
+ // The test harness wants its own `main` and top-level functions, so
+ // never wrap the test in `fn main() { ... }`.
let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
// FIXME(#44940): if doctests ever support path remapping, then this filename
- // needs to be the result of SourceMap::span_to_unmapped_path
-
+ // needs to be the result of `SourceMap::span_to_unmapped_path`.
let path = match filename {
FileName::Real(path) => path.clone(),
_ => PathBuf::from(r"doctest.rs"),
let filename = FileName::anon_source_code(s);
let source = crates + &everything_else;
- // any errors in parsing should also appear when the doctest is compiled for real, so just
- // send all the errors that libsyntax emits directly into a Sink instead of stderr
+ // Any errors in parsing should also appear when the doctest is compiled for real, so just
+ // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let emitter = EmitterWriter::new(box io::sink(), None, false, false);
let handler = Handler::with_emitter(false, false, box emitter);
// The name of the test displayed to the user, separated by `::`.
//
// In tests from Rust source, this is the path to the item
- // e.g. `["std", "vec", "Vec", "push"]`.
+ // e.g., `["std", "vec", "Vec", "push"]`.
//
// In tests from a markdown file, this is the titles of all headers (h1~h6)
- // of the sections that contain the code block, e.g. if the markdown file is
+ // of the sections that contain the code block, e.g., if the markdown file is
// written as:
//
// ``````markdown
fn register_header(&mut self, name: &str, level: u32) {
if self.use_headers {
- // we use these headings as test names, so it's good if
+ // We use these headings as test names, so it's good if
// they're valid identifiers.
let name = name.chars().enumerate().map(|(i, c)| {
if (i == 0 && c.is_xid_start()) ||
// Here we try to efficiently assemble the header titles into the
// test name in the form of `h1::h2::h3::h4::h5::h6`.
//
- // Suppose originally `self.names` contains `[h1, h2, h3]`...
+ // Suppose that originally `self.names` contains `[h1, h2, h3]`...
let level = level as usize;
if level <= self.names.len() {
// ... Consider `level == 2`. All headers in the lower levels
attrs.collapse_doc_comments();
attrs.unindent_doc_comments();
- // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with
- // anything else, this will combine them for us
+ // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
+ // anything else, this will combine them for us.
if let Some(doc) = attrs.collapsed_doc_value() {
self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
let res = markdown::find_testable_code(&doc, self.collector, self.codes);
#[test]
fn make_test_crate_name_no_use() {
- //if you give a crate name but *don't* use it within the test, it won't bother inserting
- //the `extern crate` statement
+ // If you give a crate name but *don't* use it within the test, it won't bother inserting
+ // the `extern crate` statement.
let opts = TestOptions::default();
let input =
"assert_eq!(2+2, 4);";
#[test]
fn make_test_crate_name() {
- //if you give a crate name and use it within the test, it will insert an `extern crate`
- //statement before `fn main`
+ // If you give a crate name and use it within the test, it will insert an `extern crate`
+ // statement before `fn main`.
let opts = TestOptions::default();
let input =
"use asdf::qwop;
#[test]
fn make_test_no_crate_inject() {
- //even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
- //adding it anyway
+ // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
+ // adding it anyway.
let opts = TestOptions {
no_crate_inject: true,
display_warnings: false,
#[test]
fn make_test_ignore_std() {
- //even if you include a crate name, and use it in the doctest, we still won't include an
- //`extern crate` statement if the crate is "std" - that's included already by the compiler!
+ // Even if you include a crate name, and use it in the doctest, we still won't include an
+ // `extern crate` statement if the crate is "std" -- that's included already by the
+ // compiler!
let opts = TestOptions::default();
let input =
"use std::*;
#[test]
fn make_test_manual_extern_crate() {
- //when you manually include an `extern crate` statement in your doctest, make_test assumes
- //you've included one for your own crate too
+ // When you manually include an `extern crate` statement in your doctest, `make_test`
+ // assumes you've included one for your own crate too.
let opts = TestOptions::default();
let input =
"extern crate asdf;
#[test]
fn make_test_opts_attrs() {
- //if you supplied some doctest attributes with #![doc(test(attr(...)))], it will use those
- //instead of the stock #![allow(unused)]
+ // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
+ // those instead of the stock `#![allow(unused)]`.
let mut opts = TestOptions::default();
opts.attrs.push("feature(sick_rad)".to_string());
let input =
let output = make_test(input, Some("asdf"), false, &opts);
assert_eq!(output, (expected, 3));
- //adding more will also bump the returned line offset
+ // Adding more will also bump the returned line offset.
opts.attrs.push("feature(hella_dope)".to_string());
let expected =
"#![feature(sick_rad)]
#[test]
fn make_test_crate_attrs() {
- //including inner attributes in your doctest will apply them to the whole "crate", pasting
- //them outside the generated main function
+ // Including inner attributes in your doctest will apply them to the whole "crate", pasting
+ // them outside the generated main function.
let opts = TestOptions::default();
let input =
"#![feature(sick_rad)]
#[test]
fn make_test_with_main() {
- //including your own `fn main` wrapper lets the test use it verbatim
+ // Including your own `fn main` wrapper lets the test use it verbatim.
let opts = TestOptions::default();
let input =
"fn main() {
#[test]
fn make_test_fake_main() {
- //...but putting it in a comment will still provide a wrapper
+ // ... but putting it in a comment will still provide a wrapper.
let opts = TestOptions::default();
let input =
"//Ceci n'est pas une `fn main`
#[test]
fn make_test_dont_insert_main() {
- //even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper
+ // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
let opts = TestOptions::default();
let input =
"//Ceci n'est pas une `fn main`
#[test]
fn make_test_display_warnings() {
- //if the user is asking to display doctest warnings, suppress the default allow(unused)
+ // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
let mut opts = TestOptions::default();
opts.display_warnings = true;
let input =
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Rust AST Visitor. Extracts useful information and massages it into a form
-//! usable for clean
-
-use std::mem;
+//! The Rust AST Visitor. Extracts useful information and massages it into a form
+//! usable for `clean`.
+use rustc::hir::{self, Node};
+use rustc::hir::def::Def;
+use rustc::hir::def_id::{DefId, LOCAL_CRATE};
+use rustc::middle::privacy::AccessLevel;
+use rustc::util::nodemap::{FxHashSet, FxHashMap};
use syntax::ast;
use syntax::attr;
use syntax::ext::base::MacroKind;
use syntax::source_map::Spanned;
use syntax_pos::{self, Span};
-use rustc::hir::Node;
-use rustc::hir::def::Def;
-use rustc::hir::def_id::{DefId, LOCAL_CRATE};
-use rustc::middle::privacy::AccessLevel;
-use rustc::util::nodemap::{FxHashSet, FxHashMap};
-
-use rustc::hir;
+use std::mem;
use core;
use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
use doctree::*;
-// looks to me like the first two of these are actually
+// Looks to me like the first two of these are actually
// output parameters, maybe only mutated once; perhaps
// better simply to have the visit method return a tuple
// containing them?
-// also, is there some reason that this doesn't use the 'visit'
-// framework from syntax?
+// Also, is there some reason that this doesn't use the 'visit'
+// framework from syntax?.
pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> {
pub module: Module,
pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
view_item_stack: FxHashSet<ast::NodeId>,
inlining: bool,
- /// Is the current module and all of its parents public?
+ /// Are the current module and all of its parents public?
inside_public_path: bool,
exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
}
}
fn store_path(&mut self, did: DefId) {
- // We can't use the entry api, as that keeps the mutable borrow of self active
- // when we try to use cx
+ // We can't use the entry API, as that keeps the mutable borrow of `self` active
+ // when we try to use `cx`.
let exact_paths = self.exact_paths.as_mut().unwrap();
if exact_paths.get(&did).is_none() {
let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
ast::CRATE_NODE_ID,
&krate.module,
None);
- // attach the crate's exported macros to the top-level module:
+ // Attach the crate's exported macros to the top-level module:
let macro_exports: Vec<_> =
krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)).collect();
self.module.macros.extend(macro_exports);
let def_did = def.def_id();
let use_attrs = tcx.hir().attrs(id);
- // Don't inline doc(hidden) imports so they can be stripped at a later stage.
+ // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
use_attrs.lists("doc").has_word("hidden");
// For cross-crate impl inlining we need to know whether items are
- // reachable in documentation - a previously nonreachable item can be
+ // reachable in documentation -- a previously nonreachable item can be
// made reachable by cross-crate inlining which we're checking here.
- // (this is done here because we need to know this upfront)
+ // (this is done here because we need to know this upfront).
if !def_did.is_local() && !is_no_inline {
let attrs = clean::inline::load_attrs(self.cx, def_did);
let self_is_hidden = attrs.lists("doc").has_word("hidden");
let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did);
let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
- // Only inline if requested or if the item would otherwise be stripped
+ // Only inline if requested or if the item would otherwise be stripped.
if (!please_inline && !is_private && !is_hidden) || is_no_inline {
return false
}
true
}
Node::ForeignItem(it) if !glob => {
- // generate a fresh `extern {}` block if we want to inline a foreign item.
+ // Generate a fresh `extern {}` block if we want to inline a foreign item.
om.foreigns.push(hir::ForeignMod {
abi: tcx.hir().get_foreign_abi(it.id),
items: vec![hir::ForeignItem {
hir::ItemKind::Use(ref path, kind) => {
let is_glob = kind == hir::UseKind::Glob;
- // struct and variant constructors always show up alongside their definitions, we've
+ // Struct and variant constructors always show up alongside their definitions, we've
// already processed them so just discard these.
match path.def {
Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return,
}
}
- // convert each exported_macro into a doc item
+ // Convert each `exported_macro` into a doc item.
fn visit_local_macro(
&self,
def: &hir::MacroDef,
// FIXME: this may not be exhaustive, but is sufficient for rustdocs current uses
/// Similar to `librustc_privacy::EmbargoVisitor`, but also takes
-/// specific rustdoc annotations into account (i.e. `doc(hidden)`)
+/// specific rustdoc annotations into account (i.e., `doc(hidden)`)
pub struct LibEmbargoVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> {
cx: &'a ::core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
// Accessibility levels for reachable nodes
}
/// Visits the values representing the difference,
- /// i.e. the values that are in `self` but not in `other`.
+ /// i.e., the values that are in `self` but not in `other`.
///
/// # Examples
///
}
/// Visits the values representing the symmetric difference,
- /// i.e. the values that are in `self` or in `other` but not in both.
+ /// i.e., the values that are in `self` or in `other` but not in both.
///
/// # Examples
///
}
/// Visits the values representing the intersection,
- /// i.e. the values that are both in `self` and `other`.
+ /// i.e., the values that are both in `self` and `other`.
///
/// # Examples
///
}
/// Visits the values representing the union,
- /// i.e. all the values in `self` or `other`, without duplicates.
+ /// i.e., all the values in `self` or `other`, without duplicates.
///
/// # Examples
///
}
/// Returns `true` if the set is a subset of another,
- /// i.e. `other` contains at least all the values in `self`.
+ /// i.e., `other` contains at least all the values in `self`.
///
/// # Examples
///
}
/// Returns `true` if the set is a superset of another,
- /// i.e. `self` contains at least all the values in `other`.
+ /// i.e., `self` contains at least all the values in `other`.
///
/// # Examples
///
use string;
/// `Error` is a trait representing the basic expectations for error values,
-/// i.e. values of type `E` in [`Result<T, E>`]. Errors must describe
+/// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
/// themselves through the [`Display`] and [`Debug`] traits, and may provide
/// cause chain information:
///
/// The [`cause`] method is generally used when errors cross "abstraction
-/// boundaries", i.e. when a one module must report an error that is "caused"
+/// boundaries", i.e., when a one module must report an error that is "caused"
/// by an error from a lower-level module. This setup makes it possible for the
/// high-level module to provide its own errors that do not commit to any
/// particular implementation, but also reveal some of its implementation for
}
// Solaris/Illumos requires a wrapper around log, log2, and log10 functions
- // because of their non-standard behavior (e.g. log(-n) returns -Inf instead
+ // because of their non-standard behavior (e.g., log(-n) returns -Inf instead
// of expected NaN).
fn log_wrapper<F: Fn(f64) -> f64>(self, log_fn: F) -> f64 {
if !cfg!(target_os = "solaris") {
/// # Safety
///
/// This should only ever be called with a pointer that was earlier
- /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g. trying to take
+ /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
/// ownership of a string that was allocated by foreign code) is likely to lead
/// to undefined behavior or allocator corruption.
///
/// ```
#[stable(feature = "cstr_to_str", since = "1.4.0")]
pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
- // NB: When CStr is changed to perform the length check in .to_bytes()
- // instead of in from_ptr(), it may be worth considering if this should
+ // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
+ // instead of in `from_ptr()`, it may be worth considering if this should
// be rewritten to do the UTF-8 check inline with the length calculation
// instead of doing it afterwards.
str::from_utf8(self.to_bytes())
//! Rust represents owned strings with the [`String`] type, and
//! borrowed slices of strings with the [`str`] primitive. Both are
//! always in UTF-8 encoding, and may contain nul bytes in the middle,
-//! i.e. if you look at the bytes that make up the string, there may
+//! i.e., if you look at the bytes that make up the string, there may
//! be a `\0` among them. Both `String` and `str` store their length
//! explicitly; there are no nul terminators at the end of strings
//! like in C.
//! code point]'.
//!
//! * **Nul terminators and implicit string lengths** - Often, C
-//! strings are nul-terminated, i.e. they have a `\0` character at the
+//! strings are nul-terminated, i.e., they have a `\0` character at the
//! end. The length of a string buffer is not stored, but has to be
//! calculated; to compute the length of a string, C code must
//! manually call a function like `strlen()` for `char`-based strings,
/// and platform-native string values, and in particular allowing a Rust string
/// to be converted into an "OS" string with no cost if possible. A consequence
/// of this is that `OsString` instances are *not* `NUL` terminated; in order
-/// to pass to e.g. Unix system call, you should create a [`CStr`].
+/// to pass to e.g., Unix system call, you should create a [`CStr`].
///
/// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former
/// in each pair are owned strings; the latter are borrowed
/// Removes a file from the filesystem.
///
/// Note that there is no
-/// guarantee that the file is immediately deleted (e.g. depending on
+/// guarantee that the file is immediately deleted (e.g., depending on
/// platform, other open file descriptors may prevent immediate removal).
///
/// # Platform-specific behavior
impl<T> Cursor<T> {
/// Creates a new cursor wrapping the provided underlying in-memory buffer.
///
- /// Cursor initial position is `0` even if underlying buffer (e.g. `Vec`)
+ /// Cursor initial position is `0` even if underlying buffer (e.g., `Vec`)
/// is not empty. So writing to cursor starts with overwriting `Vec`
/// content, not with appending to it.
///
///
/// Each handle is a shared reference to a global buffer of input data to this
/// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
-/// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect
+/// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
/// to other reads.
///
/// This handle implements the `Read` trait, but beware that concurrent reads
///
/// You can run the example one of two ways:
///
- /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
+ /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
/// - Give it text interactively by running the executable directly,
/// in which case it will wait for the Enter key to be pressed before
/// continuing
/// For external connections in Rust code.
///
/// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
-/// keyword to make your Rust code aware of other Rust crates in your project, i.e. `extern crate
+/// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
/// lazy_static;`. The other use is in foreign function interfaces (FFI).
///
/// `extern` is used in two different contexts within FFI. The first is in the form of external
/// the other: for simple uses a string like `"localhost:12345"` is much nicer
/// than manual construction of the corresponding [`SocketAddr`], but sometimes
/// [`SocketAddr`] value is *the* main source of the address, and converting it to
-/// some other type (e.g. a string) just for it to be converted back to
+/// some other type (e.g., a string) just for it to be converted back to
/// [`SocketAddr`] in constructor methods is pointless.
///
/// Addresses returned by the operating system that are not IP addresses are
/// Moves this TCP stream into or out of nonblocking mode.
///
/// This will result in `read`, `write`, `recv` and `send` operations
- /// becoming nonblocking, i.e. immediately returning from their calls.
+ /// becoming nonblocking, i.e., immediately returning from their calls.
/// If the IO operation is successful, `Ok` is returned and no further
/// action is required. If the IO operation could not be completed and needs
/// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
/// Moves this TCP stream into or out of nonblocking mode.
///
/// This will result in the `accept` operation becoming nonblocking,
- /// i.e. immediately returning from their calls. If the IO operation is
+ /// i.e., immediately returning from their calls. If the IO operation is
/// successful, `Ok` is returned and no further action is required. If the
/// IO operation could not be completed and needs to be retried, an error
/// with kind [`io::ErrorKind::WouldBlock`] is returned.
/// Moves this UDP socket into or out of nonblocking mode.
///
/// This will result in `recv`, `recv_from`, `send`, and `send_to`
- /// operations becoming nonblocking, i.e. immediately returning from their
+ /// operations becoming nonblocking, i.e., immediately returning from their
/// calls. If the IO operation is successful, `Ok` is returned and no
/// further action is required. If the IO operation could not be completed
/// and needs to be retried, an error with kind
/// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
/// witnessing a broken invariant through the use of `catch_unwind` (catching a
/// panic). This trait is an auto trait, so it is automatically implemented for
-/// many types, and it is also structurally composed (e.g. a struct is unwind
+/// many types, and it is also structurally composed (e.g., a struct is unwind
/// safe if all of its components are unwind safe).
///
/// Note, however, that this is not an unsafe trait, so there is not a succinct
let panics = update_panic_count(1);
- // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
+ // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
// the panic hook probably triggered the last panic, otherwise the
// double-panic check would have aborted the process. In this case abort the
// process real quickly as we don't want to try calling it again as it'll
// Windows Prefixes
////////////////////////////////////////////////////////////////////////////////
-/// Windows path prefixes, e.g. `C:` or `\\server\share`.
+/// Windows path prefixes, e.g., `C:` or `\\server\share`.
///
/// Windows uses a variety of path prefix styles, including references to drive
/// volumes (like `C:`), network shared folders (like `\\server\share`), and
-/// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
+/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
/// no normalization is performed.
///
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Prefix<'a> {
- /// Verbatim prefix, e.g. `\\?\cat_pics`.
+ /// Verbatim prefix, e.g., `\\?\cat_pics`.
///
/// Verbatim prefixes consist of `\\?\` immediately followed by the given
/// component.
Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
/// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
- /// e.g. `\\?\UNC\server\share`.
+ /// e.g., `\\?\UNC\server\share`.
///
/// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
/// server's hostname and a share name.
#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
),
- /// Verbatim disk prefix, e.g. `\\?\C:\`.
+ /// Verbatim disk prefix, e.g., `\\?\C:\`.
///
/// Verbatim disk prefixes consist of `\\?\` immediately followed by the
/// drive letter and `:\`.
#[stable(feature = "rust1", since = "1.0.0")]
VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
- /// Device namespace prefix, e.g. `\\.\COM42`.
+ /// Device namespace prefix, e.g., `\\.\COM42`.
///
/// Device namespace prefixes consist of `\\.\` immediately followed by the
/// device name.
}
- /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
+ /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
///
/// # Examples
///
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Component<'a> {
- /// A Windows path prefix, e.g. `C:` or `\\server\share`.
+ /// A Windows path prefix, e.g., `C:` or `\\server\share`.
///
/// There is a large variety of prefix types, see [`Prefix`]'s documentation
/// for more.
#[stable(feature = "rust1", since = "1.0.0")]
RootDir,
- /// A reference to the current directory, i.e. `.`.
+ /// A reference to the current directory, i.e., `.`.
#[stable(feature = "rust1", since = "1.0.0")]
CurDir,
- /// A reference to the parent directory, i.e. `..`.
+ /// A reference to the parent directory, i.e., `..`.
#[stable(feature = "rust1", since = "1.0.0")]
ParentDir,
- /// A normal component, e.g. `a` and `b` in `a/b`.
+ /// A normal component, e.g., `a` and `b` in `a/b`.
///
/// This variant is the most common one, it represents references to files
/// or directories.
// true if path *physically* has a root separator; for most Windows
// prefixes, it may have a "logical" rootseparator for the purposes of
- // normalization, e.g. \\server\share == \\server\share\.
+ // normalization, e.g., \\server\share == \\server\share\.
has_physical_root: bool,
// The iterator is double-ended, and these two states keep track of what has
(comp.len() + extra, self.parse_single_component(comp))
}
- // trim away repeated separators (i.e. empty components) on the left
+ // trim away repeated separators (i.e., empty components) on the left
fn trim_left(&mut self) {
while !self.path.is_empty() {
let (size, comp) = self.parse_next_component();
}
}
- // trim away repeated separators (i.e. empty components) on the right
+ // trim away repeated separators (i.e., empty components) on the right
fn trim_right(&mut self) {
while self.path.len() > self.len_before_body() {
let (size, comp) = self.parse_next_component_back();
///
/// On Windows:
///
- /// * if `path` has a root but no prefix (e.g. `\windows`), it
+ /// * if `path` has a root but no prefix (e.g., `\windows`), it
/// replaces everything except for the prefix (if any) of `self`.
/// * if `path` has a prefix but no root, it replaces `self`.
///
if path.is_absolute() || path.prefix().is_some() {
self.as_mut_vec().truncate(0);
- // `path` has a root but no prefix, e.g. `\windows` (Windows only)
+ // `path` has a root but no prefix, e.g., `\windows` (Windows only)
} else if path.has_root() {
let prefix_len = self.components().prefix_remaining();
self.as_mut_vec().truncate(prefix_len);
PathBuf::from(self.inner.to_os_string())
}
- /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
+ /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
/// the current directory.
///
/// * On Unix, a path is absolute if it starts with the root, so
}
}
- /// Returns `true` if the `Path` is relative, i.e. not absolute.
+ /// Returns `true` if the `Path` is relative, i.e., not absolute.
///
/// See [`is_absolute`]'s documentation for more details.
///
/// * On Unix, a path has a root if it begins with `/`.
///
/// * On Windows, a path has a root if it:
- /// * has no prefix and begins with a separator, e.g. `\windows`
- /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
- /// * has any non-disk prefix, e.g. `\\server\share`
+ /// * has no prefix and begins with a separator, e.g., `\windows`
+ /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
+ /// * has any non-disk prefix, e.g., `\\server\share`
///
/// # Examples
///
///
/// # Errors
///
- /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
+ /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
/// returns `false`), returns [`Err`].
///
/// [`starts_with`]: #method.starts_with
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
- /// If you cannot access the directory containing the file, e.g. because of a
+ /// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
- /// If you cannot access the directory containing the file, e.g. because of a
+ /// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
- /// If you cannot access the directory containing the file, e.g. because of a
+ /// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// There are two syntactic forms for creating an array:
///
-/// * A list with each element, i.e. `[x, y, z]`.
+/// * A list with each element, i.e., `[x, y, z]`.
/// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
/// The type of `x` must be [`Copy`][copy].
///
///
/// # Platform-specific behavior
///
- /// If the program path is relative (e.g. `"./script.sh"`), it's ambiguous
+ /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
//!
//! - A **single processor** executing instructions [out-of-order]:
//! Modern CPUs are capable of [superscalar] execution,
-//! i.e. multiple instructions might be executing at the same time,
+//! i.e., multiple instructions might be executing at the same time,
//! even though the machine code describes a sequential process.
//!
//! This kind of reordering is handled transparently by the CPU.
}
}
- // NB: Channel could be disconnected while waiting, so the order of
+ // N.B., channel could be disconnected while waiting, so the order of
// these conditionals is important.
if guard.disconnected && guard.buf.size() == 0 {
return Err(Disconnected);
/// static INIT: Once = Once::new();
///
/// // Accessing a `static mut` is unsafe much of the time, but if we do so
- /// // in a synchronized fashion (e.g. write once or read all) then we're
+ /// // in a synchronized fashion (e.g., write once or read all) then we're
/// // good to go!
/// //
/// // This function will only call `expensive_computation` once, and will
/// Performs the same function as [`call_once`] except ignores poisoning.
///
- /// Unlike [`call_once`], if this `Once` has been poisoned (i.e. a previous
+ /// Unlike [`call_once`], if this `Once` has been poisoned (i.e., a previous
/// call to `call_once` or `call_once_force` caused a panic), calling
/// `call_once_force` will still invoke the closure `f` and will _not_
/// result in an immediate panic. If `f` panics, the `Once` will remain
//! always work with the most recent version of Android, but we also want to
//! work with older versions of Android for whenever projects need to.
//!
-//! Our current minimum supported Android version is `android-9`, e.g. Android
+//! Our current minimum supported Android version is `android-9`, e.g., Android
//! with API level 9. We then in theory want to work on that and all future
//! versions of Android!
//!
if len == 0 {
// When there is a datagram from unnamed unix socket
// linux returns zero bytes of address
- len = sun_path_offset() as libc::socklen_t; // i.e. zero-length address
+ len = sun_path_offset() as libc::socklen_t; // i.e., zero-length address
} else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"file descriptor did not correspond to a Unix socket"));
pub type wrlen_t = size_t;
// See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
-// Linux currently (e.g. support doesn't exist on other platforms). In order to
+// Linux currently (e.g., support doesn't exist on other platforms). In order to
// get name resolution to work and things to compile we just define a dummy
// SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
// actually ever used (the blocks below are wrapped in `if cfg!` as well.
// and has a closed remote end will return ERR_REMOTE_CLOSED.
#[allow(unused)] pub const ERR_SHOULD_WAIT: zx_status_t = -22;
-// ERR_CANCELED: The in-progress operation (e.g. a wait) has been
+// ERR_CANCELED: The in-progress operation (e.g., a wait) has been
// // canceled.
#[allow(unused)] pub const ERR_CANCELED: zx_status_t = -23;
/// [`OsStr`]: ../../../../std/ffi/struct.OsStr.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait OsStrExt {
- /// Re-encodes an `OsStr` as a wide character sequence, i.e. potentially
+ /// Re-encodes an `OsStr` as a wide character sequence, i.e., potentially
/// ill-formed UTF-16.
///
/// This is lossless: calling [`OsString::from_wide`] and then
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- // FIXME(#24570): add more info here (e.g. mode)
+ // FIXME(#24570): add more info here (e.g., mode)
let mut b = f.debug_struct("File");
b.field("handle", &self.handle.raw());
if let Ok(path) = get_path(&self) {
buf.len() as c::DWORD,
ptr::null()) as usize;
if res == 0 {
- // Sometimes FormatMessageW can fail e.g. system doesn't like langId,
+ // Sometimes FormatMessageW can fail e.g., system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})",
errnum, fm_err);
0,
ptr::null_mut());
- // We pass the FILE_FLAG_FIRST_PIPE_INSTANCE flag above, and we're
+ // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're
// also just doing a best effort at selecting a unique name. If
- // ERROR_ACCESS_DENIED is returned then it could mean that we
+ // `ERROR_ACCESS_DENIED` is returned then it could mean that we
// accidentally conflicted with an already existing pipe, so we try
// again.
//
// Don't try again too much though as this could also perhaps be a
// legit error.
- // If ERROR_INVALID_PARAMETER is returned, this probably means we're
- // running on pre-Vista version where PIPE_REJECT_REMOTE_CLIENTS is
+ // If `ERROR_INVALID_PARAMETER` is returned, this probably means we're
+ // running on pre-Vista version where `PIPE_REJECT_REMOTE_CLIENTS` is
// not supported, so we continue retrying without it. This implies
// reduced security on Windows versions older than Vista by allowing
// connections to this pipe from remote machines.
// Proper fix would increase the number of FFI imports and introduce
// significant amount of Windows XP specific code with no clean
// testing strategy
- // for more info see https://github.com/rust-lang/rust/pull/37677
+ // For more info, see https://github.com/rust-lang/rust/pull/37677.
if handle == c::INVALID_HANDLE_VALUE {
let err = io::Error::last_os_error();
let raw_os_err = err.raw_os_error();
where F: FnMut(&[u8], u32) -> io::Result<()>
{
// pcinfo may return an arbitrary number of file:line pairs,
- // in the order of stack trace (i.e. inlined calls first).
+ // in the order of stack trace (i.e., inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), !0); FILELINE_SIZE];
// ptr::write(ptr, Some(value))
//
// Due to this pattern it's possible for the destructor of the value in
- // `ptr` (e.g. if this is being recursively initialized) to re-access
+ // `ptr` (e.g., if this is being recursively initialized) to re-access
// TLS, in which case there will be a `&` and `&mut` pointer to the same
// value (an aliasing violation). To avoid setting the "I'm running a
// destructor" flag we just use `mem::replace` which should sequence the
//! Threads are represented via the [`Thread`] type, which you can get in one of
//! two ways:
//!
-//! * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
+//! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
//! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
//! * By requesting the current thread, using the [`thread::current`] function.
//!
//! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
//!
//! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
-//! * The thread name is provided to the OS where applicable (e.g. `pthread_setname_np` in
+//! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
//! unix-like platforms).
//!
//! ## Stack size
///
/// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
/// data is dropped
- /// - use only types with `'static` lifetime bounds, i.e. those with no or only
+ /// - use only types with `'static` lifetime bounds, i.e., those with no or only
/// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
/// and [`thread::spawn`][`spawn`] enforce this property statically)
///
/// already poison themselves when a thread panics while holding the lock.
///
/// This can also be used in multithreaded applications, in order to send a
-/// message to other threads warning that a thread has panicked (e.g. for
+/// message to other threads warning that a thread has panicked (e.g., for
/// monitoring purposes).
///
/// # Examples
/// Threads are represented via the `Thread` type, which you can get in one of
/// two ways:
///
-/// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
+/// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
/// function, and calling [`thread`][`JoinHandle::thread`] on the
/// [`JoinHandle`].
/// * By requesting the current thread, using the [`thread::current`] function.
/// Returns the amount of time elapsed since this system time was created.
///
/// This function may fail as the underlying system clock is susceptible to
- /// drift and updates (e.g. the system clock could go backwards), so this
+ /// drift and updates (e.g., the system clock could go backwards), so this
/// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
/// returned where the duration represents the amount of time elapsed from
/// this time measurement to the current time.
/// It's represented as a sequence of identifiers,
/// along with a bunch of supporting information.
///
-/// E.g. `std::cmp::PartialEq`
+/// E.g., `std::cmp::PartialEq`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Path {
pub span: Span,
}
impl Path {
- // convert a span and an identifier to the corresponding
- // 1-segment path
+ // Convert a span and an identifier to the corresponding
+ // one-segment path.
pub fn from_ident(ident: Ident) -> Path {
Path {
segments: vec![PathSegment::from_ident(ident)],
/// A segment of a path: an identifier, an optional lifetime, and a set of types.
///
-/// E.g. `std`, `String` or `Box<T>`
+/// E.g., `std`, `String` or `Box<T>`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct PathSegment {
/// The identifier portion of this path segment.
/// Arguments of a path segment.
///
-/// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
+/// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericArgs {
/// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericParamKind {
- /// A lifetime definition, e.g. `'a: 'b+'c+'d`.
+ /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
Lifetime,
Type {
default: Option<P<Ty>>,
/// A single predicate in a `where` clause
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum WherePredicate {
- /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
+ /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
BoundPredicate(WhereBoundPredicate),
- /// A lifetime predicate, e.g. `'a: 'b+'c`
+ /// A lifetime predicate (e.g., `'a: 'b + 'c`).
RegionPredicate(WhereRegionPredicate),
- /// An equality predicate (unsupported)
+ /// An equality predicate (unsupported).
EqPredicate(WhereEqPredicate),
}
/// A type bound.
///
-/// E.g. `for<'c> Foo: Send+Clone+'c`
+/// E.g., `for<'c> Foo: Send + Clone + 'c`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereBoundPredicate {
pub span: Span,
/// A lifetime predicate.
///
-/// E.g. `'a: 'b+'c`
+/// E.g., `'a: 'b + 'c`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereRegionPredicate {
pub span: Span,
/// An equality predicate (unsupported).
///
-/// E.g. `T=int`
+/// E.g., `T = int`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub rhs_ty: P<Ty>,
}
-/// The set of MetaItems that define the compilation environment of the crate,
-/// used to drive conditional compilation
+/// The set of `MetaItem`s that define the compilation environment of the crate,
+/// used to drive conditional compilation.
pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
/// Possible values inside of compile-time attribute lists.
///
-/// E.g. the '..' in `#[name(..)]`.
+/// E.g., the '..' in `#[name(..)]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum NestedMetaItemKind {
/// A full MetaItem, for recursive meta items.
MetaItem(MetaItem),
/// A literal.
///
- /// E.g. "foo", 64, true
+ /// E.g., `"foo"`, `64`, `true`.
Literal(Lit),
}
/// A spanned compile-time attribute item.
///
-/// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`
+/// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MetaItem {
pub ident: Path,
/// A compile-time attribute item.
///
-/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
+/// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum MetaItemKind {
/// Word meta item.
///
- /// E.g. `test` as in `#[test]`
+ /// E.g., `test` as in `#[test]`.
Word,
/// List meta item.
///
- /// E.g. `derive(..)` as in `#[derive(..)]`
+ /// E.g., `derive(..)` as in `#[derive(..)]`.
List(Vec<NestedMetaItem>),
/// Name value meta item.
///
- /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
+ /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
NameValue(Lit),
}
/// A Block (`{ .. }`).
///
-/// E.g. `{ .. }` as in `fn foo() { .. }`
+/// E.g., `{ .. }` as in `fn foo() { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Block {
/// Statements in a block
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum PatKind {
- /// Represents a wildcard pattern (`_`)
+ /// Represents a wildcard pattern (`_`).
Wild,
/// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
/// during name resolution.
Ident(BindingMode, Ident, Option<P<Pat>>),
- /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
+ /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
/// The `bool` is `true` in the presence of a `..`.
Struct(Path, Vec<Spanned<FieldPat>>, bool),
- /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
+ /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
/// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
- /// 0 <= position <= subpats.len()
+ /// `0 <= position <= subpats.len()`.
TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
/// A possibly qualified path pattern.
/// only legally refer to associated constants.
Path(Option<QSelf>, Path),
- /// A tuple pattern `(a, b)`.
+ /// A tuple pattern (`(a, b)`).
/// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
- /// 0 <= position <= subpats.len()
+ /// `0 <= position <= subpats.len()`.
Tuple(Vec<P<Pat>>, Option<usize>),
- /// A `box` pattern
+ /// A `box` pattern.
Box(P<Pat>),
- /// A reference pattern, e.g. `&mut (a, b)`
+ /// A reference pattern (e.g., `&mut (a, b)`).
Ref(P<Pat>, Mutability),
- /// A literal
+ /// A literal.
Lit(P<Expr>),
- /// A range pattern, e.g. `1...2`, `1..=2` or `1..2`
+ /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
/// `[a, b, ..i, y, z]` is represented as:
/// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
- /// Parentheses in patterns used for grouping, i.e. `(PAT)`.
+ /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
Paren(P<Pat>),
- /// A macro pattern; pre-expansion
+ /// A macro pattern; pre-expansion.
Mac(Mac),
}
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum MacStmtStyle {
- /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
- /// `foo!(...);`, `foo![...];`
+ /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
+ /// `foo!(...);`, `foo![...];`).
Semicolon,
- /// The macro statement had braces; e.g. foo! { ... }
+ /// The macro statement had braces (e.g., `foo! { ... }`).
Braces,
- /// The macro statement had parentheses or brackets and no semicolon; e.g.
- /// `foo!(...)`. All of these will end up being converted into macro
+ /// The macro statement had parentheses or brackets and no semicolon (e.g.,
+ /// `foo!(...)`). All of these will end up being converted into macro
/// expressions.
NoBraces,
}
-/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
+/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Local {
pub pat: P<Pat>,
pub ty: Option<P<Ty>>,
- /// Initializer expression to set the value, if any
+ /// Initializer expression to set the value, if any.
pub init: Option<P<Expr>>,
pub id: NodeId,
pub span: Span,
/// An arm of a 'match'.
///
-/// E.g. `0..=10 => { println!("match!") }` as in
+/// E.g., `0..=10 => { println!("match!") }` as in
///
/// ```
/// match 123 {
/// A constant (expression) that's not an item or associated item,
/// but needs its own `DefId` for type-checking, const-eval, etc.
-/// These are usually found nested inside types (e.g. array lengths)
-/// or expressions (e.g. repeat counts), and also used to define
+/// These are usually found nested inside types (e.g., array lengths)
+/// or expressions (e.g., repeat counts), and also used to define
/// explicit discriminant values for enum variants.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct AnonConst {
static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 88);
impl Expr {
- /// Whether this expression would be valid somewhere that expects a value, for example, an `if`
+ /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
/// condition.
pub fn returns(&self) -> bool {
if let ExprKind::Block(ref block, _) = self.node {
///
/// The `PathSegment` represents the method name and its generic arguments
/// (within the angle brackets).
- /// The first element of the vector of `Expr`s is the expression that evaluates
+ /// The first element of the vector of an `Expr` is the expression that evaluates
/// to the object on which the method is being called on (the receiver),
/// and the remaining elements are the rest of the arguments.
/// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
/// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
MethodCall(PathSegment, Vec<P<Expr>>),
- /// A tuple (`(a, b, c ,d)`)
+ /// A tuple (e.g., `(a, b, c, d)`).
Tup(Vec<P<Expr>>),
- /// A binary operation (For example: `a + b`, `a * b`)
+ /// A binary operation (e.g., `a + b`, `a * b`).
Binary(BinOp, P<Expr>, P<Expr>),
- /// A unary operation (For example: `!x`, `*x`)
+ /// A unary operation (e.g., `!x`, `*x`).
Unary(UnOp, P<Expr>),
- /// A literal (For example: `1`, `"foo"`)
+ /// A literal (e.g., `1`, `"foo"`).
Lit(Lit),
- /// A cast (`foo as f64`)
+ /// A cast (e.g., `foo as f64`).
Cast(P<Expr>, P<Ty>),
Type(P<Expr>, P<Ty>),
- /// An `if` block, with an optional else block
+ /// An `if` block, with an optional `else` block.
///
/// `if expr { block } else { expr }`
If(P<Expr>, P<Block>, Option<P<Expr>>),
///
/// `'label: while expr { block }`
While(P<Expr>, P<Block>, Option<Label>),
- /// A while-let loop, with an optional label
+ /// A `while let` loop, with an optional label.
///
/// `'label: while let pat = expr { block }`
///
/// This is desugared to a combination of `loop` and `match` expressions.
WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
- /// A for loop, with an optional label
+ /// A `for` loop, with an optional label.
///
/// `'label: for pat in expr { block }`
///
/// This is desugared to a combination of `loop` and `match` expressions.
ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
- /// Conditionless loop (can be exited with break, continue, or return)
+ /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
///
/// `'label: loop { block }`
Loop(P<Block>, Option<Label>),
/// A `match` block.
Match(P<Expr>, Vec<Arm>),
- /// A closure (for example, `move |a, b, c| a + b + c`)
+ /// A closure (e.g., `move |a, b, c| a + b + c`).
///
- /// The final span is the span of the argument block `|...|`
+ /// The final span is the span of the argument block `|...|`.
Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
- /// A block (`'label: { ... }`)
+ /// A block (`'label: { ... }`).
Block(P<Block>, Option<Label>),
- /// An async block (`async move { ... }`)
+ /// An async block (`async move { ... }`).
///
/// The `NodeId` is the `NodeId` for the closure that results from
/// desugaring an async block, just like the NodeId field in the
/// created during lowering cannot be made the parent of any other
/// preexisting defs.
Async(CaptureBy, NodeId, P<Block>),
- /// A try block (`try { ... }`)
+ /// A try block (`try { ... }`).
TryBlock(P<Block>),
- /// An assignment (`a = foo()`)
+ /// An assignment (`a = foo()`).
Assign(P<Expr>, P<Expr>),
- /// An assignment with an operator
+ /// An assignment with an operator.
///
- /// For example, `a += 1`.
+ /// E.g., `a += 1`.
AssignOp(BinOp, P<Expr>, P<Expr>),
- /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct field
+ /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
Field(P<Expr>, Ident),
- /// An indexing operation (`foo[2]`)
+ /// An indexing operation (e.g., `foo[2]`).
Index(P<Expr>, P<Expr>),
- /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
+ /// A range (e.g., `1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`).
Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
/// Variable reference, possibly containing `::` and/or type
- /// parameters, e.g. foo::bar::<baz>.
+ /// parameters (e.g., `foo::bar::<baz>`).
///
- /// Optionally "qualified",
- /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
+ /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
Path(Option<QSelf>, Path),
- /// A referencing operation (`&a` or `&mut a`)
+ /// A referencing operation (`&a` or `&mut a`).
AddrOf(Mutability, P<Expr>),
- /// A `break`, with an optional label to break, and an optional expression
+ /// A `break`, with an optional label to break, and an optional expression.
Break(Option<Label>, Option<P<Expr>>),
- /// A `continue`, with an optional label
+ /// A `continue`, with an optional label.
Continue(Option<Label>),
- /// A `return`, with an optional value to be returned
+ /// A `return`, with an optional value to be returned.
Ret(Option<P<Expr>>),
- /// Output of the `asm!()` macro
+ /// Output of the `asm!()` macro.
InlineAsm(P<InlineAsm>),
- /// A macro invocation; pre-expansion
+ /// A macro invocation; pre-expansion.
Mac(Mac),
/// A struct literal expression.
///
- /// For example, `Foo {x: 1, y: 2}`, or
- /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
+ /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
+ /// where `base` is the `Option<Expr>`.
Struct(Path, Vec<Field>, Option<P<Expr>>),
/// An array literal constructed from one repeated element.
///
- /// For example, `[1; 5]`. The expression is the element to be
+ /// E.g., `[1; 5]`. The expression is the element to be
/// repeated; the constant is the number of times to repeat it.
Repeat(P<Expr>, AnonConst),
- /// No-op: used solely so we can pretty-print faithfully
+ /// No-op: used solely so we can pretty-print faithfully.
Paren(P<Expr>),
- /// `expr?`
+ /// A try expression (`expr?`).
Try(P<Expr>),
- /// A `yield`, with an optional value to be yielded
+ /// A `yield`, with an optional value to be yielded.
Yield(Option<P<Expr>>),
}
-/// The explicit Self type in a "qualified path". The actual
+/// The explicit `Self` type in a "qualified path". The actual
/// path, including the trait and the associated item, is stored
/// separately. `position` represents the index of the associated
-/// item qualified with this Self type.
+/// item qualified with this `Self` type.
///
/// ```ignore (only-for-syntax-highlight)
/// <Vec<T> as a::b::Trait>::AssociatedItem
pub position: usize,
}
-/// A capture clause
+/// A capture clause.
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum CaptureBy {
Value,
Ref,
}
-/// The movability of a generator / closure literal
+/// The movability of a generator / closure literal.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum Movability {
Static,
pub type Mac = Spanned<Mac_>;
-/// Represents a macro invocation. The Path indicates which macro
+/// Represents a macro invocation. The `Path` indicates which macro
/// is being invoked, and the vector of token-trees contains the source
/// of the macro invocation.
///
-/// NB: the additional ident for a macro_rules-style macro is actually
-/// stored in the enclosing item. Oog.
+/// N.B., the additional ident for a `macro_rules`-style macro is actually
+/// stored in the enclosing item.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mac_ {
pub path: Path,
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
pub enum StrStyle {
- /// A regular string, like `"foo"`
+ /// A regular string, like `"foo"`.
Cooked,
- /// A raw string, like `r##"foo"##`
+ /// A raw string, like `r##"foo"##`.
///
/// The value is the number of `#` symbols used.
Raw(u16),
}
-/// A literal
+/// A literal.
pub type Lit = Spanned<LitKind>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
/// Literal kind.
///
-/// E.g. `"foo"`, `42`, `12.34` or `bool`
+/// E.g., `"foo"`, `42`, `12.34`, or `bool`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
pub enum LitKind {
- /// A string literal (`"foo"`)
+ /// A string literal (`"foo"`).
Str(Symbol, StrStyle),
- /// A byte string (`b"foo"`)
+ /// A byte string (`b"foo"`).
ByteStr(Lrc<Vec<u8>>),
- /// A byte char (`b'f'`)
+ /// A byte char (`b'f'`).
Byte(u8),
- /// A character literal (`'a'`)
+ /// A character literal (`'a'`).
Char(char),
- /// An integer literal (`1`)
+ /// An integer literal (`1`).
Int(u128, LitIntType),
- /// A float literal (`1f64` or `1E10f64`)
+ /// A float literal (`1f64` or `1E10f64`).
Float(Symbol, FloatTy),
- /// A float literal without a suffix (`1.0 or 1.0E10`)
+ /// A float literal without a suffix (`1.0 or 1.0E10`).
FloatUnsuffixed(Symbol),
- /// A boolean literal
+ /// A boolean literal.
Bool(bool),
}
impl LitKind {
- /// Returns true if this literal is a string and false otherwise.
+ /// Returns `true` if this literal is a string.
pub fn is_str(&self) -> bool {
match *self {
LitKind::Str(..) => true,
}
}
- /// Returns true if this literal is byte literal string false otherwise.
+ /// Returns `true` if this literal is byte literal string.
pub fn is_bytestr(&self) -> bool {
match self {
LitKind::ByteStr(_) => true,
}
}
- /// Returns true if this is a numeric literal.
+ /// Returns `true` if this is a numeric literal.
pub fn is_numeric(&self) -> bool {
match *self {
LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
}
}
- /// Returns true if this literal has no suffix. Note: this will return true
- /// for literals with prefixes such as raw strings and byte strings.
+ /// Returns `true` if this literal has no suffix.
+ /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
pub fn is_unsuffixed(&self) -> bool {
match *self {
// unsuffixed variants
}
}
- /// Returns true if this literal has a suffix.
+ /// Returns `true` if this literal has a suffix.
pub fn is_suffixed(&self) -> bool {
!self.is_unsuffixed()
}
}
-// NB: If you change this, you'll probably want to change the corresponding
-// type structure in middle/ty.rs as well.
+// N.B., If you change this, you'll probably want to change the corresponding
+// type structure in `middle/ty.rs` as well.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MutTy {
pub ty: P<Ty>,
pub generics: Generics,
pub node: TraitItemKind,
pub span: Span,
- /// See `Item::tokens` for what this is
+ /// See `Item::tokens` for what this is.
pub tokens: Option<TokenStream>,
}
pub generics: Generics,
pub node: ImplItemKind,
pub span: Span,
- /// See `Item::tokens` for what this is
+ /// See `Item::tokens` for what this is.
pub tokens: Option<TokenStream>,
}
}
pub fn val_to_string(&self, val: i128) -> String {
- // cast to a u128 so we can correctly print INT128_MIN. All integral types
- // are parsed as u128, so we wouldn't want to print an extra negative
+ // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
+ // are parsed as `u128`, so we wouldn't want to print an extra negative
// sign.
format!("{}{}", val as u128, self.ty_to_string())
}
}
}
-// Bind a type to an associated type: `A=Foo`.
+// Bind a type to an associated type: `A = Foo`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TypeBinding {
pub id: NodeId,
pub decl: P<FnDecl>,
}
-/// The different kinds of types recognized by the compiler
+/// The different kinds of types recognized by the compiler.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum TyKind {
- /// A variable-length slice (`[T]`)
+ /// A variable-length slice (`[T]`).
Slice(P<Ty>),
- /// A fixed length array (`[T; n]`)
+ /// A fixed length array (`[T; n]`).
Array(P<Ty>, AnonConst),
- /// A raw pointer (`*const T` or `*mut T`)
+ /// A raw pointer (`*const T` or `*mut T`).
Ptr(MutTy),
- /// A reference (`&'a T` or `&'a mut T`)
+ /// A reference (`&'a T` or `&'a mut T`).
Rptr(Option<Lifetime>, MutTy),
- /// A bare function (e.g. `fn(usize) -> bool`)
+ /// A bare function (e.g., `fn(usize) -> bool`).
BareFn(P<BareFnTy>),
- /// The never type (`!`)
+ /// The never type (`!`).
Never,
- /// A tuple (`(A, B, C, D,...)`)
+ /// A tuple (`(A, B, C, D,...)`).
Tup(Vec<P<Ty>>),
/// A path (`module::module::...::Type`), optionally
- /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
+ /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
///
- /// Type parameters are stored in the Path itself
+ /// Type parameters are stored in the `Path` itself.
Path(Option<QSelf>, Path),
/// A trait object type `Bound1 + Bound2 + Bound3`
/// where `Bound` is a trait or a lifetime.
///
/// The `NodeId` exists to prevent lowering from having to
/// generate `NodeId`s on the fly, which would complicate
- /// the generation of `existential type` items significantly
+ /// the generation of `existential type` items significantly.
ImplTrait(NodeId, GenericBounds),
- /// No-op; kept solely so that we can pretty-print faithfully
+ /// No-op; kept solely so that we can pretty-print faithfully.
Paren(P<Ty>),
- /// Unused for now
+ /// Unused for now.
Typeof(AnonConst),
- /// TyKind::Infer means the type should be inferred instead of it having been
+ /// This means the type should be inferred instead of it having been
/// specified. This can appear anywhere in a type.
Infer,
/// Inferred type of a `self` or `&self` argument in a method.
ImplicitSelf,
- // A macro in the type position.
+ /// A macro in the type position.
Mac(Mac),
/// Placeholder for a kind that has failed to be defined.
Err,
/// Inline assembly dialect.
///
-/// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
+/// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum AsmDialect {
Att,
/// Inline assembly.
///
-/// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`
+/// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsmOutput {
pub constraint: Symbol,
/// Inline assembly.
///
-/// E.g. `asm!("NOP");`
+/// E.g., `asm!("NOP");`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsm {
pub asm: Symbol,
/// An argument in a function header.
///
-/// E.g. `bar: usize` as in `fn foo(bar: usize)`
+/// E.g., `bar: usize` as in `fn foo(bar: usize)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Arg {
pub ty: P<Ty>,
/// Alternative representation for `Arg`s describing `self` parameter of methods.
///
-/// E.g. `&mut self` as in `fn foo(&mut self)`
+/// E.g., `&mut self` as in `fn foo(&mut self)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum SelfKind {
/// `self`, `mut self`
/// Header (not the body) of a function declaration.
///
-/// E.g. `fn foo(bar: baz)`
+/// E.g., `fn foo(bar: baz)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FnDecl {
pub inputs: Vec<Arg>,
false
}
}
- /// In case this is an `Async` return the `NodeId` for the generated impl Trait item
+
+ /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
pub fn opt_return_id(self) -> Option<NodeId> {
match self {
IsAsync::Async {
pub enum FunctionRetTy {
/// Return type is not specified.
///
- /// Functions default to `()` and
- /// closures default to inference. Span points to where return
- /// type would be inserted.
+ /// Functions default to `()` and closures default to inference.
+ /// Span points to where return type would be inserted.
Default(Span),
- /// Everything else
+ /// Everything else.
Ty(P<Ty>),
}
/// Module declaration.
///
-/// E.g. `mod foo;` or `mod foo { .. }`
+/// E.g., `mod foo;` or `mod foo { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mod {
/// A span from the first token past `{` to the last token until `}`.
/// to the last token in the external file.
pub inner: Span,
pub items: Vec<P<Item>>,
- /// For `mod foo;` inline is false, for `mod foo { .. }` it is true.
+ /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
pub inline: bool,
}
/// Foreign module declaration.
///
-/// E.g. `extern { .. }` or `extern C { .. }`
+/// E.g., `extern { .. }` or `extern C { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ForeignMod {
pub abi: Abi,
pub items: Vec<ForeignItem>,
}
-/// Global inline assembly
+/// Global inline assembly.
///
-/// aka module-level assembly or file-scoped assembly
+/// Also known as "module-level assembly" or "file-scoped assembly".
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
pub struct GlobalAsm {
pub asm: Symbol,
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub data: VariantData,
- /// Explicit discriminant, e.g. `Foo = 1`
+ /// Explicit discriminant, e.g., `Foo = 1`.
pub disr_expr: Option<AnonConst>,
}
}
}
-/// Distinguishes between Attributes that decorate items and Attributes that
+/// Distinguishes between `Attribute`s that decorate items and Attributes that
/// are contained as statements within items. These two cases need to be
/// distinguished for pretty-printing.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
}
}
-/// Meta-data associated with an item
-/// Doc-comments are promoted to attributes that have is_sugared_doc = true
+/// Metadata associated with an item.
+/// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Attribute {
pub id: AttrId,
pub span: Span,
}
-/// TraitRef's appear in impls.
+/// `TraitRef`s appear in impls.
///
-/// resolve maps each TraitRef's ref_id to its defining trait; that's all
-/// that the ref_id is for. The impl_id maps to the "self type" of this impl.
-/// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
-/// same as the impl's node id).
+/// Resolve maps each `TraitRef`'s `ref_id` to its defining trait; that's all
+/// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
+/// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
+/// same as the impl's node-id).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitRef {
pub path: Path,
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum CrateSugar {
- /// Source is `pub(crate)`
+ /// Source is `pub(crate)`.
PubCrate,
- /// Source is (just) `crate`
+ /// Source is (just) `crate`.
JustCrate,
}
/// Field of a struct.
///
-/// E.g. `bar: usize` as in `struct Foo { bar: usize }`
+/// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct StructField {
pub span: Span,
pub enum VariantData {
/// Struct variant.
///
- /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
+ /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
Struct(Vec<StructField>, NodeId),
/// Tuple variant.
///
- /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
+ /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
Tuple(Vec<StructField>, NodeId),
/// Unit variant.
///
- /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
+ /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
Unit(NodeId),
}
}
}
-/// An item
+/// An item.
///
-/// The name might be a dummy name in case of anonymous items
+/// The name might be a dummy name in case of anonymous items.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Item {
pub ident: Ident,
pub tokens: Option<TokenStream>,
}
-/// A function header
+/// A function header.
///
-/// All the information between the visibility & the name of the function is
-/// included in this struct (e.g. `async unsafe fn` or `const extern "C" fn`)
+/// All the information between the visibility and the name of the function is
+/// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
pub struct FnHeader {
pub unsafety: Unsafety,
pub enum ItemKind {
/// An `extern crate` item, with optional *original* crate name if the crate was renamed.
///
- /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
+ /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
ExternCrate(Option<Name>),
/// A use declaration (`use` or `pub use`) item.
///
- /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
+ /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
Use(P<UseTree>),
/// A static item (`static` or `pub static`).
///
- /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
+ /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
Static(P<Ty>, Mutability, P<Expr>),
/// A constant item (`const` or `pub const`).
///
- /// E.g. `const FOO: i32 = 42;`
+ /// E.g., `const FOO: i32 = 42;`.
Const(P<Ty>, P<Expr>),
/// A function declaration (`fn` or `pub fn`).
///
- /// E.g. `fn foo(bar: usize) -> usize { .. }`
+ /// E.g., `fn foo(bar: usize) -> usize { .. }`.
Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
/// A module declaration (`mod` or `pub mod`).
///
- /// E.g. `mod foo;` or `mod foo { .. }`
+ /// E.g., `mod foo;` or `mod foo { .. }`.
Mod(Mod),
/// An external module (`extern` or `pub extern`).
///
- /// E.g. `extern {}` or `extern "C" {}`
+ /// E.g., `extern {}` or `extern "C" {}`.
ForeignMod(ForeignMod),
- /// Module-level inline assembly (from `global_asm!()`)
+ /// Module-level inline assembly (from `global_asm!()`).
GlobalAsm(P<GlobalAsm>),
/// A type alias (`type` or `pub type`).
///
- /// E.g. `type Foo = Bar<u8>;`
+ /// E.g., `type Foo = Bar<u8>;`.
Ty(P<Ty>, Generics),
/// An existential type declaration (`existential type`).
///
- /// E.g. `existential type Foo: Bar + Boo;`
+ /// E.g., `existential type Foo: Bar + Boo;`.
Existential(GenericBounds, Generics),
/// An enum definition (`enum` or `pub enum`).
///
- /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
+ /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
Enum(EnumDef, Generics),
/// A struct definition (`struct` or `pub struct`).
///
- /// E.g. `struct Foo<A> { x: A }`
+ /// E.g., `struct Foo<A> { x: A }`.
Struct(VariantData, Generics),
/// A union definition (`union` or `pub union`).
///
- /// E.g. `union Foo<A, B> { x: A, y: B }`
+ /// E.g., `union Foo<A, B> { x: A, y: B }`.
Union(VariantData, Generics),
/// A Trait declaration (`trait` or `pub trait`).
///
- /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
+ /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
/// Trait alias
///
- /// E.g. `trait Foo = Bar + Quux;`
+ /// E.g., `trait Foo = Bar + Quux;`.
TraitAlias(Generics, GenericBounds),
/// An implementation.
///
- /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
+ /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
Impl(
Unsafety,
ImplPolarity,
),
/// A macro invocation.
///
- /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
+ /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
Mac(Mac),
/// A macro definition.
pub vis: Visibility,
}
-/// An item within an `extern` block
+/// An item within an `extern` block.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ForeignItemKind {
- /// A foreign function
+ /// A foreign function.
Fn(P<FnDecl>, Generics),
- /// A foreign static item (`static ext: u8`), with optional mutability
- /// (the boolean is true when mutable)
+ /// A foreign static item (`static ext: u8`), with optional mutability.
+ /// (The boolean is `true` for mutable items).
Static(P<Ty>, bool),
- /// A foreign type
+ /// A foreign type.
Ty,
- /// A macro invocation
+ /// A macro invocation.
Macro(Mac),
}
use super::*;
use serialize;
- // are ASTs encodable?
+ // Are ASTs encodable?
#[test]
fn check_asts_encodable() {
fn assert_encodable<T: serialize::Encodable>() {}
self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
}
- /// Returns the name of the meta item, e.g. `foo` in `#[foo]`,
+ /// Returns the name of the meta item, e.g., `foo` in `#[foo]`,
/// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem
pub fn name(&self) -> Option<Name> {
self.meta_item().and_then(|meta_item| Some(meta_item.name()))
}
/// Returns the **last** segment of the name of this attribute.
- /// E.g. `foo` for `#[foo]`, `skip` for `#[rustfmt::skip]`.
+ /// e.g., `foo` for `#[foo]`, `skip` for `#[rustfmt::skip]`.
pub fn name(&self) -> Name {
name_from_path(&self.path)
}
// Anything else is always required, and thus has to error out
// in case of a cfg attr.
//
- // NB: This is intentionally not part of the fold_expr() function
+ // N.B., this is intentionally not part of the fold_expr() function
// in order for fold_opt_expr() to be able to avoid this check
if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
let msg = "removing an expression is not supported in this position";
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
- // Don't configure interpolated AST (c.f. #34171).
+ // Don't configure interpolated AST (cf. issue #34171).
// Interpolated AST will get configured once the surrounding tokens are parsed.
mac
}
/// An attribute-like procedural macro that derives a builtin trait.
BuiltinDerive(BuiltinDeriveFn),
- /// A declarative macro, e.g. `macro m() {}`.
+ /// A declarative macro, e.g., `macro m() {}`.
DeclMacro {
expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
def_info: Option<(ast::NodeId, Span)>,
/// `span_err` should be strongly preferred where-ever possible:
/// this should *only* be used when:
///
- /// - continuing has a high risk of flow-on errors (e.g. errors in
+ /// - continuing has a high risk of flow-on errors (e.g., errors in
/// declaring a macro would cause all uses of that macro to
/// complain about "undefined macro"), or
/// - there is literally nothing else that can be done (however,
expr
});
- // we want to be able to handle e.g. `concat!("foo", "bar")`
+ // we want to be able to handle e.g., `concat!("foo", "bar")`
let expr = cx.expander().fold_expr(expr);
Err(match expr.node {
ast::ExprKind::Lit(ref l) => match l.node {
module.mod_path.push(item.ident);
// Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
- // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
+ // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
// Thus, if `inner` is the dummy span, we know the module is inline.
let inline_module = item.span.contains(inner) || inner.is_dummy();
up: Option<MatcherPosHandle<'root, 'tt>>,
/// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from
- /// a delimited token tree (e.g. something wrapped in `(` `)`) or to get the contents of a doc
+ /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc
/// comment...
///
- /// When matching against matchers with nested delimited submatchers (e.g. `pat ( pat ( .. )
+ /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. )
/// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does
/// that where the bottom of the stack is the outermost matcher.
/// Also, throughout the comments, this "descent" is often referred to as "unzipping"...
ms: &[TokenTree],
mut res: I,
) -> NamedParseResult {
- // Recursively descend into each type of matcher (e.g. sequences, delimited, metavars) and make
+ // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make
// sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one
// binding, then there is an error. If it does, then we insert the binding into the
// `NamedParseResult`.
///
/// - `p`: the "black-box" parser to use
/// - `sp`: the `Span` we want to parse
-/// - `name`: the name of the metavar _matcher_ we want to match (e.g. `tt`, `ident`, `block`,
+/// - `name`: the name of the metavar _matcher_ we want to match (e.g., `tt`, `ident`, `block`,
/// etc...)
///
/// # Returns
e
}));
- // We allow semicolons at the end of expressions -- e.g. the semicolon in
+ // We allow semicolons at the end of expressions -- e.g., the semicolon in
// `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
- // but `m!()` is allowed in expression positions (c.f. issue #34706).
+ // but `m!()` is allowed in expression positions (cf. issue #34706).
if kind == AstFragmentKind::Expr && parser.token == token::Semi {
parser.bump();
}
err == sess.span_diagnostic.err_count()
}
-// The FirstSets for a matcher is a mapping from subsequences in the
+// `The FirstSets` for a matcher is a mapping from subsequences in the
// matcher to the FIRST set for that subsequence.
//
// This mapping is partially precomputed via a backwards scan over the
// token trees of the matcher, which provides a mapping from each
-// repetition sequence to its FIRST set.
+// repetition sequence to its *first* set.
//
-// (Hypothetically sequences should be uniquely identifiable via their
-// spans, though perhaps that is false e.g. for macro-generated macros
+// (Hypothetically, sequences should be uniquely identifiable via their
+// spans, though perhaps that is false, e.g., for macro-generated macros
// that do not try to inject artificial span information. My plan is
// to try to catch such cases ahead of time and not include them in
// the precomputed mapping.)
Delimited(DelimSpan, Lrc<Delimited>),
/// A kleene-style repetition sequence
Sequence(DelimSpan, Lrc<SequenceRepetition>),
- /// E.g. `$var`
+ /// e.g., `$var`
MetaVar(Span, ast::Ident),
- /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros.
+ /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
MetaVarDecl(
Span,
ast::Ident, /* name to bind */
let mut trees = input.trees().peekable();
while let Some(tree) = trees.next() {
// Given the parsed tree, if there is a metavar and we are expecting matchers, actually
- // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`).
+ // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
let tree = parse_tree(
tree,
&mut trees,
// `tree` is a `$` token. Look at the next token in `trees`
tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
// `tree` is followed by a delimited set of token trees. This indicates the beginning
- // of a repetition sequence in the macro (e.g. `$(pat)*`).
+ // of a repetition sequence in the macro (e.g., `$(pat)*`).
Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
// Must have `(` not `{` or `[`
if delimited.delim != token::Paren {
edition,
macro_node_id,
);
- // Count the number of captured "names" (i.e. named metavars)
+ // Count the number of captured "names" (i.e., named metavars)
let name_captures = macro_parser::count_names(&sequence);
TokenTree::Sequence(
span,
// `tree` is an arbitrary token. Keep it.
tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
- // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to
+ // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
// descend into the delimited set and further parse it.
tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
span,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Feature gating
+//! # Feature gating
//!
//! This module implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
}
}
-// If you change this, please modify src/doc/unstable-book as well.
+// If you change this, please modify `src/doc/unstable-book` as well.
//
// Don't ever remove anything from this list; set them to 'Removed'.
//
// was set. This is most important for knowing when a particular feature became
// stable (active).
//
-// NB: tools/tidy/src/features.rs parses this information directly out of the
+// N.B., `tools/tidy/src/features.rs` parses this information directly out of the
// source, so take care when modifying it.
declare_features! (
(active, panic_runtime, "1.10.0", Some(32837), None),
(active, needs_panic_runtime, "1.10.0", Some(32837), None),
- // OIBIT specific features
+ // Features specific to OIBIT (auto traits)
(active, optin_builtin_traits, "1.0.0", Some(13231), None),
- // Allows use of #[staged_api]
+ // Allows `#[staged_api]`.
//
// rustc internal
(active, staged_api, "1.0.0", None, None),
- // Allows using #![no_core]
+ // Allows `#![no_core]`.
(active, no_core, "1.3.0", Some(29639), None),
- // Allows using `box` in patterns; RFC 469
+ // Allows the use of `box` in patterns (RFC 469).
(active, box_patterns, "1.0.0", Some(29641), None),
- // Allows using the unsafe_destructor_blind_to_params attribute;
- // RFC 1238
+ // Allows the use of the `unsafe_destructor_blind_to_params` attribute (RFC 1238).
(active, dropck_parametricity, "1.3.0", Some(28498), None),
- // Allows using the may_dangle attribute; RFC 1327
+ // Allows using the `may_dangle` attribute (RFC 1327).
(active, dropck_eyepatch, "1.10.0", Some(34761), None),
- // Allows the use of custom attributes; RFC 572
+ // Allows the use of custom attributes (RFC 572).
(active, custom_attribute, "1.0.0", Some(29642), None),
- // Allows the use of rustc_* attributes; RFC 572
+ // Allows the use of `rustc_*` attributes (RFC 572).
(active, rustc_attrs, "1.0.0", Some(29642), None),
- // Allows the use of non lexical lifetimes; RFC 2094
+ // Allows the use of non lexical lifetimes (RFC 2094).
(active, nll, "1.0.0", Some(43234), None),
- // Allows the use of #[allow_internal_unstable]. This is an
- // attribute on macro_rules! and can't use the attribute handling
+ // Allows the use of `#[allow_internal_unstable]`. This is an
+ // attribute on `macro_rules!` and can't use the attribute handling
// below (it has to be checked before expansion possibly makes
// macros disappear).
//
// rustc internal
(active, allow_internal_unstable, "1.0.0", None, None),
- // Allows the use of #[allow_internal_unsafe]. This is an
- // attribute on macro_rules! and can't use the attribute handling
+ // Allows the use of `#[allow_internal_unsafe]`. This is an
+ // attribute on `macro_rules!` and can't use the attribute handling
// below (it has to be checked before expansion possibly makes
// macros disappear).
//
// rustc internal
(active, allow_internal_unsafe, "1.0.0", None, None),
- // #23121. Array patterns have some hazards yet.
+ // Allows the use of slice patterns (RFC 23121).
(active, slice_patterns, "1.0.0", Some(23121), None),
- // Allows the definition of `const fn` functions with some advanced features.
+ // Allows the definition of `const` functions with some advanced features.
(active, const_fn, "1.2.0", Some(24111), None),
- // Allows let bindings and destructuring in `const fn` functions and constants.
+ // Allows let bindings and destructuring in `const` functions and constants.
(active, const_let, "1.22.1", Some(48821), None),
- // Allows accessing fields of unions inside const fn.
+ // Allows accessing fields of unions inside `const` functions.
(active, const_fn_union, "1.27.0", Some(51909), None),
// Allows casting raw pointers to `usize` during const eval.
// Allows comparing raw pointers during const eval.
(active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
- // Allows panicking during const eval (produces compile-time errors)
+ // Allows panicking during const eval (producing compile-time errors).
(active, const_panic, "1.30.0", Some(51999), None),
- // Allows using #[prelude_import] on glob `use` items.
+ // Allows using `#[prelude_import]` on glob `use` items.
//
// rustc internal
(active, prelude_import, "1.2.0", None, None),
// Allows default type parameters to influence type inference.
(active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
- // Allows associated type defaults
+ // Allows associated type defaults.
(active, associated_type_defaults, "1.2.0", Some(29661), None),
- // Allows `repr(simd)`, and importing the various simd intrinsics
+ // Allows `repr(simd)` and importing the various simd intrinsics.
(active, repr_simd, "1.4.0", Some(27731), None),
- // Allows `extern "platform-intrinsic" { ... }`
+ // Allows `extern "platform-intrinsic" { ... }`.
(active, platform_intrinsics, "1.4.0", Some(27731), None),
- // Allows `#[unwind(..)]`
+ // Allows `#[unwind(..)]`.
+ //
// rustc internal for rust runtime
(active, unwind_attributes, "1.4.0", None, None),
// Allows the use of `#[naked]` on functions.
(active, naked_functions, "1.9.0", Some(32408), None),
- // Allows `#[no_debug]`
+ // Allows `#[no_debug]`.
(active, no_debug, "1.5.0", Some(29721), None),
- // Allows `#[omit_gdb_pretty_printer_section]`
+ // Allows `#[omit_gdb_pretty_printer_section]`.
//
// rustc internal
(active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
- // Allows cfg(target_vendor = "...").
+ // Allows `cfg(target_vendor = "...")`.
(active, cfg_target_vendor, "1.5.0", Some(29718), None),
- // Allow attributes on expressions and non-item statements
+ // Allows attributes on expressions and non-item statements.
(active, stmt_expr_attributes, "1.6.0", Some(15701), None),
- // allow using type ascription in expressions
+ // Allows the use of type ascription in expressions.
(active, type_ascription, "1.6.0", Some(23416), None),
- // Allows cfg(target_thread_local)
+ // Allows `cfg(target_thread_local)`.
(active, cfg_target_thread_local, "1.7.0", Some(29594), None),
// rustc internal
(active, abi_vectorcall, "1.7.0", None, None),
- // X..Y patterns
+ // Allows `X..Y` patterns.
(active, exclusive_range_pattern, "1.11.0", Some(37854), None),
// impl specialization (RFC 1210)
(active, specialization, "1.7.0", Some(31844), None),
- // Allows cfg(target_has_atomic = "...").
+ // Allows `cfg(target_has_atomic = "...")`.
(active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
- // The `!` type. Does not imply exhaustive_patterns (below) any more.
+ // The `!` type. Does not imply 'exhaustive_patterns' (below) any more.
(active, never_type, "1.13.0", Some(35121), None),
- // Allows exhaustive pattern matching on types that contain uninhabited types
+ // Allows exhaustive pattern matching on types that contain uninhabited types.
(active, exhaustive_patterns, "1.13.0", Some(51085), None),
- // Allows untagged unions `union U { ... }`
+ // Allows untagged unions `union U { ... }`.
(active, untagged_unions, "1.13.0", Some(32836), None),
- // Used to identify the `compiler_builtins` crate
- // rustc internal
+ // Used to identify the `compiler_builtins` crate.
+ //
+ // rustc internal.
(active, compiler_builtins, "1.13.0", None, None),
- // Allows #[link(..., cfg(..))]
+ // Allows `#[link(..., cfg(..))]`.
(active, link_cfg, "1.14.0", Some(37406), None),
- // `extern "ptx-*" fn()`
+ // Allows `extern "ptx-*" fn()`.
(active, abi_ptx, "1.15.0", Some(38788), None),
- // The `repr(i128)` annotation for enums
+ // The `repr(i128)` annotation for enums.
(active, repr128, "1.16.0", Some(35118), None),
- // The `unadjusted` ABI. Perma unstable.
+ // The `unadjusted` ABI; perma-unstable.
+ //
// rustc internal
(active, abi_unadjusted, "1.16.0", None, None),
// Declarative macros 2.0 (`macro`).
(active, decl_macro, "1.17.0", Some(39412), None),
- // Allows #[link(kind="static-nobundle"...)]
+ // Allows `#[link(kind="static-nobundle"...)]`.
(active, static_nobundle, "1.16.0", Some(37403), None),
- // `extern "msp430-interrupt" fn()`
+ // Allows `extern "msp430-interrupt" fn()`.
(active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
- // Used to identify crates that contain sanitizer runtimes
+ // Used to identify crates that contain sanitizer runtimes.
+ //
// rustc internal
(active, sanitizer_runtime, "1.17.0", None, None),
- // Used to identify crates that contain the profiler runtime
+ // Used to identify crates that contain the profiler runtime.
//
// rustc internal
(active, profiler_runtime, "1.18.0", None, None),
- // `extern "x86-interrupt" fn()`
+ // Allows `extern "x86-interrupt" fn()`.
(active, abi_x86_interrupt, "1.17.0", Some(40180), None),
- // Allows the `try {...}` expression
+ // Allows the `try {...}` expression.
(active, try_blocks, "1.29.0", Some(31436), None),
- // Allows module-level inline assembly by way of global_asm!()
+ // Allows module-level inline assembly by way of `global_asm!()`.
(active, global_asm, "1.18.0", Some(35119), None),
- // Allows overlapping impls of marker traits
+ // Allows overlapping impls of marker traits.
(active, overlapping_marker_traits, "1.18.0", Some(29864), None),
- // Trait attribute to allow overlapping impls
+ // Trait attribute to allow overlapping impls.
(active, marker_trait_attr, "1.30.0", Some(29864), None),
// rustc internal
(active, abi_thiscall, "1.19.0", None, None),
- // Allows a test to fail without failing the whole suite
+ // Allows a test to fail without failing the whole suite.
(active, allow_fail, "1.19.0", Some(46488), None),
// Allows unsized tuple coercion.
// rustc internal
(active, allocator_internals, "1.20.0", None, None),
- // #[doc(cfg(...))]
+ // `#[doc(cfg(...))]`
(active, doc_cfg, "1.21.0", Some(43781), None),
- // #[doc(masked)]
+ // `#[doc(masked)]`
(active, doc_masked, "1.21.0", Some(44027), None),
- // #[doc(spotlight)]
+ // `#[doc(spotlight)]`
(active, doc_spotlight, "1.22.0", Some(45040), None),
- // #[doc(include="some-file")]
+ // `#[doc(include = "some-file")]`
(active, external_doc, "1.22.0", Some(44732), None),
- // Future-proofing enums/structs with #[non_exhaustive] attribute (RFC 2008)
+ // Future-proofing enums/structs with `#[non_exhaustive]` attribute (RFC 2008).
(active, non_exhaustive, "1.22.0", Some(44109), None),
- // `crate` as visibility modifier, synonymous to `pub(crate)`
+ // Adds `crate` as visibility modifier, synonymous with `pub(crate)`.
(active, crate_visibility_modifier, "1.23.0", Some(53120), None),
// extern types
(active, extern_types, "1.23.0", Some(43467), None),
- // Allows trait methods with arbitrary self types
+ // Allows trait methods with arbitrary self types.
(active, arbitrary_self_types, "1.23.0", Some(44874), None),
- // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`)
+ // In-band lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
(active, in_band_lifetimes, "1.23.0", Some(44524), None),
// Generic associated types (RFC 1598)
// `extern` in paths
(active, extern_in_paths, "1.23.0", Some(55600), None),
- // Infer static outlives requirements; RFC 2093
+ // Infer static outlives requirements (RFC 2093).
(active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
- // Multiple patterns with `|` in `if let` and `while let`
+ // Multiple patterns with `|` in `if let` and `while let`.
(active, if_while_or_patterns, "1.26.0", Some(48215), None),
- // Allows `#[repr(packed)]` attribute on structs
+ // Allows `#[repr(packed)]` attribute on structs.
(active, repr_packed, "1.26.0", Some(33158), None),
- // `use path as _;` and `extern crate c as _;`
+ // Allows `use path as _;` and `extern crate c as _;`.
(active, underscore_imports, "1.26.0", Some(48216), None),
- // Allows macro invocations in `extern {}` blocks
+ // Allows macro invocations in `extern {}` blocks.
(active, macros_in_extern, "1.27.0", Some(49476), None),
// `existential type`
(active, existential_type, "1.28.0", Some(34511), None),
- // unstable #[target_feature] directives
+ // unstable `#[target_feature]` directives
(active, arm_target_feature, "1.27.0", Some(44839), None),
(active, aarch64_target_feature, "1.27.0", Some(44839), None),
(active, hexagon_target_feature, "1.27.0", Some(44839), None),
// procedural macros to expand to non-items.
(active, proc_macro_hygiene, "1.30.0", Some(54727), None),
- // #[doc(alias = "...")]
+ // `#[doc(alias = "...")]`
(active, doc_alias, "1.27.0", Some(50146), None),
- // Allows irrefutable patterns in if-let and while-let statements (RFC 2086)
+ // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
(active, irrefutable_let_patterns, "1.27.0", Some(44495), None),
// inconsistent bounds in where clauses
(active, trivial_bounds, "1.28.0", Some(48214), None),
- // 'a: { break 'a; }
+ // `'a: { break 'a; }`
(active, label_break_value, "1.28.0", Some(48594), None),
// Exhaustive pattern matching on `usize` and `isize`.
(active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
- // #[doc(keyword = "...")]
+ // `#[doc(keyword = "...")]`
(active, doc_keyword, "1.28.0", Some(51315), None),
- // Allows async and await syntax
+ // Allows async and await syntax.
(active, async_await, "1.28.0", Some(50547), None),
- // #[alloc_error_handler]
+ // `#[alloc_error_handler]`
(active, alloc_error_handler, "1.29.0", Some(51540), None),
(active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
- // Perma-unstable; added for testing E0705
+ // Added for testing E0705; perma-unstable.
(active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
- // Support for arbitrary delimited token streams in non-macro attributes
+ // support for arbitrary delimited token streams in non-macro attributes
(active, unrestricted_attribute_tokens, "1.30.0", Some(55208), None),
- // Allows `use x::y;` to resolve through `self::x`, not just `::x`
+ // Allows `use x::y;` to resolve through `self::x`, not just `::x`.
(active, uniform_paths, "1.30.0", Some(53130), None),
- // Allows unsized rvalues at arguments and parameters
+ // Allows unsized rvalues at arguments and parameters.
(active, unsized_locals, "1.30.0", Some(48055), None),
- // #![test_runner]
- // #[test_case]
+ // `#![test_runner]`
+ // `#[test_case]`
(active, custom_test_frameworks, "1.30.0", Some(50297), None),
- // Non-builtin attributes in inner attribute position
+ // non-builtin attributes in inner attribute position
(active, custom_inner_attributes, "1.30.0", Some(54726), None),
- // allow mixing of bind-by-move in patterns and references to
+ // Allow mixing of bind-by-move in patterns and references to
// those identifiers in guards, *if* we are using MIR-borrowck
- // (aka NLL). Essentially this means you need to be on
- // edition:2018 or later.
+ // (aka NLL). Essentially this means you need to be using the
+ // 2018 edition or later.
(active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
- // Allows `impl Trait` in bindings (`let`, `const`, `static`)
+ // Allows `impl Trait` in bindings (`let`, `const`, `static`).
(active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
- // #[cfg_attr(predicate, multiple, attributes, here)]
+ // `#[cfg_attr(predicate, multiple, attributes, here)]`
(active, cfg_attr_multi, "1.31.0", Some(54881), None),
- // Allows `const _: TYPE = VALUE`
+ // Allows `const _: TYPE = VALUE`.
(active, underscore_const_names, "1.31.0", Some(54912), None),
// `reason = ` in lint attributes and `expect` lint attribute
declare_features! (
(removed, import_shadowing, "1.0.0", None, None, None),
(removed, managed_boxes, "1.0.0", None, None, None),
- // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
+ // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
(removed, negate_unsigned, "1.0.0", Some(29645), None, None),
(removed, reflect, "1.0.0", Some(27749), None, None),
// A way to temporarily opt out of opt in copy. This will *never* be accepted.
declare_features! (
(accepted, associated_types, "1.0.0", None, None),
- // allow overloading augmented assignment operations like `a += b`
+ // Allows overloading augmented assignment operations like `a += b`.
(accepted, augmented_assignments, "1.8.0", Some(28235), None),
- // allow empty structs and enum variants with braces
+ // Allows empty structs and enum variants with braces.
(accepted, braced_empty_structs, "1.8.0", Some(29720), None),
// Allows indexing into constant arrays.
(accepted, const_indexing, "1.26.0", Some(29947), None),
// to bootstrap fix for #5723.
(accepted, issue_5723_bootstrap, "1.0.0", None, None),
(accepted, macro_rules, "1.0.0", None, None),
- // Allows using #![no_std]
+ // Allows using `#![no_std]`.
(accepted, no_std, "1.6.0", None, None),
(accepted, slicing_syntax, "1.0.0", None, None),
(accepted, struct_variant, "1.0.0", None, None),
// These are used to test this portion of the compiler, they don't actually
- // mean anything
+ // mean anything.
(accepted, test_accepted_feature, "1.0.0", None, None),
(accepted, tuple_indexing, "1.0.0", None, None),
// Allows macros to appear in the type position.
(accepted, type_macros, "1.13.0", Some(27245), None),
(accepted, while_let, "1.0.0", None, None),
- // Allows `#[deprecated]` attribute
+ // Allows `#[deprecated]` attribute.
(accepted, deprecated, "1.9.0", Some(29935), None),
// `expr?`
(accepted, question_mark, "1.13.0", Some(31436), None),
- // Allows `..` in tuple (struct) patterns
+ // Allows `..` in tuple (struct) patterns.
(accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
(accepted, item_like_imports, "1.15.0", Some(35120), None),
// Allows using `Self` and associated types in struct expressions and patterns.
(accepted, more_struct_aliases, "1.16.0", Some(37544), None),
- // elide `'static` lifetimes in `static`s and `const`s
+ // elide `'static` lifetimes in `static`s and `const`s.
(accepted, static_in_const, "1.17.0", Some(35897), None),
// Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
(accepted, field_init_shorthand, "1.17.0", Some(37340), None),
// Allows the definition recursive static items.
(accepted, static_recursion, "1.17.0", Some(29719), None),
- // pub(restricted) visibilities (RFC 1422)
+ // `pub(restricted)` visibilities (RFC 1422)
(accepted, pub_restricted, "1.18.0", Some(32409), None),
- // The #![windows_subsystem] attribute
+ // `#![windows_subsystem]`
(accepted, windows_subsystem, "1.18.0", Some(37499), None),
// Allows `break {expr}` with a value inside `loop`s.
(accepted, loop_break_value, "1.19.0", Some(37339), None),
// Permits numeric fields in struct expressions and patterns.
(accepted, relaxed_adts, "1.19.0", Some(35626), None),
- // Coerces non capturing closures to function pointers
+ // Coerces non capturing closures to function pointers.
(accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
// Allows attributes on struct literal fields.
(accepted, struct_field_attributes, "1.20.0", Some(38814), None),
- // Allows the definition of associated constants in `trait` or `impl`
- // blocks.
+ // Allows the definition of associated constants in `trait` or `impl` blocks.
(accepted, associated_consts, "1.20.0", Some(29646), None),
- // Usage of the `compile_error!` macro
+ // Usage of the `compile_error!` macro.
(accepted, compile_error, "1.20.0", Some(40872), None),
// See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
(accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
- // Allow Drop types in constants (RFC 1440)
+ // Allows `Drop` types in constants (RFC 1440).
(accepted, drop_types_in_const, "1.22.0", Some(33156), None),
// Allows the sysV64 ABI to be specified on all platforms
- // instead of just the platforms on which it is the C ABI
+ // instead of just the platforms on which it is the C ABI.
(accepted, abi_sysv64, "1.24.0", Some(36167), None),
- // Allows `repr(align(16))` struct attribute (RFC 1358)
+ // Allows `repr(align(16))` struct attribute (RFC 1358).
(accepted, repr_align, "1.25.0", Some(33626), None),
- // allow '|' at beginning of match arms (RFC 1925)
+ // Allows '|' at beginning of match arms (RFC 1925).
(accepted, match_beginning_vert, "1.25.0", Some(44101), None),
// Nested groups in `use` (RFC 2128)
(accepted, use_nested_groups, "1.25.0", Some(44494), None),
- // a..=b and ..=b
+ // `a..=b` and `..=b`
(accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
- // allow `..=` in patterns (RFC 1192)
+ // Allows `..=` in patterns (RFC 1192).
(accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
// Termination trait in main (RFC 1937)
(accepted, termination_trait, "1.26.0", Some(43301), None),
- // Copy/Clone closures (RFC 2132)
+ // `Copy`/`Clone` closures (RFC 2132).
(accepted, clone_closures, "1.26.0", Some(44490), None),
(accepted, copy_closures, "1.26.0", Some(44490), None),
// Allows `impl Trait` in function arguments.
(accepted, i128_type, "1.26.0", Some(35118), None),
// Default match binding modes (RFC 2005)
(accepted, match_default_bindings, "1.26.0", Some(42640), None),
- // allow `'_` placeholder lifetimes
+ // Allows `'_` placeholder lifetimes.
(accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
- // Allows attributes on lifetime/type formal parameters in generics (RFC 1327)
+ // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
(accepted, generic_param_attrs, "1.27.0", Some(48848), None),
- // Allows cfg(target_feature = "...").
+ // Allows `cfg(target_feature = "...")`.
(accepted, cfg_target_feature, "1.27.0", Some(29717), None),
- // Allows #[target_feature(...)]
+ // Allows `#[target_feature(...)]`.
(accepted, target_feature, "1.27.0", None, None),
// Trait object syntax with `dyn` prefix
(accepted, dyn_trait, "1.27.0", Some(44662), None),
- // allow `#[must_use]` on functions; and, must-use operators (RFC 1940)
+ // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
(accepted, fn_must_use, "1.27.0", Some(43302), None),
- // Allows use of the :lifetime macro fragment specifier
+ // Allows use of the `:lifetime` macro fragment specifier.
(accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
// Termination trait in tests (RFC 1937)
(accepted, termination_trait_test, "1.27.0", Some(48854), None),
- // The #[global_allocator] attribute
+ // The `#[global_allocator]` attribute
(accepted, global_allocator, "1.28.0", Some(27389), None),
- // Allows `#[repr(transparent)]` attribute on newtype structs
+ // Allows `#[repr(transparent)]` attribute on newtype structs.
(accepted, repr_transparent, "1.28.0", Some(43036), None),
- // Defining procedural macros in `proc-macro` crates
+ // Procedural macros in `proc-macro` crates
(accepted, proc_macro, "1.29.0", Some(38356), None),
// `foo.rs` as an alternative to `foo/mod.rs`
(accepted, non_modrs_mods, "1.30.0", Some(44660), None),
- // Allows use of the :vis macro fragment specifier
+ // Allows use of the `:vis` macro fragment specifier
(accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
// Allows importing and reexporting macros with `use`,
// enables macro modularization in general.
(accepted, use_extern_macros, "1.30.0", Some(35896), None),
- // Allows keywords to be escaped for use as identifiers
+ // Allows keywords to be escaped for use as identifiers.
(accepted, raw_identifiers, "1.30.0", Some(48589), None),
- // Attributes scoped to tools
+ // Attributes scoped to tools.
(accepted, tool_attributes, "1.30.0", Some(44690), None),
- // Allows multi-segment paths in attributes and derives
+ // Allows multi-segment paths in attributes and derives.
(accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
// Allows all literals in attribute lists and values of key-value pairs.
(accepted, attr_literals, "1.30.0", Some(34981), None),
- // Infer outlives requirements; RFC 2093
+ // Infer outlives requirements (RFC 2093).
(accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
(accepted, panic_handler, "1.30.0", Some(44489), None),
- // Used to preserve symbols (see llvm.used)
+ // Used to preserve symbols (see llvm.used).
(accepted, used, "1.30.0", Some(40289), None),
// `crate` in paths
(accepted, crate_in_paths, "1.30.0", Some(45477), None),
- // Resolve absolute paths as paths from other crates
+ // Resolve absolute paths as paths from other crates.
(accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
- // Access to crate names passed via `--extern` through prelude
+ // Access to crate names passed via `--extern` through prelude.
(accepted, extern_prelude, "1.30.0", Some(44660), None),
// Parentheses in patterns
(accepted, pattern_parentheses, "1.31.0", Some(51087), None),
- // Allows the definition of `const fn` functions
+ // Allows the definition of `const fn` functions.
(accepted, min_const_fn, "1.31.0", Some(53555), None),
// Scoped lints
(accepted, tool_lints, "1.31.0", Some(44690), None),
- // impl<I:Iterator> Iterator for &mut Iterator
- // impl Debug for Foo<'_>
+ // `impl<I:Iterator> Iterator for &mut Iterator`
+ // `impl Debug for Foo<'_>`
(accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
- // `extern crate foo as bar;` puts `bar` into extern prelude
+ // `extern crate foo as bar;` puts `bar` into extern prelude.
(accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
- // Allows use of the :literal macro fragment specifier (RFC 1576)
+ // Allows use of the `:literal` macro fragment specifier (RFC 1576).
(accepted, macro_literal_matcher, "1.31.0", Some(35625), None),
// Integer match exhaustiveness checking (RFC 2591)
(accepted, exhaustive_integer_patterns, "1.32.0", Some(50907), None),
- // Use `?` as the Kleene "at most one" operator
+ // Use `?` as the Kleene "at most one" operator.
(accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
// `Self` struct constructor (RFC 2302)
(accepted, self_struct_ctor, "1.32.0", Some(51994), None),
if attr.path == &**n {
// Plugins can't gate attributes, so we don't check for it
// unlike the code above; we only use this loop to
- // short-circuit to avoid the checks below
+ // short-circuit to avoid the checks below.
debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
return;
}
with the prefix `rustc_` \
are reserved for internal compiler diagnostics");
} else if !attr::is_known(attr) {
- // Only run the custom attribute lint during regular
- // feature gate checking. Macro gating runs
- // before the plugin attributes are registered
- // so we skip this then
+ // Only run the custom attribute lint during regular feature gate
+ // checking. Macro gating runs before the plugin attributes are
+ // registered, so we skip this in that case.
if !is_macro {
let msg = format!("The attribute `{}` is currently unknown to the compiler and \
may have meaning added to it in the future", attr.path);
_node_id: NodeId) {
match fn_kind {
FnKind::ItemFn(_, header, _, _) => {
- // check for const fn and async fn declarations
+ // Check for const fn and async fn declarations.
if header.asyncness.is_async() {
gate_feature_post!(&self, async_await, span, "async fn is unstable");
}
- // stability of const fn methods are covered in
- // visit_trait_item and visit_impl_item below; this is
- // because default methods don't pass through this
- // point.
+ // Stability of const fn methods are covered in
+ // `visit_trait_item` and `visit_impl_item` below; this is
+ // because default methods don't pass through this point.
self.check_abi(header.abi, span);
}
fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) {
for segment in &path.segments {
- // Identifiers we are going to check could come from a legacy macro (e.g. `#[test]`).
+ // Identifiers we are going to check could come from a legacy macro (e.g., `#[test]`).
// For such macros identifiers must have empty context, because this context is
// used during name resolution and produced names must be unhygienic for compatibility.
// On the other hand, we need the actual non-empty context for feature gate checking
for &edition in ALL_EDITIONS {
if edition <= crate_edition {
// The `crate_edition` implies its respective umbrella feature-gate
- // (i.e. `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
+ // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
edition_enabled_features.insert(Symbol::intern(edition.feature_name()), edition);
}
}
impl UnstableFeatures {
pub fn from_environment() -> UnstableFeatures {
- // Whether this is a feature-staged build, i.e. on the beta or stable channel
+ // Whether this is a feature-staged build, i.e., on the beta or stable channel
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Whether we should enable unstable features for bootstrapping
let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
fn fold_mac(&mut self, _mac: Mac) -> Mac {
panic!("fold_mac disabled by default");
- // NB: see note about macros above.
+ // N.B., see note about macros above.
// if you really want a folder that
// works on macros, use this
// definition in your trait impl:
/// apply folder to elements of interpolated nodes
//
-// NB: this can occur only when applying a fold to partially expanded code, where
+// N.B., this can occur only when applying a fold to partially expanded code, where
// parsed pieces have gotten implanted ito *other* macro invocations. This is relevant
// for macro hygiene, but possibly not elsewhere.
//
pub mod metadata;
}
-// NB: This module needs to be declared first so diagnostics are
+// N.B., this module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostic_list;
"expected at least one digit in exponent"
);
if let Some(ch) = self.ch {
- // check for e.g. Unicode minus '−' (Issue #49746)
+ // check for e.g., Unicode minus '−' (Issue #49746)
if unicode_chars::check_for_substitution(self, ch, &mut err) {
self.bump();
self.scan_digits(10, 10);
/// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
Expr,
/// In other contexts, notably in types, no ambiguity exists and paths can be written
- /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
+ /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
/// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
Type,
- /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
+ /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
/// visibilities or attributes.
- /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
+ /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
/// (paths in "mod" contexts have to be checked later for absence of generic arguments
/// anyway, due to macros), but it is used to avoid weird suggestions about expected
/// tokens when something goes wrong.
self.parse_arg_general(true)
}
- /// Parse an argument in a lambda header e.g. |arg, arg|
+ /// Parse an argument in a lambda header e.g., |arg, arg|
fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
let pat = self.parse_pat(Some("argument name"))?;
let t = if self.eat(&token::Colon) {
/// parse things like parenthesized exprs,
/// macros, return, etc.
///
- /// NB: This does not parse outer attributes,
+ /// N.B., this does not parse outer attributes,
/// and is private because it only works
/// correctly if called from parse_dot_or_call_expr().
fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
}
- /// Parse the RHS of a local variable declaration (e.g. '= 14;')
+ /// Parse the RHS of a local variable declaration (e.g., '= 14;')
fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
if self.eat(&token::Eq) {
Ok(Some(self.parse_expr()?))
self.parse_pat_with_range_pat(true, expected)
}
- /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
+ /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are
/// allowed.
fn parse_pat_with_range_pat(
&mut self,
}
/// Parse a statement. This stops just before trailing semicolons on everything but items.
- /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
+ /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
Ok(self.parse_stmt_(true))
}
// Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
// BOUND = TY_BOUND | LT_BOUND
- // LT_BOUND = LIFETIME (e.g. `'a`)
+ // LT_BOUND = LIFETIME (e.g., `'a`)
// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
- // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
+ // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
let mut bounds = Vec::new();
loop {
}
// Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
- // BOUND = LT_BOUND (e.g. `'a`)
+ // BOUND = LT_BOUND (e.g., `'a`)
fn parse_lt_param_bounds(&mut self) -> GenericBounds {
let mut lifetimes = Vec::new();
while self.check_lifetime() {
/// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
/// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
- /// If the following element can't be a tuple (i.e. it's a function definition,
+ /// If the following element can't be a tuple (i.e., it's a function definition,
/// it's not a tuple struct field) and the contents within the parens
/// isn't valid, emit a proper diagnostic.
pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
});
// During early phases of the compiler the AST could get modified
- // directly (e.g. attributes added or removed) and the internal cache
+ // directly (e.g., attributes added or removed) and the internal cache
// of tokens my not be invalidated or updated. Consequently if the
// "lossless" token stream disagrees with our actual stringification
// (which has historically been much more battle-tested) then we go
//! The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and
//! 'right' indices denote the active portion of the ring buffer as well as
//! describing hypothetical points-in-the-infinite-stream at most 3N tokens
-//! apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch
+//! apart (i.e., "not wrapped to ring-buffer boundaries"). The paper will switch
//! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer
//! and point-in-infinite-stream senses freely.
//!
//! # Motivations and benefits
//!
//! * **Identity**: sharing AST nodes is problematic for the various analysis
-//! passes (e.g. one may be able to bypass the borrow checker with a shared
+//! passes (e.g., one may be able to bypass the borrow checker with a shared
//! `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the
//! AST hasn't caused issues is because of inefficient folding passes which
//! would always deduplicate any such shared nodes. Even if the AST were to
-//! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`,
+//! switch to an arena, this would still hold, i.e., it couldn't use `&'a T`,
//! but rather a wrapper like `P<'a, T>`.
//!
//! * **Immutability**: `P<T>` disallows mutating its inner `T`, unlike `Box<T>`
//! * **Maintainability**: `P<T>` provides a fixed interface - `Deref`,
//! `and_then` and `map` - which can remain fully functional even if the
//! implementation changes (using a special thread-local heap, for example).
-//! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated.
+//! Moreover, a switch to, e.g., `P<'a, T>` would be easy and mostly automated.
use std::fmt::{self, Display, Debug};
use std::iter::FromIterator;
path: Vec::new(),
test_cases: Vec::new(),
reexport_test_harness_main,
- // NB: doesn't consider the value of `--crate-name` passed on the command line.
+ // N.B., doesn't consider the value of `--crate-name` passed on the command line.
is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false),
toplevel_reexport: None,
ctxt: SyntaxContext::empty().apply_mark(mark),
}
-/// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
-/// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
+/// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
+/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
/// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
pub fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
match value.node {
/// Each method of the Visitor trait is a hook to be potentially
/// overridden. Each method's default implementation recursively visits
/// the substructure of the input via the corresponding `walk` method;
-/// e.g. the `visit_mod` method by default calls `visit::walk_mod`.
+/// e.g., the `visit_mod` method by default calls `visit::walk_mod`.
///
/// If you want to ensure that your code handles every variant
/// explicitly, you need to override each method. (And you also need
}
fn visit_mac(&mut self, _mac: &'ast Mac) {
panic!("visit_mac disabled by default");
- // NB: see note about macros above.
+ // N.B., see note about macros above.
// if you really want a visitor that
// works on macros, use this
// definition in your trait impl:
let fold = cs_fold1(false, // need foldr
|cx, span, subexpr, self_f, other_fs| {
// build up a series of `partial_cmp`s from the inside
- // out (hence foldr) to get lexical ordering, i.e. for op ==
+ // out (hence foldr) to get lexical ordering, i.e., for op ==
// `ast::lt`
//
// ```
//! - Methods taking any number of parameters of any type, and returning
//! any type, other than vectors, bottom and closures.
//! - Generating `impl`s for types with type parameters and lifetimes
-//! (e.g. `Option<T>`), the parameters are automatically given the
+//! (e.g., `Option<T>`), the parameters are automatically given the
//! current trait as a bound. (This includes separate type parameters
//! and lifetimes for methods.)
//! - Additional bounds on the type parameters (`TraitDef.additional_bounds`)
//! - `Struct`, when `Self` is a struct (including tuple structs, e.g
//! `struct T(i32, char)`).
//! - `EnumMatching`, when `Self` is an enum and all the arguments are the
-//! same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`)
+//! same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`)
//! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments
-//! are not the same variant (e.g. `None`, `Some(1)` and `None`).
+//! are not the same variant (e.g., `None`, `Some(1)` and `None`).
//! - `StaticEnum` and `StaticStruct` for static methods, where the type
//! being derived upon is either an enum or struct respectively. (Any
//! argument with type Self is just grouped among the non-self
/// other than the current trait
pub additional_bounds: Vec<Ty<'a>>,
- /// Any extra lifetimes and/or bounds, e.g. `D: serialize::Decoder`
+ /// Any extra lifetimes and/or bounds, e.g., `D: serialize::Decoder`
pub generics: LifetimeBounds<'a>,
/// Is it an `unsafe` trait?
pub struct MethodDef<'a> {
/// name of the method
pub name: &'a str,
- /// List of generics, e.g. `R: rand::Rng`
+ /// List of generics, e.g., `R: rand::Rng`
pub generics: LifetimeBounds<'a>,
- /// Whether there is a self argument (outer Option) i.e. whether
+ /// Whether there is a self argument (outer Option) i.e., whether
/// this is a static function, and whether it is a pointer (inner
/// Option)
pub explicit_self: Option<Option<PtrTy<'a>>>,
// that type. Otherwise casts to `i32` (the default repr
// type).
//
- // i.e. for `enum E<T> { A, B(1), C(T, T) }`, and a deriving
+ // i.e., for `enum E<T> { A, B(1), C(T, T) }`, and a deriving
// with three Self args, builds three statements:
//
// ```
//
// (See also #4499 and #12609; note that some of the
// discussions there influence what choice we make here;
- // e.g. if we feature-gate `match x { ... }` when x refers
- // to an uninhabited type (e.g. a zero-variant enum or a
+ // e.g., if we feature-gate `match x { ... }` when x refers
+ // to an uninhabited type (e.g., a zero-variant enum or a
// type holding such an enum), but do not feature-gate
// zero-variant enums themselves, then attempting to
// derive Debug on such a type could here generate code
Raw(ast::Mutability),
}
-/// A path, e.g. `::std::option::Option::<i32>` (global). Has support
+/// A path, e.g., `::std::option::Option::<i32>` (global). Has support
/// for type parameters and a lifetime.
#[derive(Clone)]
pub struct Path<'a> {
impl<'a, 'b> Context<'a, 'b> {
fn resolve_name_inplace(&self, p: &mut parse::Piece) {
// NOTE: the `unwrap_or` branch is needed in case of invalid format
- // arguments, e.g. `format_args!("{foo}")`.
+ // arguments, e.g., `format_args!("{foo}")`.
let lookup = |s| *self.names.get(s).unwrap_or(&0);
match *p {
fn has_bench_signature(cx: &ExtCtxt, i: &ast::Item) -> bool {
let has_sig = if let ast::ItemKind::Fn(ref decl, _, _, _) = i.node {
- // NB: inadequate check, but we're running
+ // N.B., inadequate check, but we're running
// well before resolve, can't get too deep.
decl.inputs.len() == 1
} else {
}
// Otherwise, `mark` is a macros 1.0 definition and the call site is in a
- // macros 2.0 expansion, i.e. a macros 1.0 invocation is in a macros 2.0 definition.
+ // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
//
// In this case, the tokens from the macros 1.0 definition inherit the hygiene
// at their invocation. That is, we pretend that the macros 1.0 definition
- // was defined at its invocation (i.e. inside the macros 2.0 definition)
+ // was defined at its invocation (i.e., inside the macros 2.0 definition)
// so that the macros 2.0 definition remains hygienic.
//
// See the example at `test/run-pass/hygiene/legacy_interaction.rs`.
/// }
/// ```
/// This returns the expansion whose definition scope we use to privacy check the resolution,
- /// or `None` if we privacy check as usual (i.e. not w.r.t. a macro definition scope).
+ /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
let mut scope = None;
while !expansion.is_descendant_of(self.outer()) {
/// The location of the actual macro invocation or syntax sugar , e.g.
/// `let x = foo!();` or `if let Some(y) = x {}`
///
- /// This may recursively refer to other macro invocations, e.g. if
+ /// This may recursively refer to other macro invocations, e.g., if
/// `foo!()` invoked `bar!()` internally, and there was an
/// expression inside `bar!`; the call_site of the expression in
/// the expansion would point to the `bar!` invocation; that
/// pointing to the `foo!` invocation.
pub call_site: Span,
/// The span of the macro definition itself. The macro may not
- /// have a sensible definition span (e.g. something defined
+ /// have a sensible definition span (e.g., something defined
/// completely inside libsyntax) in which case this is None.
/// This span serves only informational purpose and is not used for resolution.
pub def_site: Option<Span>,
/// The source of expansion.
#[derive(Clone, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub enum ExpnFormat {
- /// e.g. #[derive(...)] <item>
+ /// e.g., #[derive(...)] <item>
MacroAttribute(Symbol),
- /// e.g. `format!()`
+ /// e.g., `format!()`
MacroBang(Symbol),
/// Desugaring done by the compiler during HIR lowering.
CompilerDesugaring(CompilerDesugaringKind)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! The source positions and related helper functions
+//! The source positions and related helper functions.
//!
-//! # Note
+//! ## Note
//!
//! This API is completely unstable and subject to change.
#![feature(specialization)]
#![cfg_attr(not(stage0), feature(stdsimd))]
-use std::borrow::Cow;
-use std::cell::Cell;
-use std::cmp::{self, Ordering};
-use std::fmt;
-use std::hash::{Hasher, Hash};
-use std::ops::{Add, Sub};
-use std::path::PathBuf;
-
-use rustc_data_structures::stable_hasher::StableHasher;
-use rustc_data_structures::sync::{Lrc, Lock};
-
extern crate arena;
extern crate rustc_data_structures;
mod analyze_source_file;
+use rustc_data_structures::stable_hasher::StableHasher;
+use rustc_data_structures::sync::{Lrc, Lock};
+
+use std::borrow::Cow;
+use std::cell::Cell;
+use std::cmp::{self, Ordering};
+use std::fmt;
+use std::hash::{Hasher, Hash};
+use std::ops::{Add, Sub};
+use std::path::PathBuf;
+
pub struct Globals {
symbol_interner: Lock<symbol::Interner>,
span_interner: Lock<span_encoding::SpanInterner>,
scoped_thread_local!(pub static GLOBALS: Globals);
-/// Differentiates between real files and common virtual files
+/// Differentiates between real files and common virtual files.
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
pub enum FileName {
Real(PathBuf),
/// A macro. This includes the full name of the macro, so that there are no clashes.
Macros(String),
- /// call to `quote!`
+ /// Call to `quote!`.
QuoteExpansion(u64),
- /// Command line
+ /// Command line.
Anon(u64),
- /// Hack in src/libsyntax/parse.rs
- /// FIXME(jseyfried)
+ /// Hack in `src/libsyntax/parse.rs`.
+ // FIXME(jseyfried)
MacroExpansion(u64),
ProcMacroSourceCode(u64),
- /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
+ /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
CfgSpec(u64),
- /// Strings provided as crate attributes in the CLI
+ /// Strings provided as crate attributes in the CLI.
CliCrateAttr(u64),
- /// Custom sources for explicit parser calls from plugins and drivers
+ /// Custom sources for explicit parser calls from plugins and drivers.
Custom(String),
DocTest(PathBuf, isize),
}
/// Spans represent a region of code, used for error reporting. Positions in spans
/// are *absolute* positions from the beginning of the source_map, not positions
-/// relative to SourceFiles. Methods on the SourceMap can be used to relate spans back
+/// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
/// to the original source.
/// You must be careful if the span crosses more than one file - you will not be
/// able to use many of the functions on spans in source_map and you cannot assume
-/// that the length of the span = hi - lo; there may be space in the BytePos
+/// that the length of the `span = hi - lo`; there may be space in the `BytePos`
/// range between files.
///
/// `SpanData` is public because `Span` uses a thread-local interner and can't be
}
// The interner is pointed to by a thread local value which is only set on the main thread
-// with parallelization is disabled. So we don't allow Span to transfer between threads
+// with parallelization is disabled. So we don't allow `Span` to transfer between threads
// to avoid panics and other errors, even though it would be memory safe to do so.
#[cfg(not(parallel_queries))]
impl !Send for Span {}
/// A collection of spans. Spans have two orthogonal attributes:
///
-/// - they can be *primary spans*. In this case they are the locus of
+/// - They can be *primary spans*. In this case they are the locus of
/// the error, and would be rendered with `^^^`.
-/// - they can have a *label*. In this case, the label is written next
+/// - They can have a *label*. In this case, the label is written next
/// to the mark in the snippet when we render.
#[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub struct MultiSpan {
let span = self.data();
span.with_hi(span.lo)
}
- /// Returns a new span representing an empty span at the end of this span
+ /// Returns a new span representing an empty span at the end of this span.
#[inline]
pub fn shrink_to_hi(self) -> Span {
let span = self.data();
if self.is_dummy() { other } else { self }
}
- /// Return true if `self` fully encloses `other`.
+ /// Return `true` if `self` fully encloses `other`.
pub fn contains(self, other: Span) -> bool {
let span = self.data();
let other = other.data();
span.lo == other.lo && span.hi == other.hi
}
- /// Returns `Some(span)`, where the start is trimmed by the end of `other`
+ /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
pub fn trim_start(self, other: Span) -> Option<Span> {
let span = self.data();
let other = other.data();
}
}
- /// Return the source span - this is either the supplied span, or the span for
+ /// Return the source span -- this is either the supplied span, or the span for
/// the macro callsite that expanded to it.
pub fn source_callsite(self) -> Span {
self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
}
/// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
- /// if any
+ /// if any.
pub fn parent(self) -> Option<Span> {
self.ctxt().outer().expn_info().map(|i| i.call_site)
}
self.ctxt().outer().expn_info().map(source_callee)
}
- /// Check if a span is "internal" to a macro in which #[unstable]
+ /// Check if a span is "internal" to a macro in which `#[unstable]`
/// items can be used (that is, a macro marked with
/// `#[allow_internal_unstable]`).
pub fn allows_unstable(&self) -> bool {
}
}
- /// Return the compiler desugaring that created this span, or None
+ /// Return the compiler desugaring that created this span, or `None`
/// if this span is not from a desugaring.
pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
match self.ctxt().outer().expn_info() {
let mut prev_span = DUMMY_SP;
let mut result = vec![];
while let Some(info) = self.ctxt().outer().expn_info() {
- // Don't print recursive invocations
+ // Don't print recursive invocations.
if !info.call_site.source_equal(&prev_span) {
let (pre, post) = match info.format {
ExpnFormat::MacroAttribute(..) => ("#[", "]"),
pub fn to(self, end: Span) -> Span {
let span_data = self.data();
let end_data = end.data();
- // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
+ // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
// Return the macro span on its own to avoid weird diagnostic output. It is preferable to
// have an incomplete span than a completely nonsensical one.
if span_data.ctxt != end_data.ctxt {
} else if end_data.ctxt == SyntaxContext::empty() {
return self;
}
- // both span fall within a macro
- // FIXME(estebank) check if it is the *same* macro
+ // Both spans fall within a macro.
+ // FIXME(estebank): check if it is the *same* macro.
}
Span::new(
cmp::min(span_data.lo, end_data.lo),
self.span_labels.push((span, label));
}
- /// Selects the first primary span (if any)
+ /// Selects the first primary span (if any).
pub fn primary_span(&self) -> Option<Span> {
self.primary_spans.first().cloned()
}
is_dummy
}
- /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
+ /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
/// display well (like std macros). Returns true if replacements occurred.
pub fn replace(&mut self, before: Span, after: Span) -> bool {
let mut replacements_occurred = false;
/// Returns the strings to highlight. We always ensure that there
/// is an entry for each of the primary spans -- for each primary
- /// span P, if there is at least one label with span P, we return
+ /// span `P`, if there is at least one label with span `P`, we return
/// those labels (marked as primary). But otherwise we return
/// `SpanLabel` instances with empty labels.
pub fn span_labels(&self) -> Vec<SpanLabel> {
pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
-/// Identifies an offset of a multi-byte character in a SourceFile
+/// Identifies an offset of a multi-byte character in a `SourceFile`.
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
pub struct MultiByteChar {
- /// The absolute offset of the character in the SourceMap
+ /// The absolute offset of the character in the `SourceMap`.
pub pos: BytePos,
- /// The number of bytes, >=2
+ /// The number of bytes, `>= 2`.
pub bytes: u8,
}
-/// Identifies an offset of a non-narrow character in a SourceFile
+/// Identifies an offset of a non-narrow character in a `SourceFile`.
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
pub enum NonNarrowChar {
- /// Represents a zero-width character
+ /// Represents a zero-width character.
ZeroWidth(BytePos),
- /// Represents a wide (fullwidth) character
+ /// Represents a wide (full-width) character.
Wide(BytePos),
- /// Represents a tab character, represented visually with a width of 4 characters
+ /// Represents a tab character, represented visually with a width of 4 characters.
Tab(BytePos),
}
}
}
- /// Returns the absolute offset of the character in the SourceMap
+ /// Returns the absolute offset of the character in the `SourceMap`.
pub fn pos(&self) -> BytePos {
match *self {
NonNarrowChar::ZeroWidth(p) |
}
}
- /// Returns the width of the character, 0 (zero-width) or 2 (wide)
+ /// Returns the width of the character, 0 (zero-width) or 2 (wide).
pub fn width(&self) -> usize {
match *self {
NonNarrowChar::ZeroWidth(_) => 0,
}
}
-/// The state of the lazy external source loading mechanism of a SourceFile.
+/// The state of the lazy external source loading mechanism of a `SourceFile`.
#[derive(PartialEq, Eq, Clone)]
pub enum ExternalSource {
/// The external source has been loaded already.
AbsentOk,
/// A failed attempt has been made to load the external source.
AbsentErr,
- /// No external source has to be loaded, since the SourceFile represents a local crate.
+ /// No external source has to be loaded, since the `SourceFile` represents a local crate.
Unneeded,
}
}
}
-/// A single source in the SourceMap.
+/// A single source in the `SourceMap`.
#[derive(Clone)]
pub struct SourceFile {
/// The name of the file that the source came from, source that doesn't
- /// originate from files has names between angle brackets by convention,
- /// e.g. `<anon>`
+ /// originate from files has names between angle brackets by convention
+ /// (e.g., `<anon>`).
pub name: FileName,
- /// True if the `name` field above has been modified by --remap-path-prefix
+ /// True if the `name` field above has been modified by `--remap-path-prefix`.
pub name_was_remapped: bool,
/// The unmapped path of the file that the source came from.
- /// Set to `None` if the SourceFile was imported from an external crate.
+ /// Set to `None` if the `SourceFile` was imported from an external crate.
pub unmapped_path: Option<FileName>,
- /// Indicates which crate this SourceFile was imported from.
+ /// Indicates which crate this `SourceFile` was imported from.
pub crate_of_origin: u32,
- /// The complete source code
+ /// The complete source code.
pub src: Option<Lrc<String>>,
- /// The source code's hash
+ /// The source code's hash.
pub src_hash: u128,
/// The external source code (used for external crates, which will have a `None`
/// value as `self.src`.
pub external_src: Lock<ExternalSource>,
- /// The start position of this source in the SourceMap
+ /// The start position of this source in the `SourceMap`.
pub start_pos: BytePos,
- /// The end position of this source in the SourceMap
+ /// The end position of this source in the `SourceMap`.
pub end_pos: BytePos,
- /// Locations of lines beginnings in the source code
+ /// Locations of lines beginnings in the source code.
pub lines: Vec<BytePos>,
- /// Locations of multi-byte characters in the source code
+ /// Locations of multi-byte characters in the source code.
pub multibyte_chars: Vec<MultiByteChar>,
- /// Width of characters that are not narrow in the source code
+ /// Width of characters that are not narrow in the source code.
pub non_narrow_chars: Vec<NonNarrowChar>,
- /// A hash of the filename, used for speeding up the incr. comp. hashing.
+ /// A hash of the filename, used for speeding up hashing in incremental compilation.
pub name_hash: u128,
}
s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
s.emit_struct_field("lines", 6, |s| {
let lines = &self.lines[..];
- // store the length
+ // Store the length.
s.emit_u32(lines.len() as u32)?;
if !lines.is_empty() {
}
}
- /// Return the BytePos of the beginning of the current line.
+ /// Return the `BytePos` of the beginning of the current line.
pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
let line_index = self.lookup_line(pos).unwrap();
self.lines[line_index]
}
/// Find the line containing the given position. The return value is the
- /// index into the `lines` array of this SourceFile, not the 1-based line
+ /// index into the `lines` array of this `SourceFile`, not the 1-based line
/// number. If the source_file is empty or the position is located before the
- /// first line, None is returned.
+ /// first line, `None` is returned.
pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
if self.lines.len() == 0 {
return None;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct BytePos(pub u32);
-/// A character offset. Because of multibyte utf8 characters, a byte offset
-/// is not equivalent to a character offset. The SourceMap will convert BytePos
-/// values to CharPos values as necessary.
+/// A character offset. Because of multibyte UTF-8 characters, a byte offset
+/// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
+/// values to `CharPos` values as necessary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct CharPos(pub usize);
-// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
-// have been unsuccessful
+// FIXME: lots of boilerplate in these impls, but so far my attempts to fix
+// have been unsuccessful.
impl Pos for BytePos {
#[inline(always)]
// Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos
//
-/// A source code location used for error reporting
+/// A source code location used for error reporting.
#[derive(Debug, Clone)]
pub struct Loc {
- /// Information about the original source
+ /// Information about the original source.
pub file: Lrc<SourceFile>,
- /// The (1-based) line number
+ /// The (1-based) line number.
pub line: usize,
- /// The (0-based) column offset
+ /// The (0-based) column offset.
pub col: CharPos,
- /// The (0-based) column offset when displayed
+ /// The (0-based) column offset when displayed.
pub col_display: usize,
}
-/// A source code location used as the result of lookup_char_pos_adj
+/// A source code location used as the result of `lookup_char_pos_adj`.
// Actually, *none* of the clients use the filename *or* file field;
// perhaps they should just be removed.
#[derive(Debug)]
pub file: Option<Lrc<SourceFile>>,
}
-// used to be structural records. Better names, anyone?
+// Used to be structural records.
#[derive(Debug)]
pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
#[derive(Debug)]
// except according to those terms.
//! An "interner" is a data structure that associates values with usize tags and
-//! allows bidirectional lookup; i.e. given a value, one can easily find the
+//! allows bidirectional lookup; i.e., given a value, one can easily find the
//! type, and vice versa.
-use hygiene::SyntaxContext;
-use {Span, DUMMY_SP, GLOBALS};
-
-use rustc_data_structures::fx::FxHashMap;
use arena::DroplessArena;
+use rustc_data_structures::fx::FxHashMap;
use serialize::{Decodable, Decoder, Encodable, Encoder};
+
use std::fmt;
use std::str;
use std::cmp::{PartialEq, Ordering, PartialOrd, Ord};
use std::hash::{Hash, Hasher};
+use hygiene::SyntaxContext;
+use {Span, DUMMY_SP, GLOBALS};
+
#[derive(Copy, Clone, Eq)]
pub struct Ident {
pub name: Symbol,
pub const fn new(name: Symbol, span: Span) -> Ident {
Ident { name, span }
}
+
#[inline]
pub const fn with_empty_ctxt(name: Symbol) -> Ident {
Ident::new(name, DUMMY_SP)
/// "Normalize" ident for use in comparisons using "item hygiene".
/// Identifiers with same string value become same if they came from the same "modern" macro
- /// (e.g. `macro` item, but not `macro_rules` item) and stay different if they came from
+ /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
/// different "modern" macros.
/// Technically, this operation strips all non-opaque marks from ident's syntactic context.
pub fn modern(self) -> Ident {
/// "Normalize" ident for use in comparisons using "local variable hygiene".
/// Identifiers with same string value become same if they came from the same non-transparent
- /// macro (e.g. `macro` or `macro_rules!` items) and stay different if they came from different
+ /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
/// non-transparent macros.
/// Technically, this operation strips all transparent marks from ident's syntactic context.
pub fn modern_and_legacy(self) -> Ident {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
if self.span.ctxt().modern() == SyntaxContext::empty() {
s.emit_str(&self.as_str())
- } else { // FIXME(jseyfried) intercrate hygiene
+ } else { // FIXME(jseyfried): intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.as_str());
s.emit_str(&string)
let string = d.read_str()?;
Ok(if !string.starts_with('#') {
Ident::from_str(&string)
- } else { // FIXME(jseyfried) intercrate hygiene
+ } else { // FIXME(jseyfried): intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
})
}
pub struct Symbol(u32);
// The interner is pointed to by a thread local value which is only set on the main thread
-// with parallelization is disabled. So we don't allow Symbol to transfer between threads
+// with parallelization is disabled. So we don't allow `Symbol` to transfer between threads
// to avoid panics and other errors, even though it would be memory safe to do so.
#[cfg(not(parallel_queries))]
impl !Send for Symbol { }
with_interner(|interner| interner.interned(self))
}
- /// gensym's a new usize, using the current interner.
+ /// Gensyms a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
}
}
-// The &'static strs in this type actually point into the arena
+// The `&'static str`s in this type actually point into the arena.
#[derive(Default)]
pub struct Interner {
arena: DroplessArena,
let mut this = Interner::default();
for &string in init {
if string == "" {
- // We can't allocate empty strings in the arena, so handle this here
+ // We can't allocate empty strings in the arena, so handle this here.
let name = Symbol(this.strings.len() as u32);
this.names.insert("", name);
this.strings.push("");
let name = Symbol(self.strings.len() as u32);
- // from_utf8_unchecked is safe since we just allocated a &str which is known to be utf8
+ // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
+ // UTF-8.
let string: &str = unsafe {
str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
};
- // It is safe to extend the arena allocation to 'static because we only access
- // these while the arena is still alive
+ // It is safe to extend the arena allocation to `'static` because we only access
+ // these while the arena is still alive.
let string: &'static str = unsafe {
&*(string as *const str)
};
}
}}
-// NB: leaving holes in the ident table is bad! a different ident will get
+// N.B., leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
// After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
}
impl Ident {
- // Returns true for reserved identifiers used internally for elided lifetimes,
+ // Returns `true` for reserved identifiers used internally for elided lifetimes,
// unnamed method parameters, crate root module, error recovery etc.
pub fn is_special(self) -> bool {
self.name <= keywords::Underscore.name()
/// Represents a string stored in the interner. Because the interner outlives any thread
/// which uses this type, we can safely treat `string` which points to interner data,
/// as an immortal string, as long as this type never crosses between threads.
-// FIXME: Ensure that the interner outlives any thread which uses LocalInternedString,
-// by creating a new thread right after constructing the interner
+// FIXME: ensure that the interner outlives any thread which uses `LocalInternedString`,
+// by creating a new thread right after constructing the interner.
#[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
pub struct LocalInternedString {
string: &'static str,
}
}
-/// Represents a string stored in the string interner
+/// Represents a string stored in the string interner.
#[derive(Clone, Copy, Eq)]
pub struct InternedString {
symbol: Symbol,
/// *Note: This does not flush.*
///
/// That means the reset command may get buffered so, if you aren't planning on doing anything
- /// else that might flush stdout's buffer (e.g. writing a line of text), you should flush after
+ /// else that might flush stdout's buffer (e.g., writing a line of text), you should flush after
/// calling reset.
fn reset(&mut self) -> io::Result<bool>;
p.pop();
// on some installations the dir is named after the hex of the char
- // (e.g. macOS)
+ // (e.g., macOS)
p.push(&format!("{:x}", first_char as usize));
p.push(term);
if fs::metadata(&p).is_ok() {
#[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")]
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
- // note: current tests won't work with non-standard terminfo hierarchies (e.g. macOS's)
+ // note: current tests won't work with non-standard terminfo hierarchies (e.g., macOS's)
use std::env;
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
self.write_pretty(result, color)?;
if self.test_count % QUIET_MODE_MAX_COLUMN == QUIET_MODE_MAX_COLUMN - 1 {
// we insert a new line every 100 dots in order to flush the
- // screen when dealing with line-buffered output (e.g. piping to
+ // screen when dealing with line-buffered output (e.g., piping to
// `stamp` in the rust CI).
let out = format!(" {}/{}\n", self.test_count+1, self.total_test_count);
self.write_plain(&out)?;
// running tests while providing a base that other test frameworks may
// build off of.
-// NB: this is also specified in this crate's Cargo.toml, but libsyntax contains logic specific to
+// N.B., this is also specified in this crate's Cargo.toml, but libsyntax contains logic specific to
// this crate, which relies on this attribute (rather than the value of `--crate-name` passed by
// cargo) to detect this crate.
use formatters::{JsonFormatter, OutputFormatter, PrettyFormatter, TerseFormatter};
// The name of a test. By convention this follows the rules for rust
-// paths; i.e. it should be a series of identifiers separated by double
+// paths; i.e., it should be a series of identifiers separated by double
// colons. This way if some test runner wants to arrange the tests
// hierarchically it may.
// FIXME: Copied from libsyntax until linkage errors are resolved. Issue #47566
fn is_nightly() -> bool {
- // Whether this is a feature-staged build, i.e. on the beta or stable channel
+ // Whether this is a feature-staged build, i.e., on the beta or stable channel
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Whether we should enable unstable features for bootstrapping
let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
// be left doing 0 iterations on every loop. The unfortunate
// side effect of not being able to do as many runs is
// automatically handled by the statistical analysis below
- // (i.e. larger error bars).
+ // (i.e., larger error bars).
n = cmp::max(1, n);
let mut total_run = Duration::new(0, 0);
let x = *s - mean;
v = v + x * x;
}
- // NB: this is _supposed to be_ len-1, not len. If you
+ // N.B., this is _supposed to be_ len-1, not len. If you
// change it back to len, you will be calculating a
// population variance, not a sample variance.
let denom = (self.len() - 1) as f64;
pub mod ms_init {
// .CRT$X?? sections are roughly analogous to ELF's .init_array and .fini_array,
// except that they exploit the fact that linker will sort them alphabitically,
- // so e.g. sections with names between .CRT$XIA and .CRT$XIZ are guaranteed to be
+ // so e.g., sections with names between .CRT$XIA and .CRT$XIZ are guaranteed to be
// placed between those two, without requiring any ordering of objects on the linker
// command line.
// Note that ordering of same-named sections from different objects is not guaranteed.
// ignore-tidy-linelength
// compile-flags:-Zprint-mono-items=lazy
-// NB: We do not expect *any* monomorphization to be generated here.
+// N.B., we do not expect *any* monomorphization to be generated here.
#![deny(dead_code)]
#![crate_type = "rlib"]
// except according to those terms.
// compile-flags: -C no-prepopulate-passes
-// `#[no_mangle]`d functions always have external linkage, i.e. no `internal` in their `define`s
+// `#[no_mangle]`d functions always have external linkage, i.e., no `internal` in their `define`s
#![crate_type = "lib"]
#![no_std]
// except according to those terms.
// compile-flags: -O
-// `#[no_mangle]`d static variables always have external linkage, i.e. no `internal` in their
+// `#[no_mangle]`d static variables always have external linkage, i.e., no `internal` in their
// definitions
#![crate_type = "lib"]
}
// In many of the cases below, the type that is actually under test is wrapped
-// in a tuple, e.g. Box<T>, references, raw pointers, fixed-size vectors, ...
+// in a tuple, e.g., Box<T>, references, raw pointers, fixed-size vectors, ...
// This is because GDB will not print the type name from DWARF debuginfo for
// some kinds of types (pointers, arrays, functions, ...)
// Since tuples are structs as far as GDB is concerned, their name will be
// except according to those terms.
// This test case tests the incremental compilation hash (ICH) implementation
-// for exprs that can panic at runtime (e.g. because of bounds checking). For
+// for exprs that can panic at runtime (e.g., because of bounds checking). For
// these expressions an error message containing their source location is
// generated, so their hash must always depend on their location in the source
// code, not just when debuginfo is enabled.
// Empty struct ----------------------------------------------------------------
// Since we cannot change anything in this case, we just make sure that the
-// fingerprint is stable (i.e. that there are no random influences like memory
+// fingerprint is stable (i.e., that there are no random influences like memory
// addresses taken into account by the hashing algorithm).
// Note: there is no #[cfg(...)], so this is ALWAYS compiled
#[rustc_clean(label="Hir", cfg="cfail2")]
// compile-flags: --crate-type=lib
// A bunch of tests for syntactic forms involving blocks that were
-// previously ambiguous (e.g. 'if true { } *val;' gets parsed as a
+// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a
// binop)
// except according to those terms.
// This test case makes sure that two identical invocations of the compiler
-// (i.e. same code base, same compile-flags, same compiler-versions, etc.)
+// (i.e., same code base, same compile-flags, same compiler-versions, etc.)
// produce the same output. In the past, symbol names of monomorphized functions
// were not deterministic (which we want to avoid).
//
check2!($b, $c);
check2!($a, $c);
- // Check the remaining cases, i.e. permutations of ($a, $b, $c).
+ // Check the remaining cases, i.e., permutations of ($a, $b, $c).
check!($a, $b, $c);
check!($a, $c, $b);
check!($b, $a, $c);
}
// LUB-coercion (if-else/match/array) coerces `xs: &'b [&'static T: N]`
-// to a subtype of the LUB of `xs` and `ys` (i.e. `&'b [&'a T]`),
+// to a subtype of the LUB of `xs` and `ys` (i.e., `&'b [&'a T]`),
// regardless of the order they appear (in if-else/match/array).
fn long_and_short_lub1<'a, 'b, T>(xs: &'b [&'static T; 1], ys: &'b [&'a T]) {
let _order1 = [xs, ys];
}
// LUB-coercion should also have the exact same effect when `&'b [&'a T; N]`
-// needs to be coerced, i.e. the resulting type is not &'b [&'static T], but
+// needs to be coerced, i.e., the resulting type is not &'b [&'static T], but
// rather the `&'b [&'a T]` LUB.
fn long_and_short_lub2<'a, 'b, T>(xs: &'b [&'static T], ys: &'b [&'a T; 1]) {
let _order1 = [xs, ys];
// ignore-cloudabi no processes
// ignore-emscripten no processes
-// NB: These tests kill child processes. Valgrind sees these children as leaking
+// N.B., these tests kill child processes. Valgrind sees these children as leaking
// memory, which makes for some *confusing* logs. That's why these are here
// instead of in std.
// - D means "I implement Drop"
//
// - P means "I implement Drop but guarantee my (first) parameter is
-// pure, i.e. not accessed from the destructor"; no other parameters
+// pure, i.e., not accessed from the destructor"; no other parameters
// are pure.
//
// - S means "I do not implement Drop"
// of all-zeroes.
//
// 6. assert that the context confirms that it actually saw a cycle (since a traversal
-// might have terminated, e.g. on a tree structure that contained no cycles).
+// might have terminated, e.g., on a tree structure that contained no cycles).
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
// Ensure S is moved, not copied, on assignment.
impl Drop for S { fn drop(&mut self) { } }
-// user-defined function "returning" bottom (i.e. no return at all).
+// user-defined function "returning" bottom (i.e., no return at all).
fn my_panic() -> ! { loop {} }
pub fn step(f: bool) {
let weeks_in_year = self.last_week_number();
// Work out the final result.
- // If the week is -1 or >= weeks_in_year, we will need to adjust the year.
+ // If the week is `-1` or `>= weeks_in_year`, we will need to adjust the year.
let year = self.year();
let wd = self.weekday();
}
}
-/// GroupBy implementation.
+/// `GroupBy` implementation.
struct GroupBy<It: Iterator, F> {
it: std::iter::Peekable<It>,
f: F,
s
}
- // HACK(eddyb) Only needed because `impl Trait` can't be
+ // HACK(eddyb): only needed because `impl Trait` can't be
// used with trait methods: `.foo()` becomes `.__(foo)`.
fn __<F, R>(self, f: F) -> R
where F: FnOnce(Self) -> R {
impl<It> IteratorExt for It where It: Iterator {}
-///
-/// Generates an iterator that yields exactly n spaces.
-///
+/// Generates an iterator that yields exactly `n` spaces.
fn spaces(n: usize) -> std::iter::Take<std::iter::Repeat<char>> {
std::iter::repeat(' ').take(n)
}
assert_eq!(spaces(10).collect::<String>(), " ")
}
-///
/// Returns an iterator of dates in a given year.
-///
fn dates_in_year(year: i32) -> impl Iterator<Item=NaiveDate>+Clone {
InGroup {
it: NaiveDate::from_ymd(year, 1, 1)..,
let mut dates = dates_in_year(2013);
assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 1)));
- // Check increment
+ // Check increment.
assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 2)));
- // Check monthly rollover
+ // Check monthly roll-over.
for _ in 3..31 {
assert!(dates.next() != None);
}
}
{
- // Check length of year
+ // Check length of year.
let mut dates = dates_in_year(2013);
for _ in 0..365 {
assert!(dates.next() != None);
}
{
- // Check length of leap year
+ // Check length of leap year.
let mut dates = dates_in_year(1984);
for _ in 0..366 {
assert!(dates.next() != None);
}
}
-///
/// Convenience trait for verifying that a given type iterates over
/// `NaiveDate`s.
-///
trait DateIterator: Iterator<Item=NaiveDate> + Clone {}
impl<It> DateIterator for It where It: Iterator<Item=NaiveDate> + Clone {}
}
}
-///
/// Groups an iterator of dates by month.
-///
fn by_month(it: impl Iterator<Item=NaiveDate> + Clone)
- -> impl Iterator<Item=(u32, impl Iterator<Item=NaiveDate> + Clone)> + Clone
+ -> impl Iterator<Item=(u32, impl Iterator<Item=NaiveDate> + Clone)> + Clone
{
it.group_by(|d| d.month())
}
assert!(months.next().is_none());
}
-///
/// Groups an iterator of dates by week.
-///
fn by_week(it: impl DateIterator)
-> impl Iterator<Item=(u32, impl DateIterator)> + Clone
{
/// The number of columns per week in the formatted output.
const COLS_PER_WEEK: u32 = 7 * COLS_PER_DAY;
-///
/// Formats an iterator of weeks into an iterator of strings.
-///
fn format_weeks(it: impl Iterator<Item = impl DateIterator>) -> impl Iterator<Item=String> {
it.map(|week| {
let mut buf = String::with_capacity((COLS_PER_DAY * COLS_PER_WEEK + 2) as usize);
}
// Insert more filler at the end to fill up the remainder of the week,
- // if its a short week (e.g. at the end of the month).
+ // if its a short week (e.g., at the end of the month).
buf.extend(spaces((COLS_PER_DAY * (6 - last_day)) as usize));
buf
})
);
}
-///
-/// Formats the name of a month, centered on COLS_PER_WEEK.
-///
+/// Formats the name of a month, centered on `COLS_PER_WEEK`.
fn month_title(month: u32) -> String {
const MONTH_NAMES: &'static [&'static str] = &[
"January", "February", "March", "April", "May", "June",
let before = (COLS_PER_WEEK as usize - name.len()) / 2;
let after = COLS_PER_WEEK as usize - name.len() - before;
- // NOTE: Being slightly more verbose to avoid extra allocations.
+ // Note: being slightly more verbose to avoid extra allocations.
let mut result = String::with_capacity(COLS_PER_WEEK as usize);
result.extend(spaces(before));
result.push_str(name);
assert_eq!(month_title(1).len(), COLS_PER_WEEK as usize);
}
-///
/// Formats a month.
-///
fn format_month(it: impl DateIterator) -> impl Iterator<Item=String> {
let mut month_days = it.peekable();
let title = month_title(month_days.peek().unwrap().month());
);
}
-
-///
/// Formats an iterator of months.
-///
fn format_months(it: impl Iterator<Item = impl DateIterator>)
-> impl Iterator<Item=impl Iterator<Item=String>>
{
it.map(format_month)
}
-///
/// Takes an iterator of iterators of strings; the sub-iterators are consumed
/// in lock-step, with their elements joined together.
-///
trait PasteBlocks: Iterator + Sized
-where Self::Item: Iterator<Item=String> {
+where Self::Item: Iterator<Item = String> {
fn paste_blocks(self, sep_width: usize) -> PasteBlocksIter<Self::Item> {
PasteBlocksIter {
iters: self.collect(),
);
}
-///
/// Produces an iterator that yields `n` elements at a time.
-///
trait Chunks: Iterator + Sized {
fn chunks(self, n: usize) -> ChunksIter<Self> {
assert!(n > 0);
n: usize,
}
-// NOTE: `chunks` in Rust is more-or-less impossible without overhead of some kind.
+// Note: `chunks` in Rust is more-or-less impossible without overhead of some kind.
// Aliasing rules mean you need to add dynamic borrow checking, and the design of
// `Iterator` means that you need to have the iterator's state kept in an allocation
// that is jointly owned by the iterator itself and the sub-iterator.
assert_eq!(&*c, &[vec![1, 2, 3], vec![4, 5, 6], vec![7]]);
}
-///
/// Formats a year.
-///
fn format_year(year: i32, months_per_row: usize) -> String {
const COL_SPACING: usize = 1;
// Group the months into horizontal rows.
.chunks(months_per_row)
- // Format each row
+ // Format each row...
.map(|r| r.into_iter()
- // By formatting each month
+ // ... by formatting each month ...
.__(format_months)
- // Horizontally pasting each respective month's lines together.
+ // ... and horizontally pasting each respective month's lines together.
.paste_blocks(COL_SPACING)
.join("\n")
)
- // Insert a blank line between each row
+ // Insert a blank line between each row.
.join("\n\n")
}
// except according to those terms.
// run-pass
+
#![deny(dead_code)]
// use different types / traits to test all combinations
impl UserDefined for i32 { }
impl<'a, T> UserDefined for &'a T { }
-// e.g. `impl_drop!(Send, D_Send)` expands to:
+// e.g., `impl_drop!(Send, D_Send)` expands to:
// ```rust
// struct D_Send<T:Send>(T);
// impl<T:Send> Drop for D_Send<T> { fn drop(&mut self) { } }
// run-pass
-// This test is bogus (i.e. should be compile-fail) during the period
+// This test is bogus (i.e., should be compile-fail) during the period
// where #54986 is implemented and #54987 is *not* implemented. For
// now: just ignore it under nll
//
// run-pass
-// This test is bogus (i.e. should be compile-fail) during the period
+// This test is bogus (i.e., should be compile-fail) during the period
// where #54986 is implemented and #54987 is *not* implemented. For
// now: just ignore it under nll
//
}
// Here we provide an implementation of the Canvas methods for AsciiArt.
-// Other implementations could also be provided (e.g. for PDF or Apple's Quartz)
+// Other implementations could also be provided (e.g., for PDF or Apple's Quartz)
// and code can use them polymorphically via the Canvas trait.
impl Canvas for AsciiArt {
fn add_point(&mut self, shape: Point) {
#![feature(test)]
#![allow(unused_mut)] // under NLL we get warning about `x` below: rust-lang/rust#54499
-// This test is bogus (i.e. should be compile-fail) during the period
+// This test is bogus (i.e., should be compile-fail) during the period
// where #54986 is implemented and #54987 is *not* implemented. For
// now: just ignore it under nll
//
#[inline(never)]
fn tuple_field() -> &'static u32 {
// This test is MIR-borrowck-only because the old borrowck
- // doesn't agree that borrows of "frozen" (i.e. without any
+ // doesn't agree that borrows of "frozen" (i.e., without any
// interior mutability) fields of non-frozen temporaries,
// should be promoted, while MIR promotion does promote them.
&(FIVE, 42).1
// option. This file may not be copied, modified, or distributed\r
// except according to those terms.\r
\r
-// NB: this file needs CRLF line endings. The .gitattributes file in\r
+// N.B., this file needs CRLF line endings. The .gitattributes file in\r
// this directory should enforce it.\r
\r
// ignore-pretty issue #37195\r
#![forbid(non_upper_case_globals)]
#![feature(non_ascii_idents)]
-// Some scripts (e.g. hiragana) don't have a concept of
+// Some scripts (e.g., hiragana) don't have a concept of
// upper/lowercase
struct ヒ;
//
// This checks the behavior of macros with trailing commas in key
// places where regressions in behavior seem highly possible (due
-// to it being e.g. a place where the addition of an argument
+// to it being e.g., a place where the addition of an argument
// causes it to go down a code path with subtly different behavior).
//
// There is a companion test in compile-fail.
// In #46769, `Option<(Packed<&()>, bool)>` was found to have
// pointer alignment, without actually being aligned in size.
- // E.g. on 64-bit platforms, it had alignment `8` but size `9`.
+ // e.g., on 64-bit platforms, it had alignment `8` but size `9`.
type PackedRefAndBool<'a> = (Packed<&'a ()>, bool);
sanity_check_size::<Option<PackedRefAndBool>>(Some((Packed(&()), true)));
// Make sure we don't pay for the enum optimization in size,
- // e.g. we shouldn't need extra padding after the packed data.
+ // e.g., we shouldn't need extra padding after the packed data.
assert_eq!(std::mem::align_of::<Option<PackedRefAndBool>>(), 1);
assert_eq!(std::mem::size_of::<Option<PackedRefAndBool>>(),
std::mem::size_of::<PackedRefAndBool>());
// for details.
assert_eq!(object_invoke2(&*m), 5);
- // The RefMakerTrait above is pretty strange (i.e. it is strange
+ // The RefMakerTrait above is pretty strange (i.e., it is strange
// to consume a value of type T and return a &T). Easiest thing
// that came to my mind: consume a cell of a linked list and
// return a reference to the list it points to.
// there are platform differences for some out of range
// casts, so we just normalize such things: it's OK for
// "invalid" calculations to result in nonsense answers.
- // (E.g. negative float to unsigned integer goes through a
+ // (e.g., negative float to unsigned integer goes through a
// library routine on the default i686 platforms, and the
- // implementation of that routine differs on e.g. Linux
+ // implementation of that routine differs on e.g., Linux
// vs. macOS, resulting in different answers.)
if $from::is_float() {
if !$to::in_range(A) { from.0 = 0 as $to; to.0 = 0 as $to; }
// Err(err) => return Err(From::from(err)),
// }
//
-// This test verifies that the expansion is hygienic, i.e. it's not affected by other `val` and
+// This test verifies that the expansion is hygienic, i.e., it's not affected by other `val` and
// `err` bindings that may be in scope.
use std::num::ParseIntError;
mod bar {
// Also test the unqualified external crate import in a nested module,
// to show that the above import doesn't resolve through a local `std`
- // item, e.g. the automatically injected `extern crate std;`, which in
+ // item, e.g., the automatically injected `extern crate std;`, which in
// the Rust 2018 should no longer be visible through `crate::std`.
pub use std::io;
mod bar {
// Also test the unqualified external crate import in a nested module,
// to show that the above import doesn't resolve through a local `std`
- // item, e.g. the automatically injected `extern crate std;`, which in
+ // item, e.g., the automatically injected `extern crate std;`, which in
// the Rust 2018 should no longer be visible through `crate::std`.
pub use std::io;
}
error[E0599]: no associated item named `ID` found for type `i32` in the current scope
- --> $DIR/associated-const-no-item.rs:16:16
+ --> $DIR/associated-const-no-item.rs:16:23
|
LL | const X: i32 = <i32>::ID;
- | ^^^^^^^^^ associated item not found in `i32`
+ | -------^^
+ | |
+ | associated item not found in `i32`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `ID`, perhaps you need to implement it:
error[E0599]: no variant named `hsl` found for type `color` in the current scope
- --> $DIR/bogus-tag.rs:18:7
+ --> $DIR/bogus-tag.rs:18:14
|
LL | enum color { rgb(isize, isize, isize), rgba(isize, isize, isize, isize), }
| ---------- variant `hsl` not found here
...
LL | color::hsl(h, s, l) => { println!("hsl"); }
- | ^^^^^^^^^^^^^^^^^^^ variant not found in `color`
+ | -------^^^--------- variant not found in `color`
error: aborting due to previous error
//
// - [x] Resolving overloaded_call_traits (call, call_mut, call_once)
// - [x] deref_coercion (shown above)
-// - [x] coerce_unsized e.g. `&[T; n]`, `&mut [T; n] -> &[T]`,
+// - [x] coerce_unsized e.g., `&[T; n]`, `&mut [T; n] -> &[T]`,
// `&mut [T; n] -> &mut [T]`, `&Concrete -> &Trait`
// - [x] Method Call Receivers (the case we want to support!)
// - [x] ExprKind::Index and ExprKind::Unary Deref; only need to handle coerce_index_op
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-all-remote.rs:16:1
|
LL | impl<T> Remote1<T> for isize { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-bigint-param.rs:18:1
|
LL | impl<T> Remote1<BigInt> for T { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-cow.rs:26:1
|
LL | impl<T> Remote for Pair<T,Cover<T>> { } //[a]~ ERROR E0210
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-cow.rs:29:1
|
LL | impl<T> Remote for Pair<Cover<T>,T> { } //[b]~ ERROR E0210
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-cow.rs:32:1
|
LL | impl<T,U> Remote for Pair<Cover<T>,U> { }
= note: conflicting implementation in crate `trait_impl_conflict`:
- impl trait_impl_conflict::Foo for isize;
-error[E0210]: type parameter `A` must be used as the type parameter for some local type (e.g. `MyStruct<A>`)
+error[E0210]: type parameter `A` must be used as the type parameter for some local type (e.g., `MyStruct<A>`)
--> $DIR/coherence-cross-crate-conflict.rs:18:1
|
LL | impl<A> Foo for A {
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-lone-type-parameter.rs:16:1
|
LL | impl<T> Remote for T { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-overlapping-pairs.rs:18:1
|
LL | impl<T> Remote for lib::Pair<T,Foo> { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-pair-covered-uncovered-1.rs:21:1
|
LL | impl<T, U> Remote1<Pair<T, Local<U>>> for i32 { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-pair-covered-uncovered.rs:18:1
|
LL | impl<T,U> Remote for Pair<T,Local<U>> { }
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/coherence-vec-local-2.rs:21:1
|
LL | impl<T> Remote for Vec<Local<T>> { } //~ ERROR E0210
// except according to those terms.
// All lifetime parameters in struct constructors are currently considered early bound,
-// i.e. `S::<ARGS>` is interpreted kinda like an associated item `S::<ARGS>::ctor`.
+// i.e., `S::<ARGS>` is interpreted kinda like an associated item `S::<ARGS>::ctor`.
// This behavior is a bit weird, because if equivalent constructor were written manually
// it would get late bound lifetime parameters.
// Variant constructors behave in the same way, lifetime parameters are considered
#![allow(unused_imports)]
// Note: the relevant lint pass here runs before some of the constant
-// evaluation below (e.g. that performed by codegen and llvm), so if you
+// evaluation below (e.g., that performed by codegen and llvm), so if you
// change this warn to a deny, then the compiler will exit before
// those errors are detected.
#![allow(unused_imports)]
// Note: the relevant lint pass here runs before some of the constant
-// evaluation below (e.g. that performed by codegen and llvm), so if you
+// evaluation below (e.g., that performed by codegen and llvm), so if you
// change this warn to a deny, then the compiler will exit before
// those errors are detected.
#![allow(unused_imports)]
// Note: the relevant lint pass here runs before some of the constant
-// evaluation below (e.g. that performed by codegen and llvm), so if you
+// evaluation below (e.g., that performed by codegen and llvm), so if you
// change this warn to a deny, then the compiler will exit before
// those errors are detected.
LL | const fn bar() -> u32 { foo() } //~ ERROR `foo` is not yet stable as a const fn
| ^^^^^
|
- = help: in Nightly builds, add `#![feature(foo)]` to the crate attributes to enable
+ = help: add `#![feature(foo)]` to the crate attributes to enable
error[E0597]: borrowed value does not live long enough
--> $DIR/dont_promote_unstable_const_fn.rs:28:28
let a = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered
let c = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered
let d = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered
- fn f() {} // Check that the `NOTE`s still work with an item here (c.f. issue #35115).
+ fn f() {} // Check that the `NOTE`s still work with an item here (cf. issue #35115).
}
LL | const A_ID: TypeId = TypeId::of::<A>();
| ^^^^^^^^^^^^^^^^^
|
- = help: in Nightly builds, add `#![feature(const_type_id)]` to the crate attributes to enable
+ = help: add `#![feature(const_type_id)]` to the crate attributes to enable
error: aborting due to previous error
| ^^^^^^^^^^^^^^^^ help: try: `<(u8,)>::AssocItem`
error[E0599]: no associated item named `AssocItem` found for type `[u8]` in the current scope
- --> $DIR/bad-assoc-pat.rs:13:9
+ --> $DIR/bad-assoc-pat.rs:13:15
|
LL | [u8]::AssocItem => {}
- | ^^^^^^^^^^^^^^^ associated item not found in `[u8]`
+ | ------^^^^^^^^^
+ | |
+ | associated item not found in `[u8]`
error[E0599]: no associated item named `AssocItem` found for type `(u8, u8)` in the current scope
- --> $DIR/bad-assoc-pat.rs:16:9
+ --> $DIR/bad-assoc-pat.rs:16:19
|
LL | (u8, u8)::AssocItem => {}
- | ^^^^^^^^^^^^^^^^^^^ associated item not found in `(u8, u8)`
+ | ----------^^^^^^^^^
+ | |
+ | associated item not found in `(u8, u8)`
error[E0599]: no associated item named `AssocItem` found for type `_` in the current scope
- --> $DIR/bad-assoc-pat.rs:19:9
+ --> $DIR/bad-assoc-pat.rs:19:12
|
LL | _::AssocItem => {}
- | ^^^^^^^^^^^^ associated item not found in `_`
+ | ---^^^^^^^^^
+ | |
+ | associated item not found in `_`
error[E0599]: no associated item named `AssocItem` found for type `(u8,)` in the current scope
- --> $DIR/bad-assoc-pat.rs:24:10
+ --> $DIR/bad-assoc-pat.rs:24:17
|
LL | &(u8,)::AssocItem => {}
- | ^^^^^^^^^^^^^^^^ associated item not found in `(u8,)`
+ | -------^^^^^^^^^
+ | |
+ | associated item not found in `(u8,)`
error: aborting due to 8 previous errors
error[E0599]: no function or associated item named `new` found for type `T` in the current scope
- --> $DIR/dont-suggest-private-trait-method.rs:14:5
+ --> $DIR/dont-suggest-private-trait-method.rs:14:8
|
LL | struct T;
| --------- function or associated item `new` not found for this
...
LL | T::new();
- | ^^^^^^ function or associated item not found in `T`
+ | ---^^^
+ | |
+ | function or associated item not found in `T`
error: aborting due to previous error
// - D means "I implement Drop"
//
// - P means "I implement Drop but guarantee my (first) parameter is
-// pure, i.e. not accessed from the destructor"; no other parameters
+// pure, i.e., not accessed from the destructor"; no other parameters
// are pure.
//
// - S means "I do not implement Drop"
- impl<'a, 'b, 'c, T, U, V, W> complex_impl_support::External for (T, complex_impl_support::M<'a, 'b, 'c, std::boxed::Box<U>, V, W>)
where <U as std::ops::FnOnce<(T,)>>::Output == V, <V as std::iter::Iterator>::Item == T, 'b : 'a, T : 'a, U: std::ops::FnOnce<(T,)>, U : 'static, V: std::iter::Iterator, V: std::clone::Clone, W: std::ops::Add, <W as std::ops::Add>::Output: std::marker::Copy;
-error[E0210]: type parameter `R` must be used as the type parameter for some local type (e.g. `MyStruct<R>`)
+error[E0210]: type parameter `R` must be used as the type parameter for some local type (e.g., `MyStruct<R>`)
--> $DIR/complex-impl.rs:19:1
|
LL | impl<R> External for (Q, R) {} //~ ERROR must be used
- impl<T> std::ops::Deref for &T
where T: ?Sized;
-error[E0210]: type parameter `Foo` must be used as the type parameter for some local type (e.g. `MyStruct<Foo>`)
+error[E0210]: type parameter `Foo` must be used as the type parameter for some local type (e.g., `MyStruct<Foo>`)
--> $DIR/issue-28981.rs:15:1
|
LL | impl<Foo> Deref for Foo { } //~ ERROR must be used
| did you mean `XEmpty1 { /* fields */ }`?
error[E0599]: no variant named `Empty3` found for type `empty_struct::XE` in the current scope
- --> $DIR/empty-struct-braces-expr.rs:32:15
+ --> $DIR/empty-struct-braces-expr.rs:32:19
|
LL | let xe3 = XE::Empty3; //~ ERROR no variant named `Empty3` found for type
- | ^^^^^^^^^^ variant not found in `empty_struct::XE`
+ | ----^^^^^^
+ | |
+ | variant not found in `empty_struct::XE`
|
- = note: did you mean `empty_struct::XE::XEmpty3`?
+ = help: did you mean `XEmpty3`?
error[E0599]: no variant named `Empty3` found for type `empty_struct::XE` in the current scope
- --> $DIR/empty-struct-braces-expr.rs:33:15
+ --> $DIR/empty-struct-braces-expr.rs:33:19
|
LL | let xe3 = XE::Empty3(); //~ ERROR no variant named `Empty3` found for type
- | ^^^^^^^^^^ variant not found in `empty_struct::XE`
+ | ----^^^^^^
+ | |
+ | variant not found in `empty_struct::XE`
|
- = note: did you mean `empty_struct::XE::XEmpty3`?
+ = help: did you mean `XEmpty3`?
error: aborting due to 8 previous errors
error[E0599]: no associated item named `NotEvenReal` found for type `Foo` in the current scope
- --> $DIR/E0599.rs:14:15
+ --> $DIR/E0599.rs:14:20
|
LL | struct Foo;
| ----------- associated item `NotEvenReal` not found for this
...
LL | || if let Foo::NotEvenReal() = Foo {}; //~ ERROR E0599
- | ^^^^^^^^^^^^^^^^^^ associated item not found in `Foo`
+ | -----^^^^^^^^^^^-- associated item not found in `Foo`
error: aborting due to previous error
}
mod m3 {
- pub(super) use super::f; // Check that this is counted as used (c.f. #36249).
+ pub(super) use super::f; // Check that this is counted as used (cf. issue #36249).
}
pub mod m4 {
error[E0599]: no associated item named `DOESNOTEXIST` found for type `u32` in the current scope
- --> $DIR/invalid-path-in-const.rs:12:18
+ --> $DIR/invalid-path-in-const.rs:12:23
|
LL | fn f(a: [u8; u32::DOESNOTEXIST]) {}
- | ^^^^^^^^^^^^^^^^^ associated item not found in `u32`
+ | -----^^^^^^^^^^^^
+ | |
+ | associated item not found in `u32`
error: aborting due to previous error
// except according to those terms.
fn main() {
- // NB: this (almost) typechecks when default binding modes are enabled.
+ // N.B., this (almost) typechecks when default binding modes are enabled.
for (ref i,) in [].iter() {
i.clone();
//~^ ERROR type annotations needed
error[E0599]: no variant named `PIE` found for type `Delicious` in the current scope
- --> $DIR/issue-22933-2.rs:14:44
+ --> $DIR/issue-22933-2.rs:14:55
|
LL | enum Delicious {
| -------------- variant `PIE` not found here
...
LL | ApplePie = Delicious::Apple as isize | Delicious::PIE as isize,
- | ^^^^^^^^^^^^^^ variant not found in `Delicious`
+ | -----------^^^
+ | |
+ | variant not found in `Delicious`
error: aborting due to previous error
error[E0599]: no associated item named `MIN` found for type `u8` in the current scope
- --> $DIR/issue-22933-3.rs:11:18
+ --> $DIR/issue-22933-3.rs:11:22
|
LL | const FOO: [u32; u8::MIN as usize] = [];
- | ^^^^^^^ associated item not found in `u8`
+ | ----^^^
+ | |
+ | associated item not found in `u8`
error: aborting due to previous error
error[E0599]: no variant named `Homura` found for type `Token` in the current scope
- --> $DIR/issue-23173.rs:19:16
+ --> $DIR/issue-23173.rs:19:23
|
LL | enum Token { LeftParen, RightParen, Plus, Minus, /* etc */ }
| ---------- variant `Homura` not found here
...
LL | use_token(&Token::Homura);
- | ^^^^^^^^^^^^^ variant not found in `Token`
+ | -------^^^^^^
+ | |
+ | variant not found in `Token`
error[E0599]: no function or associated item named `method` found for type `Struct` in the current scope
- --> $DIR/issue-23173.rs:21:5
+ --> $DIR/issue-23173.rs:21:13
|
LL | struct Struct {
| ------------- function or associated item `method` not found for this
...
LL | Struct::method();
- | ^^^^^^^^^^^^^^ function or associated item not found in `Struct`
+ | --------^^^^^^
+ | |
+ | function or associated item not found in `Struct`
error[E0599]: no function or associated item named `method` found for type `Struct` in the current scope
- --> $DIR/issue-23173.rs:23:5
+ --> $DIR/issue-23173.rs:23:13
|
LL | struct Struct {
| ------------- function or associated item `method` not found for this
...
LL | Struct::method;
- | ^^^^^^^^^^^^^^ function or associated item not found in `Struct`
+ | --------^^^^^^
+ | |
+ | function or associated item not found in `Struct`
error[E0599]: no associated item named `Assoc` found for type `Struct` in the current scope
- --> $DIR/issue-23173.rs:25:5
+ --> $DIR/issue-23173.rs:25:13
|
LL | struct Struct {
| ------------- associated item `Assoc` not found for this
...
LL | Struct::Assoc;
- | ^^^^^^^^^^^^^ associated item not found in `Struct`
+ | --------^^^^^
+ | |
+ | associated item not found in `Struct`
error: aborting due to 4 previous errors
error[E0599]: no variant named `A` found for type `SomeEnum` in the current scope
- --> $DIR/issue-23217.rs:12:9
+ --> $DIR/issue-23217.rs:12:19
|
LL | pub enum SomeEnum {
| ----------------- variant `A` not found here
LL | B = SomeEnum::A,
- | ^^^^^^^^^^^ variant not found in `SomeEnum`
+ | ----------^
+ | |
+ | variant not found in `SomeEnum`
|
- = note: did you mean `SomeEnum::B`?
+ = help: did you mean `B`?
error: aborting due to previous error
LL | let _ = tup[i];
| ^^^^^^
|
- = help: to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`)
+ = help: to access tuple elements, use tuple indexing syntax (e.g., `tuple.0`)
error: aborting due to 2 previous errors
| ^^^^^^^^^^^^^ associated type `Output` must be specified
error[E0599]: no function or associated item named `bitor` found for type `dyn std::ops::BitXor<_>` in the current scope
- --> $DIR/issue-28344.rs:14:17
+ --> $DIR/issue-28344.rs:14:25
|
LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
- | ^^^^^^^^^^^^^ function or associated item not found in `dyn std::ops::BitXor<_>`
+ | --------^^^^^
+ | |
+ | function or associated item not found in `dyn std::ops::BitXor<_>`
|
= help: did you mean `bitxor`?
| ^^^^^^^^^^^^^ associated type `Output` must be specified
error[E0599]: no function or associated item named `bitor` found for type `dyn std::ops::BitXor<_>` in the current scope
- --> $DIR/issue-28344.rs:18:13
+ --> $DIR/issue-28344.rs:18:21
|
LL | let g = BitXor::bitor;
- | ^^^^^^^^^^^^^ function or associated item not found in `dyn std::ops::BitXor<_>`
+ | --------^^^^^
+ | |
+ | function or associated item not found in `dyn std::ops::BitXor<_>`
|
= help: did you mean `bitxor`?
error[E0599]: no associated item named `BYTES` found for type `usize` in the current scope
- --> $DIR/issue-28586.rs:14:19
+ --> $DIR/issue-28586.rs:14:26
|
LL | impl Foo for [u8; usize::BYTES] {}
- | ^^^^^^^^^^^^ associated item not found in `usize`
+ | -------^^^^^
+ | |
+ | associated item not found in `usize`
error: aborting due to previous error
error[E0599]: no variant named `Baz` found for type `Foo` in the current scope
- --> $DIR/issue-28971.rs:19:13
+ --> $DIR/issue-28971.rs:19:18
|
LL | enum Foo {
| -------- variant `Baz` not found here
...
LL | Foo::Baz(..) => (),
- | ^^^^^^^^^^^^ variant not found in `Foo`
+ | -----^^^---- variant not found in `Foo`
|
- = note: did you mean `Foo::Bar`?
+ = help: did you mean `Bar`?
error: aborting due to previous error
error[E0599]: no function or associated item named `new_undirected` found for type `issue_30123_aux::Graph<i32, i32>` in the current scope
- --> $DIR/issue-30123.rs:17:14
+ --> $DIR/issue-30123.rs:17:33
|
LL | let ug = Graph::<i32, i32>::new_undirected();
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `issue_30123_aux::Graph<i32, i32>`
+ | -------------------^^^^^^^^^^^^^^
+ | |
+ | function or associated item not found in `issue_30123_aux::Graph<i32, i32>`
error: aborting due to previous error
// compile-pass
// Tests for an LLVM abort when storing a lifetime-parametric fn into
// context that is expecting one that is not lifetime-parametric
-// (i.e. has no `for <'_>`).
+// (i.e., has no `for <'_>`).
pub struct A<'a>(&'a ());
pub struct S<T>(T);
error[E0599]: no associated item named `Item` found for type `T` in the current scope
- --> $DIR/issue-38919.rs:12:5
+ --> $DIR/issue-38919.rs:12:8
|
LL | T::Item; //~ ERROR no associated item named `Item` found for type `T` in the current scope
- | ^^^^^^^ associated item not found in `T`
+ | ---^^^^
+ | |
+ | associated item not found in `T`
error: aborting due to previous error
error[E0599]: no function or associated item named `dim` found for type `D` in the current scope
- --> $DIR/issue-39559.rs:24:18
+ --> $DIR/issue-39559.rs:24:21
|
LL | entries: [T; D::dim()],
- | ^^^^^^ function or associated item not found in `D`
+ | ---^^^
+ | |
+ | function or associated item not found in `D`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `dim`, perhaps you need to implement it:
| |_____^ not a member of trait `ToString_`
error[E0599]: no function or associated item named `new` found for type `Point` in the current scope
- --> $DIR/issue-3973.rs:32:13
+ --> $DIR/issue-3973.rs:32:20
|
LL | struct Point {
| ------------ function or associated item `new` not found for this
...
LL | let p = Point::new(0.0, 0.0);
- | ^^^^^^^^^^ function or associated item not found in `Point`
+ | -------^^^
+ | |
+ | function or associated item not found in `Point`
error: aborting due to 2 previous errors
LL | ()[f(&[1.0])];
| ^^^^^^^^^^^^^
|
- = help: to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`)
+ = help: to access tuple elements, use tuple indexing syntax (e.g., `tuple.0`)
error: aborting due to previous error
LL | impl<T> Drop for T where T: A { //~ ERROR E0119
| ^ implementing Drop requires a struct
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/issue-41974.rs:17:1
|
LL | impl<T> Drop for T where T: A { //~ ERROR E0119
error[E0599]: no associated item named `String` found for type `std::string::String` in the current scope
- --> $DIR/issue-42880.rs:14:15
+ --> $DIR/issue-42880.rs:14:22
|
LL | let f = |&Value::String(_)| (); //~ ERROR no associated item named
- | ^^^^^^^^^^^^^^^^ associated item not found in `std::string::String`
+ | -------^^^^^^--- associated item not found in `std::string::String`
error: aborting due to previous error
LL | static B: [u32; 1] = [0; A.len()];
| ^^^^^^^
|
- = help: in Nightly builds, add `#![feature(const_slice_len)]` to the crate attributes to enable
+ = help: add `#![feature(const_slice_len)]` to the crate attributes to enable
error: aborting due to 2 previous errors
error[E0599]: no function or associated item named `bar` found for type `Foo` in the current scope
- --> $DIR/issue-7950.rs:16:5
+ --> $DIR/issue-7950.rs:16:10
|
LL | struct Foo;
| ----------- function or associated item `bar` not found for this
...
LL | Foo::bar();
- | ^^^^^^^^ function or associated item not found in `Foo`
+ | -----^^^
+ | |
+ | function or associated item not found in `Foo`
error: aborting due to previous error
|
error[E0599]: no function or associated item named `f` found for type `Foo` in the current scope
- --> $DIR/lexical-scopes.rs:20:5
+ --> $DIR/lexical-scopes.rs:20:10
|
LL | Foo::f(); //~ ERROR no function or associated item named `f`
- | ^^^^^^ function or associated item not found in `Foo`
+ | -----^
+ | |
+ | function or associated item not found in `Foo`
error: aborting due to 2 previous errors
}
}
-// c.f. issue #35135
+// cf. issue #35135.
#[allow(unused_variables)]
fn h() {
use test2::foo; //~ ERROR unused import: `test2::foo`
pub struct Item;
}
-// Use something emitting the type argument name, e.g. unsatisfied bound.
+// Use something emitting the type argument name, e.g., unsatisfied bound.
trait Impossible {}
fn check<T: Impossible>(_: T) {}
// As a shorthand for the cases above, adding a numeric summary to
// each test's fn name to denote each point on each axis.
//
-// E.g. 1000 = field fully init struct; 0211 = local void reinit tuple
+// e.g., 1000 = field fully init struct; 0211 = local void reinit tuple
// It got pretty monotonous writing the same code over and over, and I
// feared I would forget details. So I abstracted some desiderata into
// Test that things from the prelude aren't in scope. Use many of them
// so that renaming some things won't magically make this test fail
-// for the wrong reason (e.g. if `Add` changes to `Addition`, and
+// for the wrong reason (e.g., if `Add` changes to `Addition`, and
// `no_implicit_prelude` stops working, then the `impl Add` will still
// fail with the same error message).
// Test that things from the prelude aren't in scope. Use many of them
// so that renaming some things won't magically make this test fail
-// for the wrong reason (e.g. if `Add` changes to `Addition`, and
+// for the wrong reason (e.g., if `Add` changes to `Addition`, and
// `no_implicit_prelude` stops working, then the `impl Add` will still
// fail with the same error message).
-error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
+error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> $DIR/orphan-check-diagnostics.rs:20:1
|
LL | impl<T> RemoteTrait for T where T: LocalTrait {}
x = if c { a } else { b }();
x = if true { 1 } else { 0 } as *mut _;
// however this does not parse and probably should fail to retain compat?
- // NB: `..` here is arbitrary, failure happens/should happen ∀ops that aren’t `=`
+ // N.B., `..` here is arbitrary, failure happens/should happen ∀ops that aren’t `=`
// see assoc-oddities-2 and assoc-oddities-3
..if c { a } else { b }[n]; //~ ERROR expected one of
}
// Copy.
//
// (I suspect this reflect some naivety within the rust compiler
-// itself; it should be checking for drop glue, i.e. a destructor
+// itself; it should be checking for drop glue, i.e., a destructor
// somewhere in the monomorphized types. It should not matter whether
// the type is Copy.)
#[derive(Copy, Clone)]
// Test that free regions ordering only goes one way. That is,
// we have `&'a Node<'b, T>`, which implies that `'a <= 'b`,
-// but not `'b <= 'a`. Hence returning `&self.val` (which has lifetime
+// but not `'b <= 'a`. Hence, returning `&self.val` (which has lifetime
// `'a`) where `'b` is expected yields an error.
//
// This test began its life as a test for issue #4325.
-struct Node<'b, T:'b> {
- val: T,
- next: Option<&'b Node<'b, T>>
+struct Node<'b, T: 'b> {
+ val: T,
+ next: Option<&'b Node<'b, T>>
}
impl<'b, T> Node<'b, T> {
- fn get<'a>(&'a self) -> &'b T {
- match self.next {
- Some(ref next) => next.get(),
- None => &self.val //~ ERROR cannot infer
+ fn get<'a>(&'a self) -> &'b T {
+ match self.next {
+ Some(ref next) => next.get(),
+ None => &self.val //~ ERROR cannot infer
+ }
}
- }
}
fn main() {}
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
- --> $DIR/regions-free-region-ordering-incorrect.rs:27:15
+ --> $DIR/regions-free-region-ordering-incorrect.rs:27:21
|
-LL | None => &self.val //~ ERROR cannot infer
- | ^^^^^^^^^
+LL | None => &self.val //~ ERROR cannot infer
+ | ^^^^^^^^^
|
-note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 24:10...
- --> $DIR/regions-free-region-ordering-incorrect.rs:24:10
+note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 24:12...
+ --> $DIR/regions-free-region-ordering-incorrect.rs:24:12
|
-LL | fn get<'a>(&'a self) -> &'b T {
- | ^^
+LL | fn get<'a>(&'a self) -> &'b T {
+ | ^^
note: ...so that reference does not outlive borrowed content
- --> $DIR/regions-free-region-ordering-incorrect.rs:27:15
+ --> $DIR/regions-free-region-ordering-incorrect.rs:27:21
|
-LL | None => &self.val //~ ERROR cannot infer
- | ^^^^^^^^^
+LL | None => &self.val //~ ERROR cannot infer
+ | ^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'b as defined on the impl at 23:6...
--> $DIR/regions-free-region-ordering-incorrect.rs:23:6
|
LL | impl<'b, T> Node<'b, T> {
| ^^
note: ...so that reference does not outlive borrowed content
- --> $DIR/regions-free-region-ordering-incorrect.rs:25:5
+ --> $DIR/regions-free-region-ordering-incorrect.rs:25:9
|
-LL | / match self.next {
-LL | | Some(ref next) => next.get(),
-LL | | None => &self.val //~ ERROR cannot infer
-LL | | }
- | |_____^
+LL | / match self.next {
+LL | | Some(ref next) => next.get(),
+LL | | None => &self.val //~ ERROR cannot infer
+LL | | }
+ | |_________^
error: aborting due to previous error
use ImportError; //~ ERROR unresolved import `ImportError` [E0432]
//~^ no `ImportError` in the root
-impl ImportError for () {} // check that this is not an additional error (c.f. #35142)
+impl ImportError for () {} // check that this is not an additional error (cf. issue #35142)
fn main() {}
error[E0599]: no associated item named `XXX` found for type `u32` in the current scope
- --> $DIR/no-double-error.rs:18:9
+ --> $DIR/no-double-error.rs:18:14
|
LL | u32::XXX => { } //~ ERROR no associated item named
- | ^^^^^^^^ associated item not found in `u32`
+ | -----^^^
+ | |
+ | associated item not found in `u32`
error: aborting due to previous error
// edition:2018
// Tests that `meta` is whitelisted, even if the crate doesn't exist
-// yet (i.e. it causes a different error than `not-whitelisted.rs`).
+// yet (i.e., it causes a different error than `not-whitelisted.rs`).
use meta; //~ ERROR can't find crate for `meta`
fn main() {}
| ^^^
error[E0599]: no function or associated item named `from_str` found for type `u32` in the current scope
- --> $DIR/trait-import-suggestions.rs:40:13
+ --> $DIR/trait-import-suggestions.rs:40:18
|
LL | let y = u32::from_str("33"); //~ ERROR no function or associated item named `from_str`
- | ^^^^^^^^^^^^^ function or associated item not found in `u32`
+ | -----^^^^^^^^
+ | |
+ | function or associated item not found in `u32`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope, perhaps add a `use` for it:
struct B(i16, i16, i16, i16, i16, i16, i16, i16);
// each intrinsic definition has to use the same nominal type for any
-// vector structure throughout that declaration (i.e. every instance
+// vector structure throughout that declaration (i.e., every instance
// of i16x8 in each `fn ...;` needs to be either A or B)
extern "platform-intrinsic" {
impl<'a,T> HasMethodWithSelfArg for &'a T { }
impl<'a,T> HasType for &'a T { type Something = (); }
-// e.g. `impl_drop!(Send, D_Send)` expands to:
+// e.g., `impl_drop!(Send, D_Send)` expands to:
// ```rust
// struct D_Send<T:Send>(T);
// impl<T:Send> Drop for D_Send<T> { fn drop(&mut self) { } }
| ^
error[E0599]: no function or associated item named `a` found for type `S` in the current scope
- --> $DIR/trait-item-privacy.rs:88:5
+ --> $DIR/trait-item-privacy.rs:88:8
|
LL | struct S;
| --------- function or associated item `a` not found for this
...
LL | S::a(&S);
- | ^^^^ function or associated item not found in `S`
+ | ---^
+ | |
+ | function or associated item not found in `S`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `a`, perhaps you need to implement it:
candidate #1: `method::A`
error[E0599]: no function or associated item named `b` found for type `S` in the current scope
- --> $DIR/trait-item-privacy.rs:90:5
+ --> $DIR/trait-item-privacy.rs:90:8
|
LL | struct S;
| --------- function or associated item `b` not found for this
...
LL | S::b(&S);
- | ^^^^ function or associated item not found in `S`
+ | ---^
+ | |
+ | function or associated item not found in `S`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope, perhaps add a `use` for it:
| ^^^^
error[E0599]: no associated item named `A` found for type `S` in the current scope
- --> $DIR/trait-item-privacy.rs:107:5
+ --> $DIR/trait-item-privacy.rs:107:8
|
LL | struct S;
| --------- associated item `A` not found for this
...
LL | S::A; //~ ERROR no associated item named `A` found for type `S` in the current scope
- | ^^^^ associated item not found in `S`
+ | ---^
+ | |
+ | associated item not found in `S`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `A`, perhaps you need to implement it:
candidate #1: `assoc_const::A`
error[E0599]: no associated item named `B` found for type `S` in the current scope
- --> $DIR/trait-item-privacy.rs:108:5
+ --> $DIR/trait-item-privacy.rs:108:8
|
LL | struct S;
| --------- associated item `B` not found for this
...
LL | S::B; //~ ERROR no associated item named `B` found for type `S` in the current scope
- | ^^^^ associated item not found in `S`
+ | ---^
+ | |
+ | associated item not found in `S`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope, perhaps add a `use` for it:
x.1.push(y); // &'a i32: 'static does not hold
}
-// Bounds are not checked either, i.e. the definition is not necessarily well-formed
+// Bounds are not checked either, i.e., the definition is not necessarily well-formed
struct Sendable<T: Send>(T);
type MySendable<T> = Sendable<T>; // no error here!
| ^^^^^^^^^^^^^^^^^ help: use fully-qualified syntax: `<<u8 as Tr>::Y as Trait>::NN`
error[E0599]: no associated item named `NN` found for type `<u8 as Tr>::Y` in the current scope
- --> $DIR/ufcs-partially-resolved.rs:48:5
+ --> $DIR/ufcs-partially-resolved.rs:48:20
|
LL | <u8 as Tr>::Y::NN; //~ ERROR no associated item named `NN` found for type `<u8 as Tr>::Y`
- | ^^^^^^^^^^^^^^^^^ associated item not found in `<u8 as Tr>::Y`
+ | ---------------^^
+ | |
+ | associated item not found in `<u8 as Tr>::Y`
error[E0599]: no associated item named `N` found for type `<u8 as Dr>::X` in the current scope
- --> $DIR/ufcs-partially-resolved.rs:65:5
+ --> $DIR/ufcs-partially-resolved.rs:65:20
|
LL | <u8 as Dr>::X::N; //~ ERROR no associated item named `N` found for type `<u8 as Dr>::X`
- | ^^^^^^^^^^^^^^^^ associated item not found in `<u8 as Dr>::X`
+ | ---------------^
+ | |
+ | associated item not found in `<u8 as Dr>::X`
error: aborting due to 32 previous errors
error[E0599]: no function or associated item named `lol` found for type `dyn Foo<_>` in the current scope
- --> $DIR/unspecified-self-in-trait-ref.rs:20:13
+ --> $DIR/unspecified-self-in-trait-ref.rs:20:18
|
LL | let a = Foo::lol();
- | ^^^^^^^^ function or associated item not found in `dyn Foo<_>`
+ | -----^^^
+ | |
+ | function or associated item not found in `dyn Foo<_>`
error[E0599]: no function or associated item named `lol` found for type `dyn Foo<_>` in the current scope
- --> $DIR/unspecified-self-in-trait-ref.rs:22:13
+ --> $DIR/unspecified-self-in-trait-ref.rs:22:23
|
LL | let b = Foo::<_>::lol();
- | ^^^^^^^^^^^^^ function or associated item not found in `dyn Foo<_>`
+ | ----------^^^
+ | |
+ | function or associated item not found in `dyn Foo<_>`
error[E0599]: no function or associated item named `lol` found for type `dyn Bar<_, _>` in the current scope
- --> $DIR/unspecified-self-in-trait-ref.rs:24:13
+ --> $DIR/unspecified-self-in-trait-ref.rs:24:18
|
LL | let c = Bar::lol();
- | ^^^^^^^^ function or associated item not found in `dyn Bar<_, _>`
+ | -----^^^
+ | |
+ | function or associated item not found in `dyn Bar<_, _>`
error[E0599]: no function or associated item named `lol` found for type `dyn Bar<usize, _>` in the current scope
- --> $DIR/unspecified-self-in-trait-ref.rs:26:13
+ --> $DIR/unspecified-self-in-trait-ref.rs:26:30
|
LL | let d = Bar::<usize, _>::lol();
- | ^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `dyn Bar<usize, _>`
+ | -----------------^^^
+ | |
+ | function or associated item not found in `dyn Bar<usize, _>`
error[E0393]: the type parameter `A` must be explicitly specified
--> $DIR/unspecified-self-in-trait-ref.rs:28:13
#[derive(Debug)]
pub struct Error {
pub line_num: usize,
- /// What kind of message we expect (e.g. warning, error, suggestion).
+ /// What kind of message we expect (e.g., warning, error, suggestion).
/// `None` if not specified or unknown message kind.
pub kind: Option<ErrorKind>,
pub msg: String,
}
}
- /// Parses a name-value directive which contains config-specific information, e.g. `ignore-x86`
+ /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86`
/// or `normalize-stderr-32bit`.
fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective {
if line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-') {