Fix merge issues

This commit is contained in:
Christian Poveda 2019-06-20 17:01:48 -05:00
commit e152c38f65
424 changed files with 8084 additions and 4055 deletions

View file

@ -37,7 +37,8 @@ steps:
set -e
brew update
brew install xz
brew install swig
brew install swig@3
brew link --force swig@3
displayName: Install build dependencies (OSX)
condition: and(succeeded(), eq(variables['Agent.OS'], 'Darwin'), eq(variables['SCRIPT'],'./x.py dist'))

View file

@ -263,7 +263,8 @@ install:
if [[ "$SCRIPT" == "./x.py dist" ]]; then
travis_retry brew update &&
travis_retry brew install xz &&
travis_retry brew install swig;
travis_retry brew install swig@3 &&
brew link --force swig@3;
fi &&
travis_retry curl -fo /usr/local/bin/sccache https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/2018-04-02-sccache-x86_64-apple-darwin &&
chmod +x /usr/local/bin/sccache &&

File diff suppressed because it is too large Load diff

View file

@ -32,6 +32,7 @@
use std::env;
use std::io;
use std::mem;
use std::ptr;
use crate::Build;
type HANDLE = *mut u8;
@ -118,8 +119,8 @@ pub unsafe fn setup(build: &mut Build) {
SetErrorMode(mode & !SEM_NOGPFAULTERRORBOX);
// Create a new job object for us to use
let job = CreateJobObjectW(0 as *mut _, 0 as *const _);
assert!(job != 0 as *mut _, "{}", io::Error::last_os_error());
let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
assert!(!job.is_null(), "{}", io::Error::last_os_error());
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
@ -166,8 +167,8 @@ pub unsafe fn setup(build: &mut Build) {
};
let parent = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid.parse().unwrap());
assert!(parent != 0 as *mut _, "{}", io::Error::last_os_error());
let mut parent_handle = 0 as *mut _;
assert!(!parent.is_null(), "{}", io::Error::last_os_error());
let mut parent_handle = ptr::null_mut();
let r = DuplicateHandle(GetCurrentProcess(), job,
parent, &mut parent_handle,
0, FALSE, DUPLICATE_SAME_ACCESS);

View file

@ -209,7 +209,7 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
let h = CreateFileW(path.as_ptr(),
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0 as *mut _,
ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
ptr::null_mut());

View file

@ -30,23 +30,8 @@
# the second column is always zero.
#
# Once you've downloaded a file there's various ways to plot it and visualize
# it. For command line usage you can use a script like so:
#
# set timefmt '%Y-%m-%dT%H:%M:%S'
# set xdata time
# set ylabel "Idle CPU %"
# set xlabel "Time"
# set datafile sep ','
# set term png
# set output "printme.png"
# set grid
# builder = "i686-apple"
# plot "cpu-".builder.".csv" using 1:2 with lines title builder
#
# Executed as `gnuplot < ./foo.plot` it will generate a graph called
# `printme.png` which you can then open up. If you know how to improve this
# script or the viewing process that would be much appreciated :) (or even if
# you know how to automate it!)
# it. For command line usage you use the `src/etc/cpu-usage-over-time-plot.sh`
# script in this repository.
import datetime
import sys

View file

@ -132,7 +132,7 @@ The advantages over a simple `fn(&str) -> u32` are:
In addition to procedural macros, you can define new
[`derive`](../../reference/attributes/derive.md)-like attributes and other kinds
of extensions. See `Registry::register_syntax_extension` and the
`SyntaxExtension` enum. For a more involved macro example, see
`SyntaxExtension` struct. For a more involved macro example, see
[`regex_macros`](https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs).

View file

@ -0,0 +1,49 @@
#!/bin/bash
# A small script to help visualizing CPU usage over time data collected on CI
# using `gnuplot`.
#
# This script is expected to be called with two arguments. The first is the full
# commit SHA of the build you're interested in, and the second is the name of
# the builder. For example:
#
# ./src/etc/cpu-usage-over-time-plot.sh e699ea096fcc2fc9ce8e8bcf884e11496a31cc9f i686-mingw-1
#
# That will generate `$builder.png` in the current directory which you can open
# up to see a hopefully pretty graph.
#
# Improvements to this script are greatly appreciated!
set -ex
bucket=rust-lang-ci-evalazure
commit=$1
builder=$2
curl -O https://$bucket.s3.amazonaws.com/rustc-builds/$commit/cpu-$builder.csv
gnuplot <<-EOF
reset
set timefmt '%Y-%m-%dT%H:%M:%S'
set xdata time
set ylabel "CPU Usage %"
set xlabel "Time"
set datafile sep ','
set term png size 3000,1000
set output "$builder.png"
set grid
f(x) = mean_y
fit f(x) 'cpu-$builder.csv' using 1:(100-\$2) via mean_y
set label 1 gprintf("Average = %g%%", mean_y) center font ",18"
set label 1 at graph 0.50, 0.25
set xtics rotate by 45 offset -2,-2.4 300
set ytics 10
set boxwidth 0.5
plot \\
mean_y with lines linetype 1 linecolor rgb "#ff0000" title "average", \\
"cpu-$builder.csv" using 1:(100-\$2) with points pointtype 7 pointsize 0.4 title "$builder", \\
"" using 1:(100-\$2) smooth bezier linewidth 3 title "bezier"
EOF

View file

@ -31,7 +31,7 @@ category_definition="type summary add --no-value --python-function lldb_rust_for
category_enable="type category enable Rust"
# Call LLDB with the commands added to the argument list
exec "$lldb" --one-line-before-file="$script_import" \
--one-line-before-file="$category_definition" \
--one-line-before-file="$category_enable" \
exec "$lldb" --one-line-before-file "$script_import" \
--one-line-before-file "$category_definition" \
--one-line-before-file "$category_enable" \
"$@"

View file

@ -1515,18 +1515,18 @@ impl<T: ?Sized> Weak<T> {
///
/// ```
/// #![feature(weak_ptr_eq)]
/// use std::rc::{Rc, Weak};
/// use std::rc::Rc;
///
/// let first_rc = Rc::new(5);
/// let first = Rc::downgrade(&first_rc);
/// let second = Rc::downgrade(&first_rc);
///
/// assert!(Weak::ptr_eq(&first, &second));
/// assert!(first.ptr_eq(&second));
///
/// let third_rc = Rc::new(5);
/// let third = Rc::downgrade(&third_rc);
///
/// assert!(!Weak::ptr_eq(&first, &third));
/// assert!(!first.ptr_eq(&third));
/// ```
///
/// Comparing `Weak::new`.
@ -1537,16 +1537,16 @@ impl<T: ?Sized> Weak<T> {
///
/// let first = Weak::new();
/// let second = Weak::new();
/// assert!(Weak::ptr_eq(&first, &second));
/// assert!(first.ptr_eq(&second));
///
/// let third_rc = Rc::new(());
/// let third = Rc::downgrade(&third_rc);
/// assert!(!Weak::ptr_eq(&first, &third));
/// assert!(!first.ptr_eq(&third));
/// ```
#[inline]
#[unstable(feature = "weak_ptr_eq", issue = "55981")]
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr.as_ptr() == other.ptr.as_ptr()
pub fn ptr_eq(&self, other: &Self) -> bool {
self.ptr.as_ptr() == other.ptr.as_ptr()
}
}

View file

@ -1349,18 +1349,18 @@ impl<T: ?Sized> Weak<T> {
///
/// ```
/// #![feature(weak_ptr_eq)]
/// use std::sync::{Arc, Weak};
/// use std::sync::Arc;
///
/// let first_rc = Arc::new(5);
/// let first = Arc::downgrade(&first_rc);
/// let second = Arc::downgrade(&first_rc);
///
/// assert!(Weak::ptr_eq(&first, &second));
/// assert!(first.ptr_eq(&second));
///
/// let third_rc = Arc::new(5);
/// let third = Arc::downgrade(&third_rc);
///
/// assert!(!Weak::ptr_eq(&first, &third));
/// assert!(!first.ptr_eq(&third));
/// ```
///
/// Comparing `Weak::new`.
@ -1371,16 +1371,16 @@ impl<T: ?Sized> Weak<T> {
///
/// let first = Weak::new();
/// let second = Weak::new();
/// assert!(Weak::ptr_eq(&first, &second));
/// assert!(first.ptr_eq(&second));
///
/// let third_rc = Arc::new(());
/// let third = Arc::downgrade(&third_rc);
/// assert!(!Weak::ptr_eq(&first, &third));
/// assert!(!first.ptr_eq(&third));
/// ```
#[inline]
#[unstable(feature = "weak_ptr_eq", issue = "55981")]
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr.as_ptr() == other.ptr.as_ptr()
pub fn ptr_eq(&self, other: &Self) -> bool {
self.ptr.as_ptr() == other.ptr.as_ptr()
}
}

View file

@ -114,8 +114,8 @@ impl<T> Default for TypedArena<T> {
TypedArena {
// We set both `ptr` and `end` to 0 so that the first call to
// alloc() will trigger a grow().
ptr: Cell::new(0 as *mut T),
end: Cell::new(0 as *mut T),
ptr: Cell::new(ptr::null_mut()),
end: Cell::new(ptr::null_mut()),
chunks: RefCell::new(vec![]),
_own: PhantomData,
}
@ -370,8 +370,8 @@ impl Default for DroplessArena {
#[inline]
fn default() -> DroplessArena {
DroplessArena {
ptr: Cell::new(0 as *mut u8),
end: Cell::new(0 as *mut u8),
ptr: Cell::new(ptr::null_mut()),
end: Cell::new(ptr::null_mut()),
chunks: Default::default(),
}
}

View file

@ -202,9 +202,9 @@ pub trait AsMut<T: ?Sized> {
/// A value-to-value conversion that consumes the input value. The
/// opposite of [`From`].
///
/// One should only implement `Into` if a conversion to a type outside the current crate is
/// required. Otherwise one should always prefer implementing [`From`] over `Into` because
/// implementing [`From`] automatically provides one with a implementation of `Into` thanks to
/// One should only implement [`Into`] if a conversion to a type outside the current crate is
/// required. Otherwise one should always prefer implementing [`From`] over [`Into`] because
/// implementing [`From`] automatically provides one with a implementation of [`Into`] thanks to
/// the blanket implementation in the standard library. [`From`] cannot do these type of
/// conversions because of Rust's orphaning rules.
///
@ -213,9 +213,9 @@ pub trait AsMut<T: ?Sized> {
/// # Generic Implementations
///
/// - [`From`]`<T> for U` implies `Into<U> for T`
/// - `Into` is reflexive, which means that `Into<T> for T` is implemented
/// - [`Into`] is reflexive, which means that `Into<T> for T` is implemented
///
/// # Implementing `Into` for conversions to external types
/// # Implementing [`Into`] for conversions to external types
///
/// If the destination type is not part of the current crate
/// then you can't implement [`From`] directly.
@ -231,7 +231,7 @@ pub trait AsMut<T: ?Sized> {
/// ```
/// This will fail to compile because we cannot implement a trait for a type
/// if both the trait and the type are not defined by the current crate.
/// This is due to Rust's orphaning rules. To bypass this, you can implement `Into` directly:
/// This is due to Rust's orphaning rules. To bypass this, you can implement [`Into`] directly:
///
/// ```
/// struct Wrapper<T>(Vec<T>);
@ -242,19 +242,19 @@ pub trait AsMut<T: ?Sized> {
/// }
/// ```
///
/// It is important to understand that `Into` does not provide a [`From`] implementation
/// (as [`From`] does with `Into`). Therefore, you should always try to implement [`From`]
/// and then fall back to `Into` if [`From`] can't be implemented.
/// It is important to understand that [`Into`] does not provide a [`From`] implementation
/// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]
/// and then fall back to [`Into`] if [`From`] can't be implemented.
///
/// Prefer using `Into` over [`From`] when specifying trait bounds on a generic function
/// to ensure that types that only implement `Into` can be used as well.
/// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
/// to ensure that types that only implement [`Into`] can be used as well.
///
/// # Examples
///
/// [`String`] implements `Into<Vec<u8>>`:
///
/// In order to express that we want a generic function to take all arguments that can be
/// converted to a specified type `T`, we can use a trait bound of `Into<T>`.
/// converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.
/// For example: The function `is_hello` takes all arguments that can be converted into a
/// `Vec<u8>`.
///
@ -273,7 +273,7 @@ pub trait AsMut<T: ?Sized> {
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
/// [`String`]: ../../std/string/struct.String.html
/// [`From`]: trait.From.html
/// [`into`]: trait.Into.html#tymethod.into
/// [`Into`]: trait.Into.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
/// Performs the conversion.

View file

@ -5,6 +5,8 @@
//! Utilities related to FFI bindings.
use crate::fmt;
use crate::marker::PhantomData;
use crate::ops::{Deref, DerefMut};
/// Equivalent to C's `void` type when used as a [pointer].
///
@ -45,25 +47,33 @@ impl fmt::Debug for c_void {
}
/// Basic implementation of a `va_list`.
// The name is WIP, using `VaListImpl` for now.
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64")),
not(target_arch = "x86_64"), not(target_arch = "asmjs")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
#[repr(transparent)]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[lang = "va_list"]
pub struct VaListImpl<'f> {
ptr: *mut c_void,
_marker: PhantomData<&'f c_void>,
}
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64"), not(target_arch = "asmjs")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
extern {
type VaListImpl;
}
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
impl fmt::Debug for VaListImpl {
impl<'f> fmt::Debug for VaListImpl<'f> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "va_list* {:p}", self)
write!(f, "va_list* {:p}", self.ptr)
}
}
@ -79,12 +89,14 @@ impl fmt::Debug for VaListImpl {
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
struct VaListImpl {
#[lang = "va_list"]
pub struct VaListImpl<'f> {
stack: *mut c_void,
gr_top: *mut c_void,
vr_top: *mut c_void,
gr_offs: i32,
vr_offs: i32,
_marker: PhantomData<&'f c_void>,
}
/// PowerPC ABI implementation of a `va_list`.
@ -95,12 +107,14 @@ struct VaListImpl {
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
struct VaListImpl {
#[lang = "va_list"]
pub struct VaListImpl<'f> {
gpr: u8,
fpr: u8,
reserved: u16,
overflow_arg_area: *mut c_void,
reg_save_area: *mut c_void,
_marker: PhantomData<&'f c_void>,
}
/// x86_64 ABI implementation of a `va_list`.
@ -111,22 +125,131 @@ struct VaListImpl {
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
struct VaListImpl {
#[lang = "va_list"]
pub struct VaListImpl<'f> {
gp_offset: i32,
fp_offset: i32,
overflow_arg_area: *mut c_void,
reg_save_area: *mut c_void,
_marker: PhantomData<&'f c_void>,
}
/// asm.js ABI implementation of a `va_list`.
// asm.js uses the PNaCl ABI, which specifies that a `va_list` is
// an array of 4 32-bit integers, according to the old PNaCl docs at
// https://web.archive.org/web/20130518054430/https://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Derived-Types
// and clang does the same in `CreatePNaClABIBuiltinVaListDecl` from `lib/AST/ASTContext.cpp`
#[cfg(all(target_arch = "asmjs", not(windows)))]
#[repr(C)]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[lang = "va_list"]
pub struct VaListImpl<'f> {
inner: [crate::mem::MaybeUninit<i32>; 4],
_marker: PhantomData<&'f c_void>,
}
#[cfg(all(target_arch = "asmjs", not(windows)))]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl<'f> fmt::Debug for VaListImpl<'f> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe {
write!(f, "va_list* [{:#x}, {:#x}, {:#x}, {:#x}]",
self.inner[0].read(), self.inner[1].read(),
self.inner[2].read(), self.inner[3].read())
}
}
}
/// A wrapper for a `va_list`
#[lang = "va_list"]
#[repr(transparent)]
#[derive(Debug)]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[repr(transparent)]
pub struct VaList<'a>(&'a mut VaListImpl);
pub struct VaList<'a, 'f: 'a> {
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64"), not(target_arch = "asmjs")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
inner: VaListImpl<'f>,
#[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
target_arch = "x86_64", target_arch = "asmjs"),
any(not(target_arch = "aarch64"), not(target_os = "ios")),
not(windows)))]
inner: &'a mut VaListImpl<'f>,
_marker: PhantomData<&'a mut VaListImpl<'f>>,
}
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64"), not(target_arch = "asmjs")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl<'f> VaListImpl<'f> {
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
#[inline]
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
VaList {
inner: VaListImpl { ..*self },
_marker: PhantomData,
}
}
}
#[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc",
target_arch = "x86_64", target_arch = "asmjs"),
any(not(target_arch = "aarch64"), not(target_os = "ios")),
not(windows)))]
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl<'f> VaListImpl<'f> {
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
#[inline]
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
VaList {
inner: self,
_marker: PhantomData,
}
}
}
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
type Target = VaListImpl<'f>;
#[inline]
fn deref(&self) -> &VaListImpl<'f> {
&self.inner
}
}
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
#[inline]
fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
&mut self.inner
}
}
// The VaArgSafe trait needs to be used in public interfaces, however, the trait
// itself must not be allowed to be used outside this module. Allowing users to
@ -175,56 +298,76 @@ impl<T> sealed_trait::VaArgSafe for *mut T {}
issue = "44930")]
impl<T> sealed_trait::VaArgSafe for *const T {}
impl<'a> VaList<'a> {
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[cfg(not(bootstrap))]
impl<'f> VaListImpl<'f> {
/// Advance to the next arg.
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[inline]
pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
va_arg(self)
}
/// Copies the `va_list` at the current location.
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
pub unsafe fn with_copy<F, R>(&self, f: F) -> R
where F: for<'copy> FnOnce(VaList<'copy>) -> R {
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
let mut ap = va_copy(self);
#[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
let mut ap_inner = va_copy(self);
#[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
let mut ap = VaList(&mut ap_inner);
let ret = f(VaList(ap.0));
where F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R {
let mut ap = self.clone();
let ret = f(ap.as_va_list());
va_end(&mut ap);
ret
}
}
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[cfg(not(bootstrap))]
impl<'f> Clone for VaListImpl<'f> {
#[inline]
fn clone(&self) -> Self {
let mut dest = crate::mem::MaybeUninit::uninit();
unsafe {
va_copy(dest.as_mut_ptr(), self);
dest.assume_init()
}
}
}
#[unstable(feature = "c_variadic",
reason = "the `c_variadic` feature has not been properly tested on \
all supported platforms",
issue = "44930")]
#[cfg(not(bootstrap))]
impl<'f> Drop for VaListImpl<'f> {
fn drop(&mut self) {
// FIXME: this should call `va_end`, but there's no clean way to
// guarantee that `drop` always gets inlined into its caller,
// so the `va_end` would get directly called from the same function as
// the corresponding `va_copy`. `man va_end` states that C requires this,
// and LLVM basically follows the C semantics, so we need to make sure
// that `va_end` is always called from the same function as `va_copy`.
// For more details, see https://github.com/rust-lang/rust/pull/59625
// and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
//
// This works for now, since `va_end` is a no-op on all current LLVM targets.
}
}
extern "rust-intrinsic" {
/// Destroy the arglist `ap` after initialization with `va_start` or
/// `va_copy`.
fn va_end(ap: &mut VaList<'_>);
#[cfg(not(bootstrap))]
fn va_end(ap: &mut VaListImpl<'_>);
/// Copies the current location of arglist `src` to the arglist `dst`.
#[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"),
not(target_arch = "x86_64")),
all(target_arch = "aarch64", target_os = "ios"),
windows))]
fn va_copy<'a>(src: &VaList<'a>) -> VaList<'a>;
#[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", target_arch = "x86_64"),
not(windows), not(all(target_arch = "aarch64", target_os = "ios"))))]
fn va_copy(src: &VaList<'_>) -> VaListImpl;
#[cfg(not(bootstrap))]
fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
/// Loads an argument of type `T` from the `va_list` `ap` and increment the
/// argument `ap` points to.
fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaList<'_>) -> T;
#[cfg(not(bootstrap))]
fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
}

View file

@ -1607,3 +1607,9 @@ pub fn maxnumf64(x: f64, y: f64) -> f64 {
// Identical to the `f32` case.
(if x < y || x != x { y } else { x }) * 1.0
}
/// For bootstrapping, implement unchecked_sub as just wrapping_sub.
#[cfg(bootstrap)]
pub unsafe fn unchecked_sub<T>(x: T, y: T) -> T {
sub_with_overflow(x, y).0
}

View file

@ -1509,6 +1509,20 @@ impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSize
}
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
let len = self.len();
if n < len {
self.iter.nth_back(n)
} else {
if len > 0 {
// consume the original iterator
self.iter.nth_back(len-1);
}
None
}
}
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
{

View file

@ -100,6 +100,7 @@
#![feature(staged_api)]
#![feature(std_internals)]
#![feature(stmt_expr_attributes)]
#![cfg_attr(not(bootstrap), feature(transparent_unions))]
#![feature(unboxed_closures)]
#![feature(unsized_locals)]
#![feature(untagged_unions)]

View file

@ -172,7 +172,7 @@ use crate::mem::ManuallyDrop;
///
/// # Layout
///
/// `MaybeUninit<T>` is guaranteed to have the same size and alignment as `T`:
/// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
///
/// ```rust
/// use std::mem::{MaybeUninit, size_of, align_of};
@ -191,9 +191,23 @@ use crate::mem::ManuallyDrop;
/// assert_eq!(size_of::<Option<bool>>(), 1);
/// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
/// ```
///
/// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
///
/// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
/// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
/// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
/// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
/// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
/// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
/// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
/// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
/// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
/// guarantee may evolve.
#[allow(missing_debug_implementations)]
#[stable(feature = "maybe_uninit", since = "1.36.0")]
#[derive(Copy)]
#[cfg_attr(not(bootstrap), repr(transparent))]
pub union MaybeUninit<T> {
uninit: (),
value: ManuallyDrop<T>,

View file

@ -230,6 +230,53 @@ pub const fn null<T>() -> *const T { 0 as *const T }
#[rustc_promotable]
pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
#[repr(C)]
pub(crate) union Repr<T> {
pub(crate) rust: *const [T],
rust_mut: *mut [T],
pub(crate) raw: FatPtr<T>,
}
#[repr(C)]
pub(crate) struct FatPtr<T> {
data: *const T,
pub(crate) len: usize,
}
/// Forms a slice from a pointer and a length.
///
/// The `len` argument is the number of **elements**, not the number of bytes.
///
/// # Examples
///
/// ```rust
/// #![feature(slice_from_raw_parts)]
/// use std::ptr;
///
/// // create a slice pointer when starting out with a pointer to the first element
/// let mut x = [5, 6, 7];
/// let ptr = &mut x[0] as *mut _;
/// let slice = ptr::slice_from_raw_parts_mut(ptr, 3);
/// assert_eq!(unsafe { &*slice }[2], 7);
/// ```
#[inline]
#[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
pub fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
unsafe { Repr { raw: FatPtr { data, len } }.rust }
}
/// Performs the same functionality as [`from_raw_parts`], except that a
/// mutable slice is returned.
///
/// See the documentation of [`from_raw_parts`] for more details.
///
/// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
#[inline]
#[unstable(feature = "slice_from_raw_parts", reason = "recently added", issue = "36925")]
pub fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
unsafe { Repr { raw: FatPtr { data, len } }.rust_mut }
}
/// Swaps the values at two mutable locations of the same type, without
/// deinitializing either.
///

View file

@ -25,7 +25,7 @@
use crate::cmp::Ordering::{self, Less, Equal, Greater};
use crate::cmp;
use crate::fmt;
use crate::intrinsics::assume;
use crate::intrinsics::{assume, exact_div, unchecked_sub};
use crate::isize;
use crate::iter::*;
use crate::ops::{FnMut, Try, self};
@ -45,19 +45,6 @@ pub mod memchr;
mod rotate;
mod sort;
#[repr(C)]
union Repr<'a, T: 'a> {
rust: &'a [T],
rust_mut: &'a mut [T],
raw: FatPtr<T>,
}
#[repr(C)]
struct FatPtr<T> {
data: *const T,
len: usize,
}
//
// Extension traits
//
@ -78,7 +65,7 @@ impl<T> [T] {
#[rustc_const_unstable(feature = "const_slice_len")]
pub const fn len(&self) -> usize {
unsafe {
Repr { rust: self }.raw.len
crate::ptr::Repr { rust: self }.raw.len
}
}
@ -2998,14 +2985,27 @@ macro_rules! is_empty {
// unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
macro_rules! len {
($self: ident) => {{
#![allow(unused_unsafe)] // we're sometimes used within an unsafe block
let start = $self.ptr;
let diff = ($self.end as usize).wrapping_sub(start as usize);
let size = size_from_ptr(start);
if size == 0 {
// This _cannot_ use `unchecked_sub` because we depend on wrapping
// to represent the length of long ZST slice iterators.
let diff = ($self.end as usize).wrapping_sub(start as usize);
diff
} else {
// Using division instead of `offset_from` helps LLVM remove bounds checks
diff / size
// We know that `start <= end`, so can do better than `offset_from`,
// which needs to deal in signed. By setting appropriate flags here
// we can tell LLVM this, which helps it remove bounds checks.
// SAFETY: By the type invariant, `start <= end`
let diff = unsafe { unchecked_sub($self.end as usize, start as usize) };
// By also telling LLVM that the pointers are apart by an exact
// multiple of the type size, it can optimize `len() == 0` down to
// `start == end` instead of `(end - start) < size`.
// SAFETY: By the type invariant, the pointers are aligned so the
// distance between them must be a multiple of pointee size
unsafe { exact_div(diff, size) }
}
}}
}
@ -3019,6 +3019,28 @@ macro_rules! iterator {
{$( $mut_:tt )*},
{$($extra:tt)*}
) => {
// Returns the first element and moves the start of the iterator forwards by 1.
// Greatly improves performance compared to an inlined function. The iterator
// must not be empty.
macro_rules! next_unchecked {
($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
}
// Returns the last element and moves the end of the iterator backwards by 1.
// Greatly improves performance compared to an inlined function. The iterator
// must not be empty.
macro_rules! next_back_unchecked {
($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
}
// Shrinks the iterator when T is a ZST, by moving the end of the iterator
// backwards by `n`. `n` must not exceed `self.len()`.
macro_rules! zst_shrink {
($self: ident, $n: ident) => {
$self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
}
}
impl<'a, T> $name<'a, T> {
// Helper function for creating a slice from the iterator.
#[inline(always)]
@ -3028,12 +3050,11 @@ macro_rules! iterator {
// Helper function for moving the start of the iterator forwards by `offset` elements,
// returning the old start.
// Unsafe because the offset must be in-bounds or one-past-the-end.
// Unsafe because the offset must not exceed `self.len()`.
#[inline(always)]
unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
if mem::size_of::<T>() == 0 {
// This is *reducing* the length. `ptr` never changes with ZST.
self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
zst_shrink!(self, offset);
self.ptr
} else {
let old = self.ptr;
@ -3044,11 +3065,11 @@ macro_rules! iterator {
// Helper function for moving the end of the iterator backwards by `offset` elements,
// returning the new end.
// Unsafe because the offset must be in-bounds or one-past-the-end.
// Unsafe because the offset must not exceed `self.len()`.
#[inline(always)]
unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
if mem::size_of::<T>() == 0 {
self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
zst_shrink!(self, offset);
self.ptr
} else {
self.end = self.end.offset(-offset);
@ -3085,7 +3106,7 @@ macro_rules! iterator {
if is_empty!(self) {
None
} else {
Some(& $( $mut_ )* *self.post_inc_start(1))
Some(next_unchecked!(self))
}
}
}
@ -3114,11 +3135,10 @@ macro_rules! iterator {
}
return None;
}
// We are in bounds. `offset` does the right thing even for ZSTs.
// We are in bounds. `post_inc_start` does the right thing even for ZSTs.
unsafe {
let elem = Some(& $( $mut_ )* *self.ptr.add(n));
self.post_inc_start((n as isize).wrapping_add(1));
elem
self.post_inc_start(n as isize);
Some(next_unchecked!(self))
}
}
@ -3135,13 +3155,13 @@ macro_rules! iterator {
let mut accum = init;
unsafe {
while len!(self) >= 4 {
accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
accum = f(accum, next_unchecked!(self))?;
accum = f(accum, next_unchecked!(self))?;
accum = f(accum, next_unchecked!(self))?;
accum = f(accum, next_unchecked!(self))?;
}
while !is_empty!(self) {
accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
accum = f(accum, next_unchecked!(self))?;
}
}
Try::from_ok(accum)
@ -3212,11 +3232,25 @@ macro_rules! iterator {
if is_empty!(self) {
None
} else {
Some(& $( $mut_ )* *self.pre_dec_end(1))
Some(next_back_unchecked!(self))
}
}
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<$elem> {
if n >= len!(self) {
// This iterator is now empty.
self.end = self.ptr;
return None;
}
// We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
unsafe {
self.pre_dec_end(n as isize);
Some(next_back_unchecked!(self))
}
}
#[inline]
fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
@ -3225,14 +3259,14 @@ macro_rules! iterator {
let mut accum = init;
unsafe {
while len!(self) >= 4 {
accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
accum = f(accum, next_back_unchecked!(self))?;
accum = f(accum, next_back_unchecked!(self))?;
accum = f(accum, next_back_unchecked!(self))?;
accum = f(accum, next_back_unchecked!(self))?;
}
// inlining is_empty everywhere makes a huge performance difference
while !is_empty!(self) {
accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
accum = f(accum, next_back_unchecked!(self))?;
}
}
Try::from_ok(accum)
@ -5182,7 +5216,7 @@ pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
"attempt to create slice covering half the address space");
Repr { raw: FatPtr { data, len } }.rust
&*ptr::slice_from_raw_parts(data, len)
}
/// Performs the same functionality as [`from_raw_parts`], except that a
@ -5203,7 +5237,7 @@ pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T]
debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
"attempt to create slice covering half the address space");
Repr { raw: FatPtr { data, len } }.rust_mut
&mut *ptr::slice_from_raw_parts_mut(data, len)
}
/// Converts a reference to T into a slice of length 1 (without copying).

View file

@ -2333,6 +2333,40 @@ fn test_skip_try_folds() {
assert_eq!(iter.next_back(), Some(24));
}
#[test]
fn test_skip_nth_back() {
let xs = [0, 1, 2, 3, 4, 5];
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(0), Some(&5));
assert_eq!(it.nth_back(1), Some(&3));
assert_eq!(it.nth_back(0), Some(&2));
assert_eq!(it.nth_back(0), None);
let ys = [2, 3, 4, 5];
let mut ity = ys.iter();
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(1), ity.nth_back(1));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(4), None);
assert_eq!(it.nth_back(0), None);
let mut it = xs.iter();
it.by_ref().skip(2).nth_back(3);
assert_eq!(it.next_back(), Some(&1));
let mut it = xs.iter();
it.by_ref().skip(2).nth_back(10);
assert_eq!(it.next_back(), Some(&1));
}
#[test]
fn test_take_try_folds() {
let f = &|acc, x| i32::checked_add(2*acc, x);

View file

@ -88,6 +88,19 @@ fn test_iterator_nth() {
assert_eq!(iter.nth(1).unwrap(), &v[4]);
}
#[test]
fn test_iterator_nth_back() {
let v: &[_] = &[0, 1, 2, 3, 4];
for i in 0..v.len() {
assert_eq!(v.iter().nth_back(i).unwrap(), &v[v.len() - i - 1]);
}
assert_eq!(v.iter().nth_back(v.len()), None);
let mut iter = v.iter();
assert_eq!(iter.nth_back(2).unwrap(), &v[2]);
assert_eq!(iter.nth_back(1).unwrap(), &v[0]);
}
#[test]
fn test_iterator_last() {
let v: &[_] = &[0, 1, 2, 3, 4];

View file

@ -7,7 +7,7 @@ use core::any::Any;
use core::intrinsics;
pub fn payload() -> *mut u8 {
0 as *mut u8
core::ptr::null_mut()
}
pub unsafe fn cleanup(_ptr: *mut u8) -> Box<dyn Any + Send> {

View file

@ -104,7 +104,7 @@ mod imp {
pub const NAME2: [u8; 7] = [b'.', b'P', b'A', b'X', 0, 0, 0];
macro_rules! ptr {
(0) => (0 as *mut u8);
(0) => (core::ptr::null_mut());
($e:expr) => ($e as *mut u8);
}
}
@ -223,13 +223,13 @@ extern "C" {
#[cfg_attr(not(test), lang = "msvc_try_filter")]
static mut TYPE_DESCRIPTOR1: _TypeDescriptor = _TypeDescriptor {
pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
spare: 0 as *mut _,
spare: core::ptr::null_mut(),
name: imp::NAME1,
};
static mut TYPE_DESCRIPTOR2: _TypeDescriptor = _TypeDescriptor {
pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
spare: 0 as *mut _,
spare: core::ptr::null_mut(),
name: imp::NAME2,
};

View file

@ -7,7 +7,7 @@ use crate::ty::{self, TyCtxt};
use crate::hir::{self, PatKind};
use crate::hir::def_id::DefId;
struct CFGBuilder<'a, 'tcx: 'a> {
struct CFGBuilder<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
owner_def_id: DefId,
tables: &'a ty::TypeckTables<'tcx>,
@ -42,7 +42,7 @@ pub fn construct<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body) -> CFG {
let body_exit;
// Find the tables for this body.
let owner_def_id = tcx.hir().local_def_id(tcx.hir().body_owner(body.id()));
let owner_def_id = tcx.hir().body_owner_def_id(body.id());
let tables = tcx.typeck_tables_of(owner_def_id);
let mut cfg_builder = CFGBuilder {
@ -330,7 +330,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
hir::ExprKind::DropTemps(ref e) |
hir::ExprKind::Unary(_, ref e) |
hir::ExprKind::Field(ref e, _) |
hir::ExprKind::Yield(ref e) |
hir::ExprKind::Yield(ref e, _) |
hir::ExprKind::Repeat(ref e, _) => {
self.straightline(expr, pred, Some(&**e).into_iter())
}
@ -357,7 +357,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
args: I) -> CFGIndex {
let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
let ret = self.straightline(call_expr, func_or_rcvr_exit, args);
let m = self.tcx.hir().get_module_parent_by_hir_id(call_expr.hir_id);
let m = self.tcx.hir().get_module_parent(call_expr.hir_id);
if self.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(call_expr)) {
self.add_unreachable_node()
} else {

View file

@ -11,7 +11,7 @@ use crate::ty::TyCtxt;
pub type Node<'a> = (cfg::CFGIndex, &'a cfg::CFGNode);
pub type Edge<'a> = &'a cfg::CFGEdge;
pub struct LabelledCFG<'a, 'tcx: 'a> {
pub struct LabelledCFG<'a, 'tcx> {
pub tcx: TyCtxt<'tcx>,
pub cfg: &'a cfg::CFG,
pub name: String,
@ -22,11 +22,11 @@ pub struct LabelledCFG<'a, 'tcx: 'a> {
impl<'a, 'tcx> LabelledCFG<'a, 'tcx> {
fn local_id_to_string(&self, local_id: hir::ItemLocalId) -> String {
assert!(self.cfg.owner_def_id.is_local());
let node_id = self.tcx.hir().hir_to_node_id(hir::HirId {
let hir_id = hir::HirId {
owner: self.tcx.hir().def_index_to_hir_id(self.cfg.owner_def_id.index).owner,
local_id
});
let s = self.tcx.hir().node_to_string(node_id);
};
let s = self.tcx.hir().node_to_string(hir_id);
// Replacing newlines with \\l causes each line to be left-aligned,
// improving presentation of (long) pretty-printed expressions.

View file

@ -204,11 +204,9 @@ macro_rules! define_dep_nodes {
impl DepNode {
#[allow(unreachable_code, non_snake_case)]
#[inline(always)]
pub fn new<'a, 'tcx>(tcx: TyCtxt<'tcx>,
pub fn new<'tcx>(tcx: TyCtxt<'tcx>,
dep: DepConstructor<'tcx>)
-> DepNode
where 'tcx: 'a,
'tcx: 'a
{
match dep {
$(

View file

@ -74,7 +74,7 @@ impl<'a> FnKind<'a> {
///
/// See the comments on `ItemLikeVisitor` for more details on the overall
/// visit strategy.
pub enum NestedVisitorMap<'this, 'tcx: 'this> {
pub enum NestedVisitorMap<'this, 'tcx> {
/// Do not visit any nested things. When you add a new
/// "non-nested" thing, you will want to audit such uses to see if
/// they remain valid.
@ -171,7 +171,7 @@ pub trait Visitor<'v> : Sized {
/// but cannot supply a `Map`; see `nested_visit_map` for advice.
#[allow(unused_variables)]
fn visit_nested_item(&mut self, id: ItemId) {
let opt_item = self.nested_visit_map().inter().map(|map| map.expect_item_by_hir_id(id.id));
let opt_item = self.nested_visit_map().inter().map(|map| map.expect_item(id.id));
if let Some(item) = opt_item {
self.visit_item(item);
}
@ -773,7 +773,6 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi
pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
walk_list!(visitor, visit_generic_param, &generics.params);
visitor.visit_id(generics.where_clause.hir_id);
walk_list!(visitor, visit_where_predicate, &generics.where_clause.predicates);
}
@ -1089,7 +1088,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
visitor.visit_expr(expr)
}
}
ExprKind::Yield(ref subexpression) => {
ExprKind::Yield(ref subexpression, _) => {
visitor.visit_expr(subexpression);
}
ExprKind::Lit(_) | ExprKind::Err => {}

View file

@ -62,14 +62,14 @@ use syntax::errors;
use syntax::ext::hygiene::{Mark, SyntaxContext};
use syntax::print::pprust;
use syntax::ptr::P;
use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned};
use syntax::source_map::{self, respan, ExpnInfo, CompilerDesugaringKind, Spanned};
use syntax::source_map::CompilerDesugaringKind::IfTemporary;
use syntax::std_inject;
use syntax::symbol::{kw, sym, Symbol};
use syntax::tokenstream::{TokenStream, TokenTree};
use syntax::parse::token::{self, Token};
use syntax::visit::{self, Visitor};
use syntax_pos::{DUMMY_SP, edition, Span};
use syntax_pos::{DUMMY_SP, Span};
const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
@ -95,8 +95,7 @@ pub struct LoweringContext<'a> {
modules: BTreeMap<NodeId, hir::ModuleItems>,
is_generator: bool,
is_async_body: bool,
generator_kind: Option<hir::GeneratorKind>,
/// Used to get the current `fn`'s def span to point to when using `await`
/// outside of an `async fn`.
@ -142,6 +141,9 @@ pub struct LoweringContext<'a> {
current_hir_id_owner: Vec<(DefIndex, u32)>,
item_local_id_counters: NodeMap<u32>,
node_id_to_hir_id: IndexVec<NodeId, hir::HirId>,
allow_try_trait: Option<Lrc<[Symbol]>>,
allow_gen_future: Option<Lrc<[Symbol]>>,
}
pub trait Resolver {
@ -261,12 +263,13 @@ pub fn lower_crate(
current_hir_id_owner: vec![(CRATE_DEF_INDEX, 0)],
item_local_id_counters: Default::default(),
node_id_to_hir_id: IndexVec::new(),
is_generator: false,
is_async_body: false,
generator_kind: None,
current_item: None,
lifetimes_to_define: Vec::new(),
is_collecting_in_band_lifetimes: false,
in_scope_lifetimes: Vec::new(),
allow_try_trait: Some([sym::try_trait][..].into()),
allow_gen_future: Some([sym::gen_future][..].into()),
}.lower_crate(krate)
}
@ -415,7 +418,7 @@ impl<'a> LoweringContext<'a> {
/// needed from arbitrary locations in the crate,
/// e.g., the number of lifetime generic parameters
/// declared for every type and trait definition.
struct MiscCollector<'tcx, 'interner: 'tcx> {
struct MiscCollector<'tcx, 'interner> {
lctx: &'tcx mut LoweringContext<'interner>,
hir_id_owner: Option<NodeId>,
}
@ -561,7 +564,7 @@ impl<'a> LoweringContext<'a> {
}
}
struct ItemLowerer<'tcx, 'interner: 'tcx> {
struct ItemLowerer<'tcx, 'interner> {
lctx: &'tcx mut LoweringContext<'interner>,
}
@ -605,15 +608,7 @@ impl<'a> LoweringContext<'a> {
});
if let Some(hir_id) = item_hir_id {
let item_generics = match self.lctx.items.get(&hir_id).unwrap().node {
hir::ItemKind::Impl(_, _, _, ref generics, ..)
| hir::ItemKind::Trait(_, _, ref generics, ..) => {
generics.params.clone()
}
_ => HirVec::new(),
};
self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
let this = &mut ItemLowerer { lctx: this };
if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.node {
this.with_trait_impl_ref(opt_trait_ref, |this| {
@ -790,18 +785,49 @@ impl<'a> LoweringContext<'a> {
})
}
fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
if self.is_generator && self.is_async_body {
span_err!(
self.sess,
value.span,
E0727,
"`async` generators are not yet supported",
);
self.sess.abort_if_errors();
fn generator_movability_for_fn(
&mut self,
decl: &ast::FnDecl,
fn_decl_span: Span,
generator_kind: Option<hir::GeneratorKind>,
movability: Movability,
) -> Option<hir::GeneratorMovability> {
match generator_kind {
Some(hir::GeneratorKind::Gen) => {
if !decl.inputs.is_empty() {
span_err!(
self.sess,
fn_decl_span,
E0628,
"generators cannot have explicit arguments"
);
self.sess.abort_if_errors();
}
Some(match movability {
Movability::Movable => hir::GeneratorMovability::Movable,
Movability::Static => hir::GeneratorMovability::Static,
})
},
Some(hir::GeneratorKind::Async) => {
bug!("non-`async` closure body turned `async` during lowering");
},
None => {
if movability == Movability::Static {
span_err!(
self.sess,
fn_decl_span,
E0697,
"closures cannot be static"
);
}
None
},
}
}
fn record_body(&mut self, arguments: HirVec<hir::Arg>, value: hir::Expr) -> hir::BodyId {
let body = hir::Body {
is_generator: self.is_generator || self.is_async_body,
generator_kind: self.generator_kind,
arguments,
value,
};
@ -848,14 +874,10 @@ impl<'a> LoweringContext<'a> {
allow_internal_unstable: Option<Lrc<[Symbol]>>,
) -> Span {
let mark = Mark::fresh(Mark::root());
mark.set_expn_info(source_map::ExpnInfo {
call_site: span,
mark.set_expn_info(ExpnInfo {
def_site: Some(span),
format: source_map::CompilerDesugaring(reason),
allow_internal_unstable,
allow_internal_unsafe: false,
local_inner_macros: false,
edition: edition::Edition::from_session(),
..ExpnInfo::default(source_map::CompilerDesugaring(reason), span, self.sess.edition())
});
span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
}
@ -1024,14 +1046,22 @@ impl<'a> LoweringContext<'a> {
// This should only be used with generics that have already had their
// in-band lifetimes added. In practice, this means that this function is
// only used when lowering a child item of a trait or impl.
fn with_parent_impl_lifetime_defs<T, F>(&mut self,
params: &HirVec<hir::GenericParam>,
fn with_parent_item_lifetime_defs<T, F>(&mut self,
parent_hir_id: hir::HirId,
f: F
) -> T where
F: FnOnce(&mut LoweringContext<'_>) -> T,
{
let old_len = self.in_scope_lifetimes.len();
let lt_def_names = params.iter().filter_map(|param| match param.kind {
let parent_generics = match self.items.get(&parent_hir_id).unwrap().node {
hir::ItemKind::Impl(_, _, _, ref generics, ..)
| hir::ItemKind::Trait(_, _, ref generics, ..) => {
&generics.params[..]
}
_ => &[],
};
let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()),
_ => None,
});
@ -1083,8 +1113,7 @@ impl<'a> LoweringContext<'a> {
lowered_generics.params = lowered_generics
.params
.iter()
.cloned()
.into_iter()
.chain(in_band_defs)
.collect();
@ -1142,7 +1171,7 @@ impl<'a> LoweringContext<'a> {
};
let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
let body_id = self.lower_fn_body(&ast_decl, |this| {
this.is_async_body = true;
this.generator_kind = Some(hir::GeneratorKind::Async);
body(this)
});
let generator = hir::Expr {
@ -1156,7 +1185,7 @@ impl<'a> LoweringContext<'a> {
let unstable_span = self.mark_span_with_reason(
CompilerDesugaringKind::Async,
span,
Some(vec![sym::gen_future].into()),
self.allow_gen_future.clone(),
);
let gen_future = self.expr_std_path(
unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
@ -1167,12 +1196,10 @@ impl<'a> LoweringContext<'a> {
&mut self,
f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec<hir::Arg>, hir::Expr),
) -> hir::BodyId {
let prev_is_generator = mem::replace(&mut self.is_generator, false);
let prev_is_async_body = mem::replace(&mut self.is_async_body, false);
let prev_gen_kind = self.generator_kind.take();
let (arguments, result) = f(self);
let body_id = self.record_body(arguments, result);
self.is_generator = prev_is_generator;
self.is_async_body = prev_is_async_body;
self.generator_kind = prev_gen_kind;
body_id
}
@ -1674,7 +1701,7 @@ impl<'a> LoweringContext<'a> {
}
TyKind::Mac(_) => bug!("`TyMac` should have been expanded by now."),
TyKind::CVarArgs => {
// Create the implicit lifetime of the "spoofed" `VaList`.
// Create the implicit lifetime of the "spoofed" `VaListImpl`.
let span = self.sess.source_map().next_point(t.span.shrink_to_lo());
let lt = self.new_implicit_lifetime(span);
hir::TyKind::CVarArgs(lt)
@ -1727,8 +1754,8 @@ impl<'a> LoweringContext<'a> {
generics: hir::Generics {
params: lifetime_defs,
where_clause: hir::WhereClause {
hir_id: lctx.next_id(),
predicates: hir_vec![],
span,
},
span,
},
@ -1788,7 +1815,7 @@ impl<'a> LoweringContext<'a> {
// This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that
// 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>`.
struct ImplTraitLifetimeCollector<'r, 'a: 'r> {
struct ImplTraitLifetimeCollector<'r, 'a> {
context: &'r mut LoweringContext<'a>,
parent: DefIndex,
exist_ty_id: NodeId,
@ -1799,7 +1826,7 @@ impl<'a> LoweringContext<'a> {
output_lifetime_params: Vec<hir::GenericParam>,
}
impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
impl<'r, 'a, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> {
fn nested_visit_map<'this>(
&'this mut self,
) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
@ -2619,8 +2646,8 @@ impl<'a> LoweringContext<'a> {
generics: hir::Generics {
params: generic_params,
where_clause: hir::WhereClause {
hir_id: this.next_id(),
predicates: hir_vec![],
span,
},
span,
},
@ -2973,11 +3000,11 @@ impl<'a> LoweringContext<'a> {
AnonymousLifetimeMode::ReportError,
|this| {
hir::WhereClause {
hir_id: this.lower_node_id(wc.id),
predicates: wc.predicates
.iter()
.map(|predicate| this.lower_where_predicate(predicate))
.collect(),
span: wc.span,
}
},
)
@ -3086,8 +3113,8 @@ impl<'a> LoweringContext<'a> {
&NodeMap::default(),
itctx.reborrow(),
);
let trait_ref = self.with_parent_impl_lifetime_defs(
&bound_generic_params,
let trait_ref = self.with_in_scope_lifetime_defs(
&p.bound_generic_params,
|this| this.lower_trait_ref(&p.trait_ref, itctx),
);
@ -3574,8 +3601,7 @@ impl<'a> LoweringContext<'a> {
// Essentially a single `use` which imports two names is desugared into
// two imports.
for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) {
let vis = vis.clone();
let ident = ident.clone();
let ident = *ident;
let mut path = path.clone();
for seg in &mut path.segments {
seg.id = self.sess.next_node_id();
@ -3588,19 +3614,7 @@ impl<'a> LoweringContext<'a> {
let path =
this.lower_path_extra(res, &path, ParamMode::Explicit, None);
let item = hir::ItemKind::Use(P(path), hir::UseKind::Single);
let vis_kind = match vis.node {
hir::VisibilityKind::Public => hir::VisibilityKind::Public,
hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
let path = this.renumber_segment_ids(path);
hir::VisibilityKind::Restricted {
path,
hir_id: this.next_id(),
}
}
};
let vis = respan(vis.span, vis_kind);
let vis = this.rebuild_vis(&vis);
this.insert_item(
hir::Item {
@ -3664,8 +3678,6 @@ impl<'a> LoweringContext<'a> {
for &(ref use_tree, id) in trees {
let new_hir_id = self.lower_node_id(id);
let mut vis = vis.clone();
let mut ident = ident.clone();
let mut prefix = prefix.clone();
// Give the segments new node-ids since they are being cloned.
@ -3679,6 +3691,9 @@ impl<'a> LoweringContext<'a> {
// own its own names, we have to adjust the owner before
// lowering the rest of the import.
self.with_hir_id_owner(id, |this| {
let mut vis = this.rebuild_vis(&vis);
let mut ident = *ident;
let item = this.lower_use_tree(use_tree,
&prefix,
id,
@ -3686,20 +3701,6 @@ impl<'a> LoweringContext<'a> {
&mut ident,
attrs);
let vis_kind = match vis.node {
hir::VisibilityKind::Public => hir::VisibilityKind::Public,
hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
let path = this.renumber_segment_ids(path);
hir::VisibilityKind::Restricted {
path: path,
hir_id: this.next_id(),
}
}
};
let vis = respan(vis.span, vis_kind);
this.insert_item(
hir::Item {
hir_id: new_hir_id,
@ -3745,15 +3746,35 @@ impl<'a> LoweringContext<'a> {
/// 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
/// `NodeId`s. (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();
for seg in path.segments.iter_mut() {
if seg.hir_id.is_some() {
seg.hir_id = Some(self.next_id());
}
fn rebuild_use_path(&mut self, path: &hir::Path) -> hir::Path {
debug!("rebuild_use_path(path = {:?})", path);
let segments = path.segments.iter().map(|seg| hir::PathSegment {
ident: seg.ident,
hir_id: seg.hir_id.map(|_| self.next_id()),
res: seg.res,
args: None,
infer_args: seg.infer_args,
}).collect();
hir::Path {
span: path.span,
res: path.res,
segments,
}
path
}
fn rebuild_vis(&mut self, vis: &hir::Visibility) -> hir::Visibility {
let vis_kind = match vis.node {
hir::VisibilityKind::Public => hir::VisibilityKind::Public,
hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar),
hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited,
hir::VisibilityKind::Restricted { ref path, hir_id: _ } => {
hir::VisibilityKind::Restricted {
path: P(self.rebuild_use_path(path)),
hir_id: self.next_id(),
}
}
};
respan(vis.span, vis_kind)
}
fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
@ -4382,7 +4403,7 @@ impl<'a> LoweringContext<'a> {
let unstable_span = this.mark_span_with_reason(
CompilerDesugaringKind::TryBlock,
body.span,
Some(vec![sym::try_trait].into()),
this.allow_try_trait.clone(),
);
let mut block = this.lower_block(body, true).into_inner();
let tail = block.expr.take().map_or_else(
@ -4475,37 +4496,18 @@ impl<'a> LoweringContext<'a> {
self.with_new_scopes(|this| {
this.current_item = Some(fn_decl_span);
let mut is_generator = false;
let mut generator_kind = None;
let body_id = this.lower_fn_body(decl, |this| {
let e = this.lower_expr(body);
is_generator = this.is_generator;
generator_kind = this.generator_kind;
e
});
let generator_option = if is_generator {
if !decl.inputs.is_empty() {
span_err!(
this.sess,
fn_decl_span,
E0628,
"generators cannot have explicit arguments"
);
this.sess.abort_if_errors();
}
Some(match movability {
Movability::Movable => hir::GeneratorMovability::Movable,
Movability::Static => hir::GeneratorMovability::Static,
})
} else {
if movability == Movability::Static {
span_err!(
this.sess,
fn_decl_span,
E0697,
"closures cannot be static"
);
}
None
};
let generator_option = this.generator_movability_for_fn(
&decl,
fn_decl_span,
generator_kind,
movability,
);
hir::ExprKind::Closure(
this.lower_capture_clause(capture_clause),
fn_decl,
@ -4677,12 +4679,26 @@ impl<'a> LoweringContext<'a> {
}
ExprKind::Yield(ref opt_expr) => {
self.is_generator = true;
match self.generator_kind {
Some(hir::GeneratorKind::Gen) => {},
Some(hir::GeneratorKind::Async) => {
span_err!(
self.sess,
e.span,
E0727,
"`async` generators are not yet supported",
);
self.sess.abort_if_errors();
},
None => {
self.generator_kind = Some(hir::GeneratorKind::Gen);
}
}
let expr = opt_expr
.as_ref()
.map(|x| self.lower_expr(x))
.unwrap_or_else(|| self.expr_unit(e.span));
hir::ExprKind::Yield(P(expr))
hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
}
ExprKind::Err => hir::ExprKind::Err,
@ -4968,13 +4984,13 @@ impl<'a> LoweringContext<'a> {
let unstable_span = self.mark_span_with_reason(
CompilerDesugaringKind::QuestionMark,
e.span,
Some(vec![sym::try_trait].into()),
self.allow_try_trait.clone(),
);
let try_span = self.sess.source_map().end_point(e.span);
let try_span = self.mark_span_with_reason(
CompilerDesugaringKind::QuestionMark,
try_span,
Some(vec![sym::try_trait].into()),
self.allow_try_trait.clone(),
);
// `Try::into_result(<expr>)`
@ -5754,19 +5770,23 @@ impl<'a> LoweringContext<'a> {
// yield ();
// }
// }
if !self.is_async_body {
let mut err = struct_span_err!(
self.sess,
await_span,
E0728,
"`await` is only allowed inside `async` functions and blocks"
);
err.span_label(await_span, "only allowed inside `async` functions and blocks");
if let Some(item_sp) = self.current_item {
err.span_label(item_sp, "this is not `async`");
match self.generator_kind {
Some(hir::GeneratorKind::Async) => {},
Some(hir::GeneratorKind::Gen) |
None => {
let mut err = struct_span_err!(
self.sess,
await_span,
E0728,
"`await` is only allowed inside `async` functions and blocks"
);
err.span_label(await_span, "only allowed inside `async` functions and blocks");
if let Some(item_sp) = self.current_item {
err.span_label(item_sp, "this is not `async`");
}
err.emit();
return hir::ExprKind::Err;
}
err.emit();
return hir::ExprKind::Err;
}
let span = self.mark_span_with_reason(
CompilerDesugaringKind::Await,
@ -5776,7 +5796,7 @@ impl<'a> LoweringContext<'a> {
let gen_future_span = self.mark_span_with_reason(
CompilerDesugaringKind::Await,
await_span,
Some(vec![sym::gen_future].into()),
self.allow_gen_future.clone(),
);
// let mut pinned = <expr>;
@ -5864,7 +5884,7 @@ impl<'a> LoweringContext<'a> {
let unit = self.expr_unit(span);
let yield_expr = P(self.expr(
span,
hir::ExprKind::Yield(P(unit)),
hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
ThinVec::new(),
));
self.stmt(span, hir::StmtKind::Expr(yield_expr))

View file

@ -1,6 +1,5 @@
use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
use crate::hir::{self, intravisit, HirId, ItemLocalId};
use syntax::ast::NodeId;
use crate::hir::itemlikevisit::ItemLikeVisitor;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{Lock, ParallelIterator, par_iter};
@ -27,19 +26,19 @@ pub fn check_crate<'hir>(hir_map: &hir::map::Map<'hir>) {
}
}
struct HirIdValidator<'a, 'hir: 'a> {
struct HirIdValidator<'a, 'hir> {
hir_map: &'a hir::map::Map<'hir>,
owner_def_index: Option<DefIndex>,
hir_ids_seen: FxHashSet<ItemLocalId>,
errors: &'a Lock<Vec<String>>,
}
struct OuterVisitor<'a, 'hir: 'a> {
struct OuterVisitor<'a, 'hir> {
hir_map: &'a hir::map::Map<'hir>,
errors: &'a Lock<Vec<String>>,
}
impl<'a, 'hir: 'a> OuterVisitor<'a, 'hir> {
impl<'a, 'hir> OuterVisitor<'a, 'hir> {
fn new_inner_visitor(&self,
hir_map: &'a hir::map::Map<'hir>)
-> HirIdValidator<'a, 'hir> {
@ -52,7 +51,7 @@ impl<'a, 'hir: 'a> OuterVisitor<'a, 'hir> {
}
}
impl<'a, 'hir: 'a> ItemLikeVisitor<'hir> for OuterVisitor<'a, 'hir> {
impl<'a, 'hir> ItemLikeVisitor<'hir> for OuterVisitor<'a, 'hir> {
fn visit_item(&mut self, i: &'hir hir::Item) {
let mut inner_visitor = self.new_inner_visitor(self.hir_map);
inner_visitor.check(i.hir_id, |this| intravisit::walk_item(this, i));
@ -69,7 +68,7 @@ impl<'a, 'hir: 'a> ItemLikeVisitor<'hir> for OuterVisitor<'a, 'hir> {
}
}
impl<'a, 'hir: 'a> HirIdValidator<'a, 'hir> {
impl<'a, 'hir> HirIdValidator<'a, 'hir> {
#[cold]
#[inline(never)]
fn error(&self, f: impl FnOnce() -> String) {
@ -112,19 +111,9 @@ impl<'a, 'hir: 'a> HirIdValidator<'a, 'hir> {
trace!("missing hir id {:#?}", hir_id);
// We are already in ICE mode here, so doing a linear search
// should be fine.
let (node_id, _) = self.hir_map
.definitions()
.node_to_hir_id
.iter()
.enumerate()
.find(|&(_, &entry)| hir_id == entry)
.expect("no node_to_hir_id entry");
let node_id = NodeId::from_usize(node_id);
missing_items.push(format!("[local_id: {}, node:{}]",
local_id,
self.hir_map.node_to_string(node_id)));
self.hir_map.node_to_string(hir_id)));
}
self.error(|| format!(
"ItemLocalIds not assigned densely in {}. \
@ -138,13 +127,13 @@ impl<'a, 'hir: 'a> HirIdValidator<'a, 'hir> {
owner: owner_def_index,
local_id,
})
.map(|h| format!("({:?} {})", h, self.hir_map.hir_to_string(h)))
.map(|h| format!("({:?} {})", h, self.hir_map.node_to_string(h)))
.collect::<Vec<_>>()));
}
}
}
impl<'a, 'hir: 'a> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self)
-> intravisit::NestedVisitorMap<'this, 'hir> {
@ -156,14 +145,14 @@ impl<'a, 'hir: 'a> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
if hir_id == hir::DUMMY_HIR_ID {
self.error(|| format!("HirIdValidator: HirId {:?} is invalid",
self.hir_map.hir_to_string(hir_id)));
self.hir_map.node_to_string(hir_id)));
return;
}
if owner != hir_id.owner {
self.error(|| format!(
"HirIdValidator: The recorded owner of {} is {} instead of {}",
self.hir_map.hir_to_string(hir_id),
self.hir_map.node_to_string(hir_id),
self.hir_map.def_path(DefId::local(hir_id.owner)).to_string_no_crate(),
self.hir_map.def_path(DefId::local(owner)).to_string_no_crate()));
}

View file

@ -35,7 +35,7 @@ mod def_collector;
pub mod definitions;
mod hir_id_validator;
/// Represents an entry and its parent `NodeId`.
/// Represents an entry and its parent `HirId`.
#[derive(Copy, Clone, Debug)]
pub struct Entry<'hir> {
parent: HirId,
@ -51,11 +51,11 @@ impl<'hir> Entry<'hir> {
}
}
fn fn_decl(&self) -> Option<&FnDecl> {
fn fn_decl(&self) -> Option<&'hir FnDecl> {
match self.node {
Node::Item(ref item) => {
match item.node {
ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
ItemKind::Fn(ref fn_decl, _, _, _) => Some(fn_decl),
_ => None,
}
}
@ -76,7 +76,7 @@ impl<'hir> Entry<'hir> {
Node::Expr(ref expr) => {
match expr.node {
ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
_ => None,
}
}
@ -200,7 +200,7 @@ impl<'hir> Map<'hir> {
/// "reveals" the content of a node to the caller (who might not
/// otherwise have had access to those contents, and hence needs a
/// read recorded). If the function just returns a DefId or
/// NodeId, no actual content was returned, so no read is needed.
/// HirId, no actual content was returned, so no read is needed.
pub fn read(&self, hir_id: HirId) {
if let Some(entry) = self.lookup(hir_id) {
self.dep_graph.read_index(entry.dep_node);
@ -286,21 +286,11 @@ impl<'hir> Map<'hir> {
self.definitions.def_index_to_hir_id(def_index)
}
#[inline]
pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
self.definitions.def_index_to_node_id(def_index)
}
#[inline]
pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
}
#[inline]
pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
}
fn def_kind(&self, node_id: NodeId) -> Option<DefKind> {
let node = if let Some(node) = self.find(node_id) {
node
@ -422,42 +412,30 @@ impl<'hir> Map<'hir> {
self.forest.krate.body(id)
}
pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
let hir_id = self.node_to_hir_id(node_id);
self.fn_decl_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<FnDecl> {
pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl> {
if let Some(entry) = self.find_entry(hir_id) {
entry.fn_decl().cloned()
entry.fn_decl()
} else {
bug!("no entry for hir_id `{}`", hir_id)
}
}
/// Returns the `NodeId` that corresponds to the definition of
/// Returns the `HirId` that corresponds to the definition of
/// 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 { hir_id }: BodyId) -> NodeId {
pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
let parent = self.get_parent_node_by_hir_id(hir_id);
assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
self.hir_to_node_id(parent)
parent
}
pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
self.local_def_id(self.body_owner(id))
self.local_def_id_from_hir_id(self.body_owner(id))
}
/// Given a `NodeId`, returns the `BodyId` associated with it,
/// Given a `HirId`, returns the `BodyId` associated with it,
/// if the node is a body owner, otherwise returns `None`.
pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
let hir_id = self.node_to_hir_id(id);
self.maybe_body_owned_by_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn maybe_body_owned_by_by_hir_id(&self, hir_id: HirId) -> Option<BodyId> {
pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
if let Some(entry) = self.find_entry(hir_id) {
if self.dep_graph.is_fully_enabled() {
let hir_id_owner = hir_id.owner;
@ -473,19 +451,13 @@ impl<'hir> Map<'hir> {
/// Given a body owner's id, returns the `BodyId` associated with it.
pub fn body_owned_by(&self, id: HirId) -> BodyId {
self.maybe_body_owned_by_by_hir_id(id).unwrap_or_else(|| {
span_bug!(self.span_by_hir_id(id), "body_owned_by: {} has no associated body",
self.hir_to_string(id));
self.maybe_body_owned_by(id).unwrap_or_else(|| {
span_bug!(self.span(id), "body_owned_by: {} has no associated body",
self.node_to_string(id));
})
}
pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
let hir_id = self.node_to_hir_id(id);
self.body_owner_kind_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn body_owner_kind_by_hir_id(&self, id: HirId) -> BodyOwnerKind {
pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
match self.get_by_hir_id(id) {
Node::Item(&Item { node: ItemKind::Const(..), .. }) |
Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
@ -514,7 +486,7 @@ impl<'hir> Map<'hir> {
Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => id,
Node::GenericParam(_) => self.get_parent_node_by_hir_id(id),
_ => bug!("ty_param_owner: {} not a type parameter", self.hir_to_string(id))
_ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
}
}
@ -523,7 +495,7 @@ impl<'hir> Map<'hir> {
Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
Node::GenericParam(param) => param.name.ident().name,
_ => bug!("ty_param_name: {} not a type parameter", self.hir_to_string(id)),
_ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
}
}
@ -576,7 +548,7 @@ impl<'hir> Map<'hir> {
let module = &self.forest.krate.modules[&node_id];
for id in &module.items {
visitor.visit_item(self.expect_item_by_hir_id(*id));
visitor.visit_item(self.expect_item(*id));
}
for id in &module.trait_items {
@ -709,7 +681,7 @@ impl<'hir> Map<'hir> {
/// 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 `NodeId` we found. Note that reaching the crate root (`id == 0`),
/// last good `HirId` 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,
@ -745,7 +717,7 @@ impl<'hir> Map<'hir> {
}
}
/// Retrieves the `NodeId` for `id`'s enclosing method, unless there's a
/// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
/// `while` or `loop` before reaching it, as block tail returns are not
/// available in them.
///
@ -753,7 +725,7 @@ impl<'hir> Map<'hir> {
/// fn foo(x: usize) -> bool {
/// if x == 1 {
/// true // `get_return_block` gets passed the `id` corresponding
/// } else { // to this, it will return `foo`'s `NodeId`.
/// } else { // to this, it will return `foo`'s `HirId`.
/// false
/// }
/// }
@ -793,17 +765,10 @@ impl<'hir> Map<'hir> {
self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
}
/// Retrieves the `NodeId` for `id`'s parent item, or `id` itself if no
/// Retrieves the `HirId` 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.
pub fn get_parent(&self, id: NodeId) -> NodeId {
let hir_id = self.node_to_hir_id(id);
let parent_hir_id = self.get_parent_item(hir_id);
self.hir_to_node_id(parent_hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
match self.walk_parent_nodes(hir_id, |node| match *node {
Node::Item(_) |
@ -819,13 +784,7 @@ impl<'hir> Map<'hir> {
/// 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 {
let hir_id = self.node_to_hir_id(id);
self.get_module_parent_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn get_module_parent_by_hir_id(&self, id: HirId) -> DefId {
pub fn get_module_parent(&self, id: HirId) -> DefId {
self.local_def_id_from_hir_id(self.get_module_parent_node(id))
}
@ -901,23 +860,11 @@ impl<'hir> Map<'hir> {
Some(scope)
}
pub fn get_parent_did(&self, id: NodeId) -> DefId {
let hir_id = self.node_to_hir_id(id);
self.get_parent_did_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn get_parent_did_by_hir_id(&self, id: HirId) -> DefId {
pub fn get_parent_did(&self, id: HirId) -> DefId {
self.local_def_id_from_hir_id(self.get_parent_item(id))
}
pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
let hir_id = self.node_to_hir_id(id);
self.get_foreign_abi_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn get_foreign_abi_by_hir_id(&self, hir_id: HirId) -> Abi {
pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
let parent = self.get_parent_item(hir_id);
if let Some(entry) = self.find_entry(parent) {
if let Entry {
@ -927,33 +874,27 @@ impl<'hir> Map<'hir> {
return nm.abi;
}
}
bug!("expected foreign mod or inlined parent, found {}", self.hir_to_string(parent))
bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
}
pub fn expect_item(&self, id: NodeId) -> &'hir Item {
let hir_id = self.node_to_hir_id(id);
self.expect_item_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item {
pub fn expect_item(&self, id: HirId) -> &'hir Item {
match self.find_by_hir_id(id) { // read recorded by `find`
Some(Node::Item(item)) => item,
_ => bug!("expected item, found {}", self.hir_to_string(id))
_ => bug!("expected item, found {}", self.node_to_string(id))
}
}
pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
match self.find_by_hir_id(id) {
Some(Node::ImplItem(item)) => item,
_ => bug!("expected impl item, found {}", self.hir_to_string(id))
_ => bug!("expected impl item, found {}", self.node_to_string(id))
}
}
pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
match self.find_by_hir_id(id) {
Some(Node::TraitItem(item)) => item,
_ => bug!("expected trait item, found {}", self.hir_to_string(id))
_ => bug!("expected trait item, found {}", self.node_to_string(id))
}
}
@ -963,26 +904,26 @@ impl<'hir> Map<'hir> {
match i.node {
ItemKind::Struct(ref struct_def, _) |
ItemKind::Union(ref struct_def, _) => struct_def,
_ => bug!("struct ID bound to non-struct {}", self.hir_to_string(id))
_ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
}
}
Some(Node::Variant(variant)) => &variant.node.data,
Some(Node::Ctor(data)) => data,
_ => bug!("expected struct or variant, found {}", self.hir_to_string(id))
_ => bug!("expected struct or variant, found {}", self.node_to_string(id))
}
}
pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
match self.find_by_hir_id(id) {
Some(Node::Variant(variant)) => variant,
_ => bug!("expected variant, found {}", self.hir_to_string(id)),
_ => bug!("expected variant, found {}", self.node_to_string(id)),
}
}
pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
match self.find_by_hir_id(id) {
Some(Node::ForeignItem(item)) => item,
_ => bug!("expected foreign item, found {}", self.hir_to_string(id))
_ => bug!("expected foreign item, found {}", self.node_to_string(id))
}
}
@ -995,7 +936,7 @@ impl<'hir> Map<'hir> {
pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr {
match self.find_by_hir_id(id) { // read recorded by find
Some(Node::Expr(expr)) => expr,
_ => bug!("expected expr, found {}", self.hir_to_string(id))
_ => bug!("expected expr, found {}", self.node_to_string(id))
}
}
@ -1018,19 +959,13 @@ impl<'hir> Map<'hir> {
Node::GenericParam(param) => param.name.ident().name,
Node::Binding(&Pat { node: PatKind::Binding(_, _, l, _), .. }) => l.name,
Node::Ctor(..) => self.name_by_hir_id(self.get_parent_item(id)),
_ => bug!("no name for {}", self.hir_to_string(id))
_ => bug!("no name for {}", self.node_to_string(id))
}
}
/// Given a node ID, gets a list of attributes associated with the AST
/// corresponding to the node-ID.
pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
let hir_id = self.node_to_hir_id(id);
self.attrs_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn attrs_by_hir_id(&self, id: HirId) -> &'hir [ast::Attribute] {
pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
self.read(id); // reveals attributes on the node
let attrs = match self.find_entry(id).map(|entry| entry.node) {
Some(Node::Local(l)) => Some(&l.attrs[..]),
@ -1046,7 +981,7 @@ impl<'hir> Map<'hir> {
Some(Node::GenericParam(param)) => Some(&param.attrs[..]),
// Unit/tuple structs/variants take the attributes straight from
// the struct/variant definition.
Some(Node::Ctor(..)) => return self.attrs_by_hir_id(self.get_parent_item(id)),
Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
_ => None
};
@ -1093,13 +1028,7 @@ impl<'hir> Map<'hir> {
})
}
pub fn span(&self, id: NodeId) -> Span {
let hir_id = self.node_to_hir_id(id);
self.span_by_hir_id(hir_id)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn span_by_hir_id(&self, hir_id: HirId) -> Span {
pub fn span(&self, hir_id: HirId) -> Span {
self.read(hir_id); // reveals span from node
match self.find_entry(hir_id).map(|entry| entry.node) {
Some(Node::Item(item)) => item.span,
@ -1139,32 +1068,17 @@ impl<'hir> Map<'hir> {
}
pub fn span_if_local(&self, id: DefId) -> Option<Span> {
self.as_local_node_id(id).map(|id| self.span(id))
self.as_local_hir_id(id).map(|id| self.span(id))
}
pub fn node_to_string(&self, id: NodeId) -> String {
hir_id_to_string(self, self.node_to_hir_id(id), true)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn hir_to_string(&self, id: HirId) -> String {
pub fn node_to_string(&self, id: HirId) -> String {
hir_id_to_string(self, id, true)
}
pub fn node_to_user_string(&self, id: NodeId) -> String {
hir_id_to_string(self, self.node_to_hir_id(id), false)
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn hir_to_user_string(&self, id: HirId) -> String {
hir_id_to_string(self, id, false)
}
pub fn node_to_pretty_string(&self, id: NodeId) -> String {
print::to_string(self, |s| s.print_node(self.get(id)))
}
// FIXME(@ljedrz): replace the `NodeId` variant.
pub fn hir_to_pretty_string(&self, id: HirId) -> String {
print::to_string(self, |s| s.print_node(self.get_by_hir_id(id)))
}
@ -1307,7 +1221,7 @@ pub fn map_crate<'hir>(sess: &crate::session::Session,
impl<'hir> print::PpAnn for Map<'hir> {
fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
match nested {
Nested::Item(id) => state.print_item(self.expect_item_by_hir_id(id.id)),
Nested::Item(id) => state.print_item(self.expect_item(id.id)),
Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
Nested::Body(id) => state.print_expr(&self.body(id).value),

View file

@ -155,7 +155,7 @@ pub const DUMMY_HIR_ID: HirId = HirId {
pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
pub struct Lifetime {
pub hir_id: HirId,
pub span: Span,
@ -295,7 +295,7 @@ impl Lifetime {
/// A `Path` is essentially Rust's notion of a name; for instance,
/// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
/// along with a bunch of supporting information.
#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
#[derive(RustcEncodable, RustcDecodable, HashStable)]
pub struct Path {
pub span: Span,
/// The resolution for the path.
@ -324,7 +324,7 @@ impl fmt::Display for Path {
/// A segment of a path: an identifier, an optional lifetime, and a set of
/// types.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct PathSegment {
/// The identifier portion of this path segment.
#[stable_hasher(project(name))]
@ -383,27 +383,23 @@ impl PathSegment {
}
}
// FIXME: hack required because you can't create a static
// `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
{
let dummy = GenericArgs::none();
f(if let Some(ref args) = self.args {
&args
pub fn generic_args(&self) -> &GenericArgs {
if let Some(ref args) = self.args {
args
} else {
&dummy
})
const DUMMY: &GenericArgs = &GenericArgs::none();
DUMMY
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct ConstArg {
pub value: AnonConst,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum GenericArg {
Lifetime(Lifetime),
Type(Ty),
@ -435,7 +431,7 @@ impl GenericArg {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct GenericArgs {
/// The generic arguments for this path segment.
pub args: HirVec<GenericArg>,
@ -449,7 +445,7 @@ pub struct GenericArgs {
}
impl GenericArgs {
pub fn none() -> Self {
pub const fn none() -> Self {
Self {
args: HirVec::new(),
bindings: HirVec::new(),
@ -509,7 +505,7 @@ pub enum TraitBoundModifier {
/// `typeck::collect::compute_bounds` matches these against
/// the "special" built-in traits (see `middle::lang_items`) and
/// detects `Copy`, `Send` and `Sync`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum GenericBound {
Trait(PolyTraitRef, TraitBoundModifier),
Outlives(Lifetime),
@ -545,7 +541,7 @@ pub enum LifetimeParamKind {
Error,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum GenericParamKind {
/// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
Lifetime {
@ -560,7 +556,7 @@ pub enum GenericParamKind {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct GenericParam {
pub hir_id: HirId,
pub name: ParamName,
@ -580,7 +576,7 @@ pub struct GenericParamCount {
/// Represents lifetimes and type parameters attached to a declaration
/// of a function, enum, trait, etc.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Generics {
pub params: HirVec<GenericParam>,
pub where_clause: WhereClause,
@ -588,12 +584,12 @@ pub struct Generics {
}
impl Generics {
pub fn empty() -> Generics {
pub const fn empty() -> Generics {
Generics {
params: HirVec::new(),
where_clause: WhereClause {
hir_id: DUMMY_HIR_ID,
predicates: HirVec::new(),
span: DUMMY_SP,
},
span: DUMMY_SP,
}
@ -642,26 +638,25 @@ pub enum SyntheticTyParamKind {
}
/// A where-clause in a definition.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct WhereClause {
pub hir_id: HirId,
pub predicates: HirVec<WherePredicate>,
// Only valid if predicates isn't empty.
span: Span,
}
impl WhereClause {
pub fn span(&self) -> Option<Span> {
self.predicates.iter().map(|predicate| predicate.span())
.fold(None, |acc, i| match (acc, i) {
(None, i) => Some(i),
(Some(acc), i) => {
Some(acc.to(i))
}
})
if self.predicates.is_empty() {
None
} else {
Some(self.span)
}
}
}
/// A single predicate in a where-clause.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum WherePredicate {
/// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
BoundPredicate(WhereBoundPredicate),
@ -682,7 +677,7 @@ impl WherePredicate {
}
/// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct WhereBoundPredicate {
pub span: Span,
/// Any generics from a `for` binding.
@ -694,7 +689,7 @@ pub struct WhereBoundPredicate {
}
/// A lifetime predicate (e.g., `'a: 'b + 'c`).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
@ -702,7 +697,7 @@ pub struct WhereRegionPredicate {
}
/// An equality predicate (e.g., `T = int`); currently unsupported.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct WhereEqPredicate {
pub hir_id: HirId,
pub span: Span,
@ -710,7 +705,7 @@ pub struct WhereEqPredicate {
pub rhs_ty: P<Ty>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct ModuleItems {
// Use BTreeSets here so items are in the same order as in the
// list of all items in Crate
@ -725,7 +720,7 @@ pub struct ModuleItems {
/// For more details, see the [rustc guide].
///
/// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct Crate {
pub module: Mod,
pub attrs: HirVec<Attribute>,
@ -820,7 +815,7 @@ impl Crate {
/// A macro definition, in this crate or imported from another.
///
/// Not parsed directly, but created on macro import or `macro_rules!` expansion.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct MacroDef {
pub name: Name,
pub vis: Visibility,
@ -834,7 +829,7 @@ pub struct MacroDef {
/// A block of statements `{ .. }`, which may have a label (in this case the
/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
/// the `rules` being anything but `DefaultBlock`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Block {
/// Statements in a block.
pub stmts: HirVec<Stmt>,
@ -852,7 +847,7 @@ pub struct Block {
pub targeted_by_break: bool,
}
#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
#[derive(RustcEncodable, RustcDecodable, HashStable)]
pub struct Pat {
#[stable_hasher(ignore)]
pub hir_id: HirId,
@ -915,7 +910,7 @@ impl Pat {
/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
/// are treated the same as` x: x, y: ref y, z: ref mut z`,
/// except `is_shorthand` is true.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct FieldPat {
#[stable_hasher(ignore)]
pub hir_id: HirId,
@ -930,7 +925,7 @@ pub struct FieldPat {
/// Explicit binding annotations given in the HIR for a binding. Note
/// that this is not the final binding *mode* that we infer after type
/// inference.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum BindingAnnotation {
/// No binding annotation given: this means that the final binding mode
/// will depend on whether we have skipped through a `&` reference
@ -957,7 +952,7 @@ pub enum RangeEnd {
Excluded,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum PatKind {
/// Represents a wildcard pattern (i.e., `_`).
Wild,
@ -1002,8 +997,8 @@ pub enum PatKind {
Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum Mutability {
MutMutable,
MutImmutable,
@ -1019,7 +1014,7 @@ impl Mutability {
}
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
pub enum BinOpKind {
/// The `+` operator (addition).
Add,
@ -1153,7 +1148,7 @@ impl Into<ast::BinOpKind> for BinOpKind {
pub type BinOp = Spanned<BinOpKind>;
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
pub enum UnOp {
/// The `*` operator (deferencing).
UnDeref,
@ -1182,7 +1177,7 @@ impl UnOp {
}
/// A statement.
#[derive(Clone, RustcEncodable, RustcDecodable)]
#[derive(RustcEncodable, RustcDecodable)]
pub struct Stmt {
pub hir_id: HirId,
pub node: StmtKind,
@ -1197,7 +1192,7 @@ impl fmt::Debug for Stmt {
}
/// The contents of a statement.
#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
#[derive(RustcEncodable, RustcDecodable, HashStable)]
pub enum StmtKind {
/// A local (`let`) binding.
Local(P<Local>),
@ -1224,7 +1219,7 @@ impl StmtKind {
}
/// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Local {
pub pat: P<Pat>,
/// Type annotation, if any (otherwise the type will be inferred).
@ -1241,7 +1236,7 @@ pub struct Local {
/// Represents a single arm of a `match` expression, e.g.
/// `<pats> (if <guard>) => <body>`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Arm {
#[stable_hasher(ignore)]
pub hir_id: HirId,
@ -1255,12 +1250,12 @@ pub struct Arm {
pub body: P<Expr>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum Guard {
If(P<Expr>),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Field {
#[stable_hasher(ignore)]
pub hir_id: HirId,
@ -1270,7 +1265,7 @@ pub struct Field {
pub is_shorthand: bool,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum BlockCheckMode {
DefaultBlock,
UnsafeBlock(UnsafeSource),
@ -1278,7 +1273,7 @@ pub enum BlockCheckMode {
PopUnsafeBlock(UnsafeSource),
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum UnsafeSource {
CompilerGenerated,
UserProvided,
@ -1306,15 +1301,15 @@ pub struct BodyId {
///
/// - an `arguments` array containing the `(x, y)` pattern
/// - a `value` containing the `x + y` expression (maybe wrapped in a block)
/// - `is_generator` would be false
/// - `generator_kind` would be `None`
///
/// All bodies have an **owner**, which can be accessed via the HIR
/// map using `body_owner_def_id()`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct Body {
pub arguments: HirVec<Arg>,
pub value: Expr,
pub is_generator: bool,
pub generator_kind: Option<GeneratorKind>,
}
impl Body {
@ -1325,6 +1320,26 @@ impl Body {
}
}
/// The type of source expression that caused this generator to be created.
// Not `IsAsync` because we want to eventually add support for `AsyncGen`
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum GeneratorKind {
/// An `async` block or function.
Async,
/// A generator literal created via a `yield` inside a closure.
Gen,
}
impl fmt::Display for GeneratorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
GeneratorKind::Async => "`async` object",
GeneratorKind::Gen => "generator",
})
}
}
#[derive(Copy, Clone, Debug)]
pub enum BodyOwnerKind {
/// Functions and methods.
@ -1364,7 +1379,7 @@ pub struct AnonConst {
}
/// An expression
#[derive(Clone, RustcEncodable, RustcDecodable)]
#[derive(RustcEncodable, RustcDecodable)]
pub struct Expr {
pub span: Span,
pub node: ExprKind,
@ -1475,7 +1490,7 @@ impl fmt::Debug for Expr {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum ExprKind {
/// A `box x` expression.
Box(P<Expr>),
@ -1531,8 +1546,8 @@ pub enum ExprKind {
///
/// The final span is the span of the argument block `|...|`.
///
/// This may also be a generator literal, indicated by the final boolean,
/// in that case there is an `GeneratorClause`.
/// This may also be a generator literal or an `async block` as indicated by the
/// `Option<GeneratorMovability>`.
Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
/// A block (e.g., `'label: { ... }`).
Block(P<Block>, Option<Label>),
@ -1576,14 +1591,14 @@ pub enum ExprKind {
Repeat(P<Expr>, AnonConst),
/// A suspension point for generators (i.e., `yield <expr>`).
Yield(P<Expr>),
Yield(P<Expr>, YieldSource),
/// A placeholder for an expression that wasn't syntactically well formed in some way.
Err,
}
/// Represents an optionally `Self`-qualified value/type path or associated extension.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum QPath {
/// Path to a definition, optionally "fully-qualified" with a `Self`
/// type, if the path points to an associated item in a trait.
@ -1603,7 +1618,7 @@ pub enum QPath {
}
/// Hints at the original code for a let statement.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum LocalSource {
/// A `match _ { .. }`.
Normal,
@ -1625,7 +1640,7 @@ pub enum LocalSource {
}
/// Hints at the original code for a `match _ { .. }`.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
pub enum MatchSource {
/// A `match _ { .. }`.
Normal,
@ -1649,7 +1664,7 @@ pub enum MatchSource {
}
/// The loop type that yielded an `ExprKind::Loop`.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum LoopSource {
/// A `loop { .. }` loop.
Loop,
@ -1659,7 +1674,7 @@ pub enum LoopSource {
ForLoop,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum LoopIdError {
OutsideLoopScope,
UnlabeledCfInWhileCondition,
@ -1668,16 +1683,16 @@ pub enum LoopIdError {
impl fmt::Display for LoopIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(match *self {
f.write_str(match self {
LoopIdError::OutsideLoopScope => "not inside loop scope",
LoopIdError::UnlabeledCfInWhileCondition =>
"unlabeled control flow (break or continue) in while condition",
LoopIdError::UnresolvedLabel => "label not found",
}, f)
})
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Destination {
// This is `Some(_)` iff there is an explicit user-specified `label
pub label: Option<Label>,
@ -1687,14 +1702,35 @@ pub struct Destination {
pub target_id: Result<HirId, LoopIdError>,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
/// Whether a generator contains self-references, causing it to be `!Unpin`.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum GeneratorMovability {
/// May contain self-references, `!Unpin`.
Static,
/// Must not contain self-references, `Unpin`.
Movable,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
/// The yield kind that caused an `ExprKind::Yield`.
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
pub enum YieldSource {
/// An `<expr>.await`.
Await,
/// A plain `yield`.
Yield,
}
impl fmt::Display for YieldSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
YieldSource::Await => "`await`",
YieldSource::Yield => "`yield`",
})
}
}
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum CaptureClause {
CaptureByValue,
CaptureByRef,
@ -1702,14 +1738,14 @@ pub enum CaptureClause {
// 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, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct MutTy {
pub ty: P<Ty>,
pub mutbl: Mutability,
}
/// Represents a method's signature in a trait declaration or implementation.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct MethodSig {
pub header: FnHeader,
pub decl: P<FnDecl>,
@ -1727,7 +1763,7 @@ pub struct TraitItemId {
/// possibly including a default implementation. A trait item is
/// either required (meaning it doesn't have an implementation, just a
/// signature) or provided (meaning it has a default implementation).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct TraitItem {
pub ident: Ident,
pub hir_id: HirId,
@ -1738,7 +1774,7 @@ pub struct TraitItem {
}
/// Represents a trait method's body (or just argument names).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum TraitMethod {
/// No default body in the trait, just a signature.
Required(HirVec<Ident>),
@ -1748,7 +1784,7 @@ pub enum TraitMethod {
}
/// Represents a trait method or associated constant or type
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum TraitItemKind {
/// An associated constant with an optional value (otherwise `impl`s must contain a value).
Const(P<Ty>, Option<BodyId>),
@ -1768,7 +1804,7 @@ pub struct ImplItemId {
}
/// Represents anything within an `impl` block
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct ImplItem {
pub ident: Ident,
pub hir_id: HirId,
@ -1781,7 +1817,7 @@ pub struct ImplItem {
}
/// Represents various kinds of content within an `impl`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum ImplItemKind {
/// An associated constant of the given type, set to the constant result
/// of the expression
@ -1808,7 +1844,7 @@ pub enum ImplItemKind {
/// Binding(...),
/// }
/// ```
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct TypeBinding {
pub hir_id: HirId,
#[stable_hasher(project(name))]
@ -1818,7 +1854,7 @@ pub struct TypeBinding {
}
// Represents the two kinds of type bindings.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum TypeBindingKind {
/// E.g., `Foo<Bar: Send>`.
Constraint {
@ -1839,7 +1875,7 @@ impl TypeBinding {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
#[derive(RustcEncodable, RustcDecodable)]
pub struct Ty {
pub hir_id: HirId,
pub node: TyKind,
@ -1854,7 +1890,7 @@ impl fmt::Debug for Ty {
}
/// Not represented directly in the AST; referred to by name through a `ty_path`.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
pub enum PrimTy {
Int(IntTy),
Uint(UintTy),
@ -1864,7 +1900,7 @@ pub enum PrimTy {
Char,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct BareFnTy {
pub unsafety: Unsafety,
pub abi: Abi,
@ -1873,7 +1909,7 @@ pub struct BareFnTy {
pub arg_names: HirVec<Ident>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct ExistTy {
pub generics: Generics,
pub bounds: GenericBounds,
@ -1893,7 +1929,7 @@ pub enum ExistTyOrigin {
}
/// The various kinds of types recognized by the compiler.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum TyKind {
/// A variable length slice (i.e., `[T]`).
Slice(P<Ty>),
@ -1930,12 +1966,12 @@ pub enum TyKind {
Infer,
/// Placeholder for a type that has failed to be defined.
Err,
/// Placeholder for C-variadic arguments. We "spoof" the `VaList` created
/// Placeholder for C-variadic arguments. We "spoof" the `VaListImpl` created
/// from the variadic arguments. This type is only valid up to typeck.
CVarArgs(Lifetime),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct InlineAsmOutput {
pub constraint: Symbol,
pub is_rw: bool,
@ -1958,14 +1994,14 @@ pub struct InlineAsm {
}
/// Represents an argument in a function header.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct Arg {
pub pat: P<Pat>,
pub hir_id: HirId,
}
/// Represents the header (not the body) of a function declaration.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct FnDecl {
/// The types of the function's arguments.
///
@ -1978,7 +2014,7 @@ pub struct FnDecl {
}
/// Represents what type of implicit self a function has, if any.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum ImplicitSelfKind {
/// Represents a `fn x(self);`.
Imm,
@ -2058,11 +2094,10 @@ impl Defaultness {
impl fmt::Display for Unsafety {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(match *self {
Unsafety::Normal => "normal",
Unsafety::Unsafe => "unsafe",
},
f)
f.write_str(match self {
Unsafety::Normal => "normal",
Unsafety::Unsafe => "unsafe",
})
}
}
@ -2076,15 +2111,15 @@ pub enum ImplPolarity {
impl fmt::Debug for ImplPolarity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ImplPolarity::Positive => "positive".fmt(f),
ImplPolarity::Negative => "negative".fmt(f),
}
f.write_str(match self {
ImplPolarity::Positive => "positive",
ImplPolarity::Negative => "negative",
})
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum FunctionRetTy {
/// Return type is not specified.
///
@ -2114,7 +2149,7 @@ impl FunctionRetTy {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct Mod {
/// A span from the first token past `{` to the last token until `}`.
/// For `mod foo;`, the inner span ranges from the first token
@ -2123,25 +2158,25 @@ pub struct Mod {
pub item_ids: HirVec<ItemId>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct ForeignMod {
pub abi: Abi,
pub items: HirVec<ForeignItem>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct GlobalAsm {
pub asm: Symbol,
#[stable_hasher(ignore)] // This is used for error reporting
pub ctxt: SyntaxContext,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct EnumDef {
pub variants: HirVec<Variant>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct VariantKind {
/// Name of the variant.
#[stable_hasher(project(name))]
@ -2177,10 +2212,10 @@ pub enum UseKind {
/// References to traits in impls.
///
/// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
/// that the `ref_id` is for. Note that `ref_id`'s value is not the `NodeId` of the
/// trait being referred to but just a unique `NodeId` that serves as a key
/// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
/// trait being referred to but just a unique `HirId` that serves as a key
/// within the resolution map.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct TraitRef {
pub path: Path,
// Don't hash the ref_id. It is tracked via the thing it is used to access
@ -2202,7 +2237,7 @@ impl TraitRef {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct PolyTraitRef {
/// The `'a` in `<'a> Foo<&'a T>`.
pub bound_generic_params: HirVec<GenericParam>,
@ -2215,7 +2250,7 @@ pub struct PolyTraitRef {
pub type Visibility = Spanned<VisibilityKind>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub enum VisibilityKind {
Public,
Crate(CrateSugar),
@ -2250,7 +2285,7 @@ impl VisibilityKind {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct StructField {
pub span: Span,
#[stable_hasher(project(name))]
@ -2270,7 +2305,7 @@ impl StructField {
}
/// Fields and constructor IDs of enum variants and structs.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum VariantData {
/// A struct variant.
///
@ -2315,7 +2350,7 @@ pub struct ItemId {
/// An item
///
/// The name might be a dummy name in case of anonymous items
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct Item {
pub ident: Ident,
pub hir_id: HirId,
@ -2325,7 +2360,7 @@ pub struct Item {
pub span: Span,
}
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct FnHeader {
pub unsafety: Unsafety,
pub constness: Constness,
@ -2342,7 +2377,7 @@ impl FnHeader {
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum ItemKind {
/// An `extern crate` item, with optional *original* crate name if the crate was renamed.
///
@ -2445,7 +2480,7 @@ impl ItemKind {
/// type or method, and whether it is public). This allows other
/// passes to find the impl they want without loading the ID (which
/// means fewer edges in the incremental compilation graph).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct TraitItemRef {
pub id: TraitItemId,
#[stable_hasher(project(name))]
@ -2461,7 +2496,7 @@ pub struct TraitItemRef {
/// type or method, and whether it is public). This allows other
/// passes to find the impl they want without loading the ID (which
/// means fewer edges in the incremental compilation graph).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct ImplItemRef {
pub id: ImplItemId,
#[stable_hasher(project(name))]
@ -2480,7 +2515,7 @@ pub enum AssocItemKind {
Existential,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct ForeignItem {
#[stable_hasher(project(name))]
pub ident: Ident,
@ -2492,7 +2527,7 @@ pub struct ForeignItem {
}
/// An item within an `extern` block.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub enum ForeignItemKind {
/// A foreign function.
Fn(P<FnDecl>, HirVec<Ident>, Generics),

View file

@ -625,10 +625,10 @@ impl<'a> State<'a> {
self.word_space("for ?")?;
self.print_trait_ref(&ptr.trait_ref)?;
} else {
real_bounds.push(b.clone());
real_bounds.push(b);
}
}
self.print_bounds(":", &real_bounds[..])?;
self.print_bounds(":", real_bounds)?;
self.s.word(";")?;
self.end()?; // end the outer ibox
}
@ -698,10 +698,10 @@ impl<'a> State<'a> {
self.word_space("for ?")?;
self.print_trait_ref(&ptr.trait_ref)?;
} else {
real_bounds.push(b.clone());
real_bounds.push(b);
}
}
self.print_bounds(":", &real_bounds[..])?;
self.print_bounds(":", real_bounds)?;
self.print_where_clause(&generics.where_clause)?;
self.s.word(" ")?;
self.bopen()?;
@ -724,11 +724,11 @@ impl<'a> State<'a> {
self.word_space("for ?")?;
self.print_trait_ref(&ptr.trait_ref)?;
} else {
real_bounds.push(b.clone());
real_bounds.push(b);
}
}
self.nbsp()?;
self.print_bounds("=", &real_bounds[..])?;
self.print_bounds("=", real_bounds)?;
self.print_where_clause(&generics.where_clause)?;
self.s.word(";")?;
}
@ -1194,12 +1194,11 @@ impl<'a> State<'a> {
self.s.word(".")?;
self.print_ident(segment.ident)?;
segment.with_generic_args(|generic_args| {
if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
return self.print_generic_args(&generic_args, segment.infer_args, true);
}
Ok(())
})?;
let generic_args = segment.generic_args();
if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
self.print_generic_args(generic_args, segment.infer_args, true)?;
}
self.print_call_post(base_args)
}
@ -1501,7 +1500,7 @@ impl<'a> State<'a> {
self.pclose()?;
}
hir::ExprKind::Yield(ref expr) => {
hir::ExprKind::Yield(ref expr, _) => {
self.word_space("yield")?;
self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
}
@ -1559,11 +1558,9 @@ impl<'a> State<'a> {
self.s.word("::")?
}
if segment.ident.name != kw::PathRoot {
self.print_ident(segment.ident)?;
segment.with_generic_args(|generic_args| {
self.print_generic_args(generic_args, segment.infer_args,
colons_before_params)
})?;
self.print_ident(segment.ident)?;
self.print_generic_args(segment.generic_args(), segment.infer_args,
colons_before_params)?;
}
}
@ -1572,10 +1569,8 @@ impl<'a> State<'a> {
pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
if segment.ident.name != kw::PathRoot {
self.print_ident(segment.ident)?;
segment.with_generic_args(|generic_args| {
self.print_generic_args(generic_args, segment.infer_args, false)
})?;
self.print_ident(segment.ident)?;
self.print_generic_args(segment.generic_args(), segment.infer_args, false)?;
}
Ok(())
}
@ -1600,11 +1595,9 @@ impl<'a> State<'a> {
}
if segment.ident.name != kw::PathRoot {
self.print_ident(segment.ident)?;
segment.with_generic_args(|generic_args| {
self.print_generic_args(generic_args,
segment.infer_args,
colons_before_params)
})?;
self.print_generic_args(segment.generic_args(),
segment.infer_args,
colons_before_params)?;
}
}
@ -1612,11 +1605,9 @@ impl<'a> State<'a> {
self.s.word("::")?;
let item_segment = path.segments.last().unwrap();
self.print_ident(item_segment.ident)?;
item_segment.with_generic_args(|generic_args| {
self.print_generic_args(generic_args,
item_segment.infer_args,
colons_before_params)
})
self.print_generic_args(item_segment.generic_args(),
item_segment.infer_args,
colons_before_params)
}
hir::QPath::TypeRelative(ref qself, ref item_segment) => {
self.s.word("<")?;
@ -1624,11 +1615,9 @@ impl<'a> State<'a> {
self.s.word(">")?;
self.s.word("::")?;
self.print_ident(item_segment.ident)?;
item_segment.with_generic_args(|generic_args| {
self.print_generic_args(generic_args,
item_segment.infer_args,
colons_before_params)
})
self.print_generic_args(item_segment.generic_args(),
item_segment.infer_args,
colons_before_params)
}
}
}
@ -2009,31 +1998,34 @@ impl<'a> State<'a> {
}
}
pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
-> io::Result<()> {
if !bounds.is_empty() {
self.s.word(prefix)?;
let mut first = true;
for bound in bounds {
if !(first && prefix.is_empty()) {
self.nbsp()?;
}
if first {
first = false;
} else {
self.word_space("+")?;
}
pub fn print_bounds<'b>(
&mut self,
prefix: &'static str,
bounds: impl IntoIterator<Item = &'b hir::GenericBound>,
) -> io::Result<()> {
let mut first = true;
for bound in bounds {
if first {
self.s.word(prefix)?;
}
if !(first && prefix.is_empty()) {
self.nbsp()?;
}
if first {
first = false;
} else {
self.word_space("+")?;
}
match bound {
GenericBound::Trait(tref, modifier) => {
if modifier == &TraitBoundModifier::Maybe {
self.s.word("?")?;
}
self.print_poly_trait_ref(tref)?;
}
GenericBound::Outlives(lt) => {
self.print_lifetime(lt)?;
match bound {
GenericBound::Trait(tref, modifier) => {
if modifier == &TraitBoundModifier::Maybe {
self.s.word("?")?;
}
self.print_poly_trait_ref(tref)?;
}
GenericBound::Outlives(lt) => {
self.print_lifetime(lt)?;
}
}
}
@ -2202,8 +2194,8 @@ impl<'a> State<'a> {
let generics = hir::Generics {
params: hir::HirVec::new(),
where_clause: hir::WhereClause {
hir_id: hir::DUMMY_HIR_ID,
predicates: hir::HirVec::new(),
span: syntax_pos::DUMMY_SP,
},
span: syntax_pos::DUMMY_SP,
};

View file

@ -14,8 +14,8 @@ pub fn provide(providers: &mut Providers<'_>) {
return None;
}
let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
let body = tcx.hir().body(tcx.hir().maybe_body_owned_by(node_id)?);
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
let body = tcx.hir().body(tcx.hir().maybe_body_owned_by(hir_id)?);
let mut local_collector = LocalCollector::default();
local_collector.visit_body(body);

View file

@ -335,15 +335,15 @@ impl<'a> HashStable<StableHashingContext<'a>> for hir::Body {
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
let hir::Body {
ref arguments,
ref value,
is_generator,
} = *self;
arguments,
value,
generator_kind,
} = self;
hcx.with_node_id_hashing_mode(NodeIdHashingMode::Ignore, |hcx| {
arguments.hash_stable(hcx, hasher);
value.hash_stable(hcx, hasher);
is_generator.hash_stable(hcx, hasher);
generator_kind.hash_stable(hcx, hasher);
});
}
}

View file

@ -391,10 +391,17 @@ impl_stable_hash_for!(enum ::syntax::ast::MetaItemKind {
NameValue(lit)
});
impl_stable_hash_for!(enum ::syntax_pos::hygiene::Transparency {
Transparent,
SemiTransparent,
Opaque,
});
impl_stable_hash_for!(struct ::syntax_pos::hygiene::ExpnInfo {
call_site,
def_site,
format,
def_site,
default_transparency,
allow_internal_unstable,
allow_internal_unsafe,
local_inner_macros,

View file

@ -30,13 +30,13 @@ use super::*;
use crate::ty::Const;
use crate::ty::relate::{Relate, TypeRelation};
pub struct At<'a, 'tcx: 'a> {
pub struct At<'a, 'tcx> {
pub infcx: &'a InferCtxt<'a, 'tcx>,
pub cause: &'a ObligationCause<'tcx>,
pub param_env: ty::ParamEnv<'tcx>,
}
pub struct Trace<'a, 'tcx: 'a> {
pub struct Trace<'a, 'tcx> {
at: At<'a, 'tcx>,
a_is_expected: bool,
trace: TypeTrace<'tcx>,

View file

@ -14,7 +14,7 @@ use crate::mir::interpret::ConstValue;
use std::sync::atomic::Ordering;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::subst::Kind;
use crate::ty::{self, BoundVar, InferConst, Lift, List, Ty, TyCtxt, TypeFlags};
use crate::ty::{self, BoundVar, InferConst, List, Ty, TyCtxt, TypeFlags};
use crate::ty::flags::FlagComputation;
use rustc_data_structures::fx::FxHashMap;
@ -43,7 +43,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
query_state: &mut OriginalQueryValues<'tcx>,
) -> Canonicalized<'tcx, V>
where
V: TypeFoldable<'tcx> + Lift<'tcx>,
V: TypeFoldable<'tcx>,
{
self.tcx
.sess
@ -87,7 +87,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
/// [c]: https://rust-lang.github.io/rustc-guide/traits/canonicalization.html#canonicalizing-the-query-result
pub fn canonicalize_response<V>(&self, value: &V) -> Canonicalized<'tcx, V>
where
V: TypeFoldable<'tcx> + Lift<'tcx>,
V: TypeFoldable<'tcx>,
{
let mut query_state = OriginalQueryValues::default();
Canonicalizer::canonicalize(
@ -101,7 +101,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
pub fn canonicalize_user_type_annotation<V>(&self, value: &V) -> Canonicalized<'tcx, V>
where
V: TypeFoldable<'tcx> + Lift<'tcx>,
V: TypeFoldable<'tcx>,
{
let mut query_state = OriginalQueryValues::default();
Canonicalizer::canonicalize(
@ -132,7 +132,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
query_state: &mut OriginalQueryValues<'tcx>,
) -> Canonicalized<'tcx, V>
where
V: TypeFoldable<'tcx> + Lift<'tcx>,
V: TypeFoldable<'tcx>,
{
self.tcx
.sess
@ -275,7 +275,7 @@ impl CanonicalizeRegionMode for CanonicalizeFreeRegionsOtherThanStatic {
}
}
struct Canonicalizer<'cx, 'tcx: 'cx> {
struct Canonicalizer<'cx, 'tcx> {
infcx: Option<&'cx InferCtxt<'cx, 'tcx>>,
tcx: TyCtxt<'tcx>,
variables: SmallVec<[CanonicalVarInfo; 8]>,
@ -506,7 +506,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> {
query_state: &mut OriginalQueryValues<'tcx>,
) -> Canonicalized<'tcx, V>
where
V: TypeFoldable<'tcx> + Lift<'tcx>,
V: TypeFoldable<'tcx>,
{
let needs_canonical_flags = if canonicalize_region_mode.any() {
TypeFlags::KEEP_IN_LOCAL_TCX |
@ -520,20 +520,12 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> {
TypeFlags::HAS_CT_PLACEHOLDER
};
let gcx = tcx.global_tcx();
// Fast path: nothing that needs to be canonicalized.
if !value.has_type_flags(needs_canonical_flags) {
let out_value = gcx.lift(value).unwrap_or_else(|| {
bug!(
"failed to lift `{:?}` (nothing to canonicalize)",
value
)
});
let canon_value = Canonical {
max_universe: ty::UniverseIndex::ROOT,
variables: List::empty(),
value: out_value,
value: value.clone(),
};
return canon_value;
}
@ -553,13 +545,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> {
// Once we have canonicalized `out_value`, it should not
// contain anything that ties it to this inference context
// anymore, so it should live in the global arena.
let out_value = gcx.lift(&out_value).unwrap_or_else(|| {
bug!(
"failed to lift `{:?}`, canonicalized from `{:?}`",
out_value,
value
)
});
debug_assert!(!out_value.has_type_flags(TypeFlags::KEEP_IN_LOCAL_TCX));
let canonical_variables = tcx.intern_canonical_var_infos(&canonicalizer.variables);

View file

@ -194,10 +194,10 @@ pub struct QueryResponse<'tcx, R> {
pub value: R,
}
pub type Canonicalized<'tcx, V> = Canonical<'tcx, <V as Lift<'tcx>>::Lifted>;
pub type Canonicalized<'tcx, V> = Canonical<'tcx, V>;
pub type CanonicalizedQueryResponse<'tcx, T> =
&'tcx Canonical<'tcx, QueryResponse<'tcx, <T as Lift<'tcx>>::Lifted>>;
&'tcx Canonical<'tcx, QueryResponse<'tcx, T>>;
/// Indicates whether or not we were able to prove the query to be
/// true.

View file

@ -26,7 +26,7 @@ use crate::traits::TraitEngine;
use crate::traits::{Obligation, ObligationCause, PredicateObligation};
use crate::ty::fold::TypeFoldable;
use crate::ty::subst::{Kind, UnpackedKind};
use crate::ty::{self, BoundVar, InferConst, Lift, Ty, TyCtxt};
use crate::ty::{self, BoundVar, InferConst, Ty, TyCtxt};
use crate::util::captures::Captures;
impl<'tcx> InferCtxtBuilder<'tcx> {
@ -53,8 +53,8 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
where
K: TypeFoldable<'tcx>,
R: Debug + Lift<'tcx> + TypeFoldable<'tcx>,
Canonical<'tcx, <QueryResponse<'tcx, R> as Lift<'tcx>>::Lifted>: ArenaAllocatable,
R: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable,
{
self.enter_with_canonical(
DUMMY_SP,
@ -99,8 +99,8 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
fulfill_cx: &mut dyn TraitEngine<'tcx>,
) -> Fallible<CanonicalizedQueryResponse<'tcx, T>>
where
T: Debug + Lift<'tcx> + TypeFoldable<'tcx>,
Canonical<'tcx, <QueryResponse<'tcx, T> as Lift<'tcx>>::Lifted>: ArenaAllocatable,
T: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable,
{
let query_response = self.make_query_response(inference_vars, answer, fulfill_cx)?;
let canonical_result = self.canonicalize_response(&query_response);
@ -126,9 +126,9 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
&self,
inference_vars: CanonicalVarValues<'tcx>,
answer: T,
) -> Canonical<'tcx, QueryResponse<'tcx, <T as Lift<'tcx>>::Lifted>>
) -> Canonical<'tcx, QueryResponse<'tcx, T>>
where
T: Debug + Lift<'tcx> + TypeFoldable<'tcx>,
T: Debug + TypeFoldable<'tcx>,
{
self.canonicalize_response(&QueryResponse {
var_values: inference_vars,
@ -147,7 +147,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
fulfill_cx: &mut dyn TraitEngine<'tcx>,
) -> Result<QueryResponse<'tcx, T>, NoSolution>
where
T: Debug + TypeFoldable<'tcx> + Lift<'tcx>,
T: Debug + TypeFoldable<'tcx>,
{
let tcx = self.tcx;

View file

@ -44,7 +44,7 @@ use syntax::ast;
use syntax_pos::{Span, DUMMY_SP};
#[derive(Clone)]
pub struct CombineFields<'infcx, 'tcx: 'infcx> {
pub struct CombineFields<'infcx, 'tcx> {
pub infcx: &'infcx InferCtxt<'infcx, 'tcx>,
pub trace: TypeTrace<'tcx>,
pub cause: Option<ty::relate::Cause>,
@ -355,7 +355,7 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
}
}
struct Generalizer<'cx, 'tcx: 'cx> {
struct Generalizer<'cx, 'tcx> {
infcx: &'cx InferCtxt<'cx, 'tcx>,
/// The span, used when creating new type variables and things.

View file

@ -11,7 +11,7 @@ use crate::mir::interpret::ConstValue;
use crate::infer::unify_key::replace_if_possible;
/// Ensures `a` is made equal to `b`. Returns `a` on success.
pub struct Equate<'combine, 'infcx: 'combine, 'tcx: 'infcx> {
pub struct Equate<'combine, 'infcx, 'tcx> {
fields: &'combine mut CombineFields<'infcx, 'tcx>,
a_is_expected: bool,
}

View file

@ -86,7 +86,7 @@ impl<'tcx> TyCtxt<'tcx> {
)
};
let span = scope.span(self, region_scope_tree);
let tag = match self.hir().find(scope.node_id(self, region_scope_tree)) {
let tag = match self.hir().find_by_hir_id(scope.hir_id(region_scope_tree)) {
Some(Node::Block(_)) => "block",
Some(Node::Expr(expr)) => match expr.node {
hir::ExprKind::Call(..) => "call",
@ -191,7 +191,7 @@ impl<'tcx> TyCtxt<'tcx> {
};
let (prefix, span) = match *region {
ty::ReEarlyBound(ref br) => {
let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
let mut sp = cm.def_span(self.hir().span(node));
if let Some(param) = self.hir()
.get_generics(scope)
.and_then(|generics| generics.get_named(br.name))
@ -204,7 +204,7 @@ impl<'tcx> TyCtxt<'tcx> {
bound_region: ty::BoundRegion::BrNamed(_, name),
..
}) => {
let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
let mut sp = cm.def_span(self.hir().span(node));
if let Some(param) = self.hir()
.get_generics(scope)
.and_then(|generics| generics.get_named(name))
@ -216,11 +216,11 @@ impl<'tcx> TyCtxt<'tcx> {
ty::ReFree(ref fr) => match fr.bound_region {
ty::BrAnon(idx) => (
format!("the anonymous lifetime #{} defined on", idx + 1),
self.hir().span_by_hir_id(node),
self.hir().span(node),
),
_ => (
format!("the lifetime {} as defined on", region),
cm.def_span(self.hir().span_by_hir_id(node)),
cm.def_span(self.hir().span(node)),
),
},
_ => bug!(),
@ -1330,12 +1330,12 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
if !param.is_self() {
let type_param = generics.type_param(param, self.tcx);
let hir = &self.tcx.hir();
hir.as_local_node_id(type_param.def_id).map(|id| {
hir.as_local_hir_id(type_param.def_id).map(|id| {
// Get the `hir::Param` to verify whether it already has any bounds.
// We do this to avoid suggesting code that ends up as `T: 'a'b`,
// instead we suggest `T: 'a + 'b` in that case.
let mut has_bounds = false;
if let Node::GenericParam(ref param) = hir.get(id) {
if let Node::GenericParam(ref param) = hir.get_by_hir_id(id) {
has_bounds = !param.bounds.is_empty();
}
let sp = hir.span(id);

View file

@ -227,16 +227,15 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
pub fn need_type_info_err_in_generator(
&self,
kind: hir::GeneratorKind,
span: Span,
ty: Ty<'tcx>,
) -> DiagnosticBuilder<'tcx> {
let ty = self.resolve_vars_if_possible(&ty);
let name = self.extract_type_name(&ty, None);
let mut err = struct_span_err!(self.tcx.sess,
span,
E0698,
"type inside generator must be known in this context");
let mut err = struct_span_err!(
self.tcx.sess, span, E0698, "type inside {} must be known in this context", kind,
);
err.span_label(span, InferCtxt::missing_type_msg(&name));
err
}

View file

@ -28,8 +28,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
) -> Option<(&hir::Ty, &hir::FnDecl)> {
if let Some(anon_reg) = self.tcx().is_suitable_region(region) {
let def_id = anon_reg.def_id;
if let Some(node_id) = self.tcx().hir().as_local_node_id(def_id) {
let fndecl = match self.tcx().hir().get(node_id) {
if let Some(hir_id) = self.tcx().hir().as_local_hir_id(def_id) {
let fndecl = match self.tcx().hir().get_by_hir_id(hir_id) {
Node::Item(&hir::Item {
node: hir::ItemKind::Fn(ref fndecl, ..),
..

View file

@ -30,7 +30,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
}
}
pub struct NiceRegionError<'cx, 'tcx: 'cx> {
pub struct NiceRegionError<'cx, 'tcx> {
infcx: &'cx InferCtxt<'cx, 'tcx>,
error: Option<RegionResolutionError<'tcx>>,
regions: Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)>,

View file

@ -48,11 +48,11 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
if let (&SubregionOrigin::BindingTypeIsNotValidAtDecl(ref external_span),
&RegionKind::ReFree(ref free_region)) = (&sub_origin, sup_region) {
let hir = &self.tcx().hir();
if let Some(node_id) = hir.as_local_node_id(free_region.scope) {
if let Some(hir_id) = hir.as_local_hir_id(free_region.scope) {
if let Node::Expr(Expr {
node: Closure(_, _, _, closure_span, None),
..
}) = hir.get(node_id) {
}) = hir.get_by_hir_id(hir_id) {
let sup_sp = sup_origin.span();
let origin_sp = origin.span();
let mut err = self.tcx().sess.struct_span_err(

View file

@ -51,11 +51,11 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
};
let hir = &self.tcx().hir();
if let Some(node_id) = hir.as_local_node_id(id) {
if let Some(body_id) = hir.maybe_body_owned_by(node_id) {
if let Some(hir_id) = hir.as_local_hir_id(id) {
if let Some(body_id) = hir.maybe_body_owned_by(hir_id) {
let body = hir.body(body_id);
let owner_id = hir.body_owner(body_id);
let fn_decl = hir.fn_decl(owner_id).unwrap();
let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap();
if let Some(tables) = self.tables {
body.arguments
.iter()
@ -63,7 +63,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
.filter_map(|(index, arg)| {
// May return None; sometimes the tables are not yet populated.
let ty_hir_id = fn_decl.inputs[index].hir_id;
let arg_ty_span = hir.span(hir.hir_to_node_id(ty_hir_id));
let arg_ty_span = hir.span(ty_hir_id);
let ty = tables.node_type_opt(arg.hir_id)?;
let mut found_anon_region = false;
let new_arg_ty = self.tcx().fold_regions(&ty, &mut false, |r, _| {

View file

@ -41,7 +41,7 @@ use std::collections::hash_map::Entry;
use super::InferCtxt;
use super::unify_key::ToType;
pub struct TypeFreshener<'a, 'tcx: 'a> {
pub struct TypeFreshener<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
ty_freshen_count: u32,
const_freshen_count: u32,

View file

@ -133,7 +133,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
}
pub struct InferenceFudger<'a, 'tcx: 'a> {
pub struct InferenceFudger<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
type_vars: (Range<TyVid>, Vec<TypeVariableOrigin>),
int_vars: Range<IntVid>,

View file

@ -8,7 +8,7 @@ use crate::ty::{self, Ty, TyCtxt};
use crate::ty::relate::{Relate, RelateResult, TypeRelation};
/// "Greatest lower bound" (common subtype)
pub struct Glb<'combine, 'infcx: 'combine, 'tcx: 'infcx> {
pub struct Glb<'combine, 'infcx, 'tcx> {
fields: &'combine mut CombineFields<'infcx, 'tcx>,
a_is_expected: bool,
}

View file

@ -27,7 +27,7 @@ use crate::ty::TyVar;
use crate::ty::{self, Ty};
use crate::ty::relate::{RelateResult, TypeRelation};
pub trait LatticeDir<'f, 'tcx: 'f>: TypeRelation<'tcx> {
pub trait LatticeDir<'f, 'tcx>: TypeRelation<'tcx> {
fn infcx(&self) -> &'f InferCtxt<'f, 'tcx>;
fn cause(&self) -> &ObligationCause<'tcx>;
@ -41,14 +41,13 @@ pub trait LatticeDir<'f, 'tcx: 'f>: TypeRelation<'tcx> {
fn relate_bound(&mut self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()>;
}
pub fn super_lattice_tys<'a, 'tcx, L>(
pub fn super_lattice_tys<'a, 'tcx: 'a, L>(
this: &mut L,
a: Ty<'tcx>,
b: Ty<'tcx>,
) -> RelateResult<'tcx, Ty<'tcx>>
where
L: LatticeDir<'a, 'tcx>,
'tcx: 'a,
{
debug!("{}.lattice_tys({:?}, {:?})",
this.tag(),

View file

@ -107,7 +107,7 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(
}
}
struct ConstraintGraph<'a, 'tcx: 'a> {
struct ConstraintGraph<'a, 'tcx> {
graph_name: String,
region_rels: &'a RegionRelations<'a, 'tcx>,
map: &'a BTreeMap<Constraint<'tcx>, SubregionOrigin<'tcx>>,

View file

@ -93,7 +93,7 @@ struct RegionAndOrigin<'tcx> {
type RegionGraph<'tcx> = Graph<(), Constraint<'tcx>>;
struct LexicalResolver<'cx, 'tcx: 'cx> {
struct LexicalResolver<'cx, 'tcx> {
region_rels: &'cx RegionRelations<'cx, 'tcx>,
var_infos: VarInfos,
data: RegionConstraintData<'tcx>,

View file

@ -8,7 +8,7 @@ use crate::ty::{self, Ty, TyCtxt};
use crate::ty::relate::{Relate, RelateResult, TypeRelation};
/// "Least upper bound" (common supertype)
pub struct Lub<'combine, 'infcx: 'combine, 'tcx: 'infcx> {
pub struct Lub<'combine, 'infcx, 'tcx> {
fields: &'combine mut CombineFields<'infcx, 'tcx>,
a_is_expected: bool,
}

View file

@ -585,7 +585,7 @@ impl<'tcx> InferOk<'tcx, ()> {
}
#[must_use = "once you start a snapshot, you should always consume it"]
pub struct CombinedSnapshot<'a, 'tcx: 'a> {
pub struct CombinedSnapshot<'a, 'tcx> {
projection_cache_snapshot: traits::ProjectionCacheSnapshot,
type_snapshot: type_variable::Snapshot<'tcx>,
const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,

View file

@ -38,7 +38,7 @@ pub enum NormalizationStrategy {
Eager,
}
pub struct TypeRelating<'me, 'tcx: 'me, D>
pub struct TypeRelating<'me, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
@ -741,7 +741,7 @@ where
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
struct ScopeInstantiator<'me, 'tcx: 'me> {
struct ScopeInstantiator<'me, 'tcx> {
next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
@ -798,7 +798,7 @@ impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
/// scopes.
///
/// [blog post]: https://is.gd/0hKvIr
struct TypeGeneralizer<'me, 'tcx: 'me, D>
struct TypeGeneralizer<'me, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx> + 'me,
{

View file

@ -469,11 +469,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
definition_ty
);
// We can unwrap here because our reverse mapper always
// produces things with 'tcx lifetime, though the type folder
// obscures that.
let definition_ty = gcx.lift(&definition_ty).unwrap();
definition_ty
}
}
@ -723,7 +718,7 @@ impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
}
}
struct Instantiator<'a, 'tcx: 'a> {
struct Instantiator<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
parent_def_id: DefId,
body_id: hir::HirId,
@ -819,7 +814,7 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
},
_ => bug!(
"expected (impl) item, found {}",
tcx.hir().hir_to_string(opaque_hir_id),
tcx.hir().node_to_string(opaque_hir_id),
),
};
if in_definition_scope {

View file

@ -67,7 +67,7 @@ pub struct OutlivesEnvironment<'tcx> {
/// because of implied bounds.
pub type RegionBoundPairs<'tcx> = Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>;
impl<'a, 'tcx: 'a> OutlivesEnvironment<'tcx> {
impl<'a, 'tcx> OutlivesEnvironment<'tcx> {
pub fn new(param_env: ty::ParamEnv<'tcx>) -> Self {
let mut env = OutlivesEnvironment {
param_env,

View file

@ -226,7 +226,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
/// via a "delegate" of type `D` -- this is usually the `infcx`, which
/// accrues them into the `region_obligations` code, but for NLL we
/// use something else.
pub struct TypeOutlives<'cx, 'tcx: 'cx, D>
pub struct TypeOutlives<'cx, 'tcx, D>
where
D: TypeOutlivesDelegate<'tcx>,
{

View file

@ -12,7 +12,7 @@ use crate::util::captures::Captures;
/// via a "delegate" of type `D` -- this is usually the `infcx`, which
/// accrues them into the `region_obligations` code, but for NLL we
/// use something else.
pub struct VerifyBoundCx<'cx, 'tcx: 'cx> {
pub struct VerifyBoundCx<'cx, 'tcx> {
tcx: TyCtxt<'tcx>,
region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>,

View file

@ -12,7 +12,7 @@ use crate::ty::fold::{TypeFolder, TypeVisitor};
/// been unified with (similar to `shallow_resolve`, but deep). This is
/// useful for printing messages etc but also required at various
/// points for correctness.
pub struct OpportunisticVarResolver<'a, 'tcx: 'a> {
pub struct OpportunisticVarResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
}
@ -50,7 +50,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticVarResolver<'a, 'tcx> {
/// The opportunistic type and region resolver is similar to the
/// opportunistic type resolver, but also opportunistically resolves
/// regions. It is useful for canonicalization.
pub struct OpportunisticTypeAndRegionResolver<'a, 'tcx: 'a> {
pub struct OpportunisticTypeAndRegionResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
}
@ -101,7 +101,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticTypeAndRegionResolver<'a, 'tcx>
/// type variables that don't yet have a value. The first unresolved type is stored.
/// It does not construct the fully resolved type (which might
/// involve some hashing and so forth).
pub struct UnresolvedTypeFinder<'a, 'tcx: 'a> {
pub struct UnresolvedTypeFinder<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
/// Used to find the type parameter name and location for error reporting.
@ -171,7 +171,7 @@ where
// N.B. This type is not public because the protocol around checking the
// `err` field is not enforcable otherwise.
struct FullTypeResolver<'a, 'tcx: 'a> {
struct FullTypeResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
err: Option<FixupError<'tcx>>,
}

View file

@ -11,7 +11,7 @@ use crate::mir::interpret::ConstValue;
use std::mem;
/// Ensures `a` is made a subtype of `b`. Returns `a` on success.
pub struct Sub<'combine, 'infcx: 'combine, 'tcx: 'infcx> {
pub struct Sub<'combine, 'infcx, 'tcx> {
fields: &'combine mut CombineFields<'infcx, 'tcx>,
a_is_expected: bool,
}

View file

@ -507,7 +507,7 @@ impl LintStore {
}
/// Context for lint checking after type checking.
pub struct LateContext<'a, 'tcx: 'a> {
pub struct LateContext<'a, 'tcx> {
/// Type context we're checking in.
pub tcx: TyCtxt<'tcx>,
@ -533,7 +533,7 @@ pub struct LateContext<'a, 'tcx: 'a> {
only_module: bool,
}
pub struct LateContextAndPass<'a, 'tcx: 'a, T: LateLintPass<'a, 'tcx>> {
pub struct LateContextAndPass<'a, 'tcx, T: LateLintPass<'a, 'tcx>> {
context: LateContext<'a, 'tcx>,
pass: T,
}
@ -1399,7 +1399,7 @@ fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
// Visit the crate attributes
if hir_id == hir::CRATE_HIR_ID {
walk_list!(cx, visit_attribute, tcx.hir().attrs_by_hir_id(hir::CRATE_HIR_ID));
walk_list!(cx, visit_attribute, tcx.hir().attrs(hir::CRATE_HIR_ID));
}
}

View file

@ -762,7 +762,7 @@ pub fn struct_lint_level<'a>(sess: &'a Session,
}
pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
let attrs = tcx.hir().attrs_by_hir_id(id);
let attrs = tcx.hir().attrs(id);
attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
}

View file

@ -38,7 +38,7 @@ fn should_explore<'tcx>(tcx: TyCtxt<'tcx>, hir_id: hir::HirId) -> bool {
}
}
struct MarkSymbolVisitor<'a, 'tcx: 'a> {
struct MarkSymbolVisitor<'a, 'tcx> {
worklist: Vec<hir::HirId>,
tcx: TyCtxt<'tcx>,
tables: &'a ty::TypeckTables<'tcx>,
@ -292,7 +292,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
match ty.node {
TyKind::Def(item_id, _) => {
let item = self.tcx.hir().expect_item_by_hir_id(item_id.id);
let item = self.tcx.hir().expect_item(item_id.id);
intravisit::walk_item(self, item);
}
_ => ()
@ -351,7 +351,7 @@ fn has_allow_dead_code_or_lang_attr(
// or
// 2) We are not sure to be live or not
// * Implementation of a trait method
struct LifeSeeder<'k, 'tcx: 'k> {
struct LifeSeeder<'k, 'tcx> {
worklist: Vec<hir::HirId>,
krate: &'k hir::Crate,
tcx: TyCtxt<'tcx>,

View file

@ -11,7 +11,7 @@ use crate::hir::itemlikevisit::ItemLikeVisitor;
use crate::ty::TyCtxt;
use crate::ty::query::Providers;
struct EntryContext<'a, 'tcx: 'a> {
struct EntryContext<'a, 'tcx> {
session: &'a Session,
map: &'a hir_map::Map<'tcx>,

View file

@ -229,7 +229,7 @@ impl OverloadedCallType {
// The ExprUseVisitor type
//
// This is the code that actually walks the tree.
pub struct ExprUseVisitor<'a, 'tcx: 'a> {
pub struct ExprUseVisitor<'a, 'tcx> {
mc: mc::MemCategorizationContext<'a, 'tcx>,
delegate: &'a mut dyn Delegate<'tcx>,
param_env: ty::ParamEnv<'tcx>,
@ -546,7 +546,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
self.consume_expr(&base);
}
hir::ExprKind::Yield(ref value) => {
hir::ExprKind::Yield(ref value, _) => {
self.consume_expr(&value);
}
}

View file

@ -15,7 +15,7 @@ use crate::ty::{self, TyCtxt, Region};
///
/// This stuff is a bit convoluted and should be refactored, but as we
/// transition to NLL, it'll all go away anyhow.
pub struct RegionRelations<'a, 'tcx: 'a> {
pub struct RegionRelations<'a, 'tcx> {
pub tcx: TyCtxt<'tcx>,
/// The context used to fetch the region maps.

View file

@ -352,7 +352,7 @@ impl IrMaps<'tcx> {
}
}
fn visit_fn<'a, 'tcx: 'a>(
fn visit_fn<'tcx>(
ir: &mut IrMaps<'tcx>,
fk: FnKind<'tcx>,
decl: &'tcx hir::FnDecl,
@ -682,7 +682,7 @@ const ACC_READ: u32 = 1;
const ACC_WRITE: u32 = 2;
const ACC_USE: u32 = 4;
struct Liveness<'a, 'tcx: 'a> {
struct Liveness<'a, 'tcx> {
ir: &'a mut IrMaps<'tcx>,
tables: &'a ty::TypeckTables<'tcx>,
s: Specials,
@ -1171,7 +1171,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
}
hir::ExprKind::Call(ref f, ref args) => {
let m = self.ir.tcx.hir().get_module_parent_by_hir_id(expr.hir_id);
let m = self.ir.tcx.hir().get_module_parent(expr.hir_id);
let succ = if self.ir.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(expr)) {
self.s.exit_ln
} else {
@ -1182,7 +1182,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
}
hir::ExprKind::MethodCall(.., ref args) => {
let m = self.ir.tcx.hir().get_module_parent_by_hir_id(expr.hir_id);
let m = self.ir.tcx.hir().get_module_parent(expr.hir_id);
let succ = if self.ir.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(expr)) {
self.s.exit_ln
} else {
@ -1218,7 +1218,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
hir::ExprKind::Type(ref e, _) |
hir::ExprKind::DropTemps(ref e) |
hir::ExprKind::Unary(_, ref e) |
hir::ExprKind::Yield(ref e) |
hir::ExprKind::Yield(ref e, _) |
hir::ExprKind::Repeat(ref e, _) => {
self.propagate_through_expr(&e, succ)
}

View file

@ -342,9 +342,9 @@ impl MutabilityCategory {
fn from_local(
tcx: TyCtxt<'_>,
tables: &ty::TypeckTables<'_>,
id: ast::NodeId,
id: hir::HirId,
) -> MutabilityCategory {
let ret = match tcx.hir().get(id) {
let ret = match tcx.hir().get_by_hir_id(id) {
Node::Binding(p) => match p.node {
PatKind::Binding(..) => {
let bm = *tables.pat_binding_modes()
@ -500,7 +500,6 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
// FIXME
None if self.is_tainted_by_errors() => Err(()),
None => {
let id = self.tcx.hir().hir_to_node_id(id);
bug!("no type for node {}: {} in mem_categorization",
id, self.tcx.hir().node_to_string(id));
}
@ -753,15 +752,14 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
}
Res::Local(var_id) => {
let var_nid = self.tcx.hir().hir_to_node_id(var_id);
if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
self.cat_upvar(hir_id, span, var_nid)
self.cat_upvar(hir_id, span, var_id)
} else {
Ok(cmt_ {
hir_id,
span,
cat: Categorization::Local(var_id),
mutbl: MutabilityCategory::from_local(self.tcx, self.tables, var_nid),
mutbl: MutabilityCategory::from_local(self.tcx, self.tables, var_id),
ty: expr_ty,
note: NoteNone
})
@ -778,7 +776,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
&self,
hir_id: hir::HirId,
span: Span,
var_id: ast::NodeId,
var_id: hir::HirId,
) -> McResult<cmt_<'tcx>> {
// An upvar can have up to 3 components. We translate first to a
// `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
@ -819,22 +817,18 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
.unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
None =>
self.tcx.global_tcx()
.lift(&closure_substs)
.expect("no inference cx, but inference variables in closure ty")
.closure_kind(closure_def_id, self.tcx.global_tcx()),
closure_substs.closure_kind(closure_def_id, self.tcx.global_tcx()),
}
}
_ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty),
};
let var_hir_id = self.tcx.hir().node_to_hir_id(var_id);
let upvar_id = ty::UpvarId {
var_path: ty::UpvarPath { hir_id: var_hir_id },
var_path: ty::UpvarPath { hir_id: var_id },
closure_expr_id: closure_expr_def_id.to_local(),
};
let var_ty = self.node_ty(var_hir_id)?;
let var_ty = self.node_ty(var_id)?;
// Mutability of original variable itself
let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);

View file

@ -65,7 +65,7 @@ fn method_might_be_inlined<'tcx>(
}
// Information needed while computing reachability.
struct ReachableContext<'a, 'tcx: 'a> {
struct ReachableContext<'a, 'tcx> {
// The type context.
tcx: TyCtxt<'tcx>,
tables: &'a ty::TypeckTables<'tcx>,
@ -174,12 +174,12 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
} else {
let impl_did = self.tcx
.hir()
.get_parent_did_by_hir_id(hir_id);
.get_parent_did(hir_id);
// Check the impl. If the generics on the self
// type of the impl require inlining, this method
// does too.
let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did).unwrap();
match self.tcx.hir().expect_item_by_hir_id(impl_hir_id).node {
match self.tcx.hir().expect_item(impl_hir_id).node {
hir::ItemKind::Impl(..) => {
let generics = self.tcx.generics_of(impl_did);
generics.requires_monomorphization(self.tcx)
@ -296,7 +296,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
self.visit_nested_body(body);
}
hir::ImplItemKind::Method(_, body) => {
let did = self.tcx.hir().get_parent_did_by_hir_id(search_item);
let did = self.tcx.hir().get_parent_did(search_item);
if method_might_be_inlined(self.tcx, impl_item, did) {
self.visit_nested_body(body)
}
@ -318,7 +318,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
_ => {
bug!(
"found unexpected node kind in worklist: {} ({:?})",
self.tcx.hir().hir_to_string(search_item),
self.tcx.hir().node_to_string(search_item),
node,
);
}
@ -334,13 +334,13 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
// items of non-exported traits (or maybe all local traits?) unless their respective
// trait items are used from inlinable code through method call syntax or UFCS, or their
// trait is a lang item.
struct CollectPrivateImplItemsVisitor<'a, 'tcx: 'a> {
struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
access_levels: &'a privacy::AccessLevels,
worklist: &'a mut Vec<hir::HirId>,
}
impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &hir::Item) {
// Anything which has custom linkage gets thrown on the worklist no
// matter where it is in the crate, along with "special std symbols"

View file

@ -14,7 +14,6 @@ use std::mem;
use std::fmt;
use rustc_macros::HashStable;
use syntax::source_map;
use syntax::ast;
use syntax_pos::{Span, DUMMY_SP};
use crate::ty::{DefIdTree, TyCtxt};
use crate::ty::query::Providers;
@ -169,15 +168,15 @@ impl Scope {
self.id
}
pub fn node_id(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> ast::NodeId {
pub fn hir_id(&self, scope_tree: &ScopeTree) -> hir::HirId {
match scope_tree.root_body {
Some(hir_id) => {
tcx.hir().hir_to_node_id(hir::HirId {
hir::HirId {
owner: hir_id.owner,
local_id: self.item_local_id()
})
}
}
None => ast::DUMMY_NODE_ID
None => hir::DUMMY_HIR_ID
}
}
@ -185,13 +184,13 @@ impl Scope {
/// returned span may not correspond to the span of any `NodeId` in
/// the AST.
pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span {
let node_id = self.node_id(tcx, scope_tree);
if node_id == ast::DUMMY_NODE_ID {
let hir_id = self.hir_id(scope_tree);
if hir_id == hir::DUMMY_HIR_ID {
return DUMMY_SP;
}
let span = tcx.hir().span(node_id);
let span = tcx.hir().span(hir_id);
if let ScopeData::Remainder(first_statement_index) = self.data {
if let Node::Block(ref blk) = tcx.hir().get(node_id) {
if let Node::Block(ref blk) = tcx.hir().get_by_hir_id(hir_id) {
// Want span for scope starting after the
// indexed statement and ending at end of
// `blk`; reuse span of `blk` and shift `lo`
@ -332,7 +331,7 @@ pub struct ScopeTree {
/// The reason is that semantically, until the `box` expression returns,
/// the values are still owned by their containing expressions. So
/// we'll see that `&x`.
yield_in_scope: FxHashMap<Scope, (Span, usize)>,
yield_in_scope: FxHashMap<Scope, YieldData>,
/// The number of visit_expr and visit_pat calls done in the body.
/// Used to sanity check visit_expr/visit_pat call count when
@ -340,6 +339,15 @@ pub struct ScopeTree {
body_expr_count: FxHashMap<hir::BodyId, usize>,
}
#[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
pub struct YieldData {
/// `Span` of the yield.
pub span: Span,
/// The number of expressions and patterns appearing before the `yield` in the body + 1.
pub expr_and_pat_count: usize,
pub source: hir::YieldSource,
}
#[derive(Debug, Copy, Clone)]
pub struct Context {
/// the root of the current region tree. This is typically the id
@ -650,7 +658,7 @@ impl<'tcx> ScopeTree {
let param_owner = tcx.parent(br.def_id).unwrap();
let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
let scope = tcx.hir().maybe_body_owned_by_by_hir_id(param_owner_id).map(|body_id| {
let scope = tcx.hir().maybe_body_owned_by(param_owner_id).map(|body_id| {
tcx.hir().body(body_id).value.hir_id.local_id
}).unwrap_or_else(|| {
// The lifetime was defined on node that doesn't own a body,
@ -696,7 +704,7 @@ impl<'tcx> ScopeTree {
/// returns `Some((span, expr_count))` with the span of a yield we found and
/// the number of expressions and patterns appearing before the `yield` in the body + 1.
/// If there a are multiple yields in a scope, the one with the highest number is returned.
pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
pub fn yield_in_scope(&self, scope: Scope) -> Option<YieldData> {
self.yield_in_scope.get(&scope).cloned()
}
@ -707,14 +715,14 @@ impl<'tcx> ScopeTree {
scope: Scope,
expr_hir_id: hir::HirId,
body: &'tcx hir::Body) -> Option<Span> {
self.yield_in_scope(scope).and_then(|(span, count)| {
self.yield_in_scope(scope).and_then(|YieldData { span, expr_and_pat_count, .. }| {
let mut visitor = ExprLocatorVisitor {
hir_id: expr_hir_id,
result: None,
expr_and_pat_count: 0,
};
visitor.visit_body(body);
if count >= visitor.result.unwrap() {
if expr_and_pat_count >= visitor.result.unwrap() {
Some(span)
} else {
None
@ -954,12 +962,16 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h
debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
if let hir::ExprKind::Yield(..) = expr.node {
if let hir::ExprKind::Yield(_, source) = &expr.node {
// Mark this expr's scope and all parent scopes as containing `yield`.
let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node };
loop {
visitor.scope_tree.yield_in_scope.insert(scope,
(expr.span, visitor.expr_and_pat_count));
let data = YieldData {
span: expr.span,
expr_and_pat_count: visitor.expr_and_pat_count,
source: *source,
};
visitor.scope_tree.yield_in_scope.insert(scope, data);
// Keep traversing up while we can.
match visitor.scope_tree.parent_map.get(&scope) {
@ -1303,7 +1315,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> {
resolve_local(self, None, Some(&body.value));
}
if body.is_generator {
if body.generator_kind.is_some() {
self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
}
@ -1337,7 +1349,7 @@ fn region_scope_tree<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx ScopeTree
}
let id = tcx.hir().as_local_hir_id(def_id).unwrap();
let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by_by_hir_id(id) {
let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) {
let mut visitor = RegionResolutionVisitor {
tcx,
scope_tree: ScopeTree::default(),

View file

@ -217,7 +217,7 @@ impl_stable_hash_for!(struct crate::middle::resolve_lifetime::ResolveLifetimes {
object_lifetime_defaults
});
struct LifetimeContext<'a, 'tcx: 'a> {
struct LifetimeContext<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
map: &'a mut NamedRegionMap,
scope: ScopeRef<'a>,
@ -625,7 +625,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
// `abstract type MyAnonTy<'b>: MyTrait<'b>;`
// ^ ^ this gets resolved in the scope of
// the exist_ty generics
let (generics, bounds) = match self.tcx.hir().expect_item_by_hir_id(item_id.id).node
let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).node
{
// named existential types are reached via TyKind::Path
// this arm is for `impl Trait` in the types of statics, constants and locals
@ -1160,7 +1160,7 @@ fn signal_shadowing_problem(tcx: TyCtxt<'_>, name: ast::Name, orig: Original, sh
// Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning
// if one of the label shadows a lifetime or another label.
fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
struct GatherLabels<'a, 'tcx: 'a> {
struct GatherLabels<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
scope: ScopeRef<'a>,
labels_in_fn: &'a mut Vec<ast::Ident>,
@ -1236,7 +1236,7 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) {
signal_shadowing_problem(
tcx,
label.name,
original_lifetime(tcx.hir().span_by_hir_id(hir_id)),
original_lifetime(tcx.hir().span(hir_id)),
shadower_label(label.span),
);
return;
@ -1590,7 +1590,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
if let Some(parent_hir_id) = self.tcx.hir()
.as_local_hir_id(parent_def_id) {
// lifetimes in `derive` expansions don't count (Issue #53738)
if self.tcx.hir().attrs_by_hir_id(parent_hir_id).iter()
if self.tcx.hir().attrs(parent_hir_id).iter()
.any(|attr| attr.check_name(sym::automatically_derived)) {
continue;
}
@ -1690,7 +1690,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
// 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_by_hir_id(parent_id);
let parent = self.tcx.hir().expect_item(parent_id);
if sub_items_have_self_param(&parent.node) {
index += 1; // Self comes before lifetimes
}
@ -1823,7 +1823,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
// Do not free early-bound regions, only late-bound ones.
} else if let Some(body_id) = outermost_body {
let fn_id = self.tcx.hir().body_owner(body_id);
match self.tcx.hir().get(fn_id) {
match self.tcx.hir().get_by_hir_id(fn_id) {
Node::Item(&hir::Item {
node: hir::ItemKind::Fn(..),
..
@ -1836,7 +1836,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
node: hir::ImplItemKind::Method(..),
..
}) => {
let scope = self.tcx.hir().local_def_id(fn_id);
let scope = self.tcx.hir().local_def_id_from_hir_id(fn_id);
def = Region::Free(scope, def.id().unwrap());
}
_ => {}
@ -2065,7 +2065,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
}) => {
if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
.hir()
.expect_item_by_hir_id(self.tcx.hir().get_parent_item(parent))
.expect_item(self.tcx.hir().get_parent_item(parent))
.node
{
assoc_item_kind = trait_items
@ -2085,7 +2085,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
}) => {
if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
.hir()
.expect_item_by_hir_id(self.tcx.hir().get_parent_item(parent))
.expect_item(self.tcx.hir().get_parent_item(parent))
.node
{
impl_self = Some(self_ty);
@ -2629,7 +2629,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
signal_shadowing_problem(
self.tcx,
param.name.ident().name,
original_lifetime(self.tcx.hir().span_by_hir_id(hir_id)),
original_lifetime(self.tcx.hir().span(hir_id)),
shadower_lifetime(&param),
);
return;
@ -2696,7 +2696,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
debug!(
"insert_lifetime: {} resolved to {:?} span={:?}",
self.tcx.hir().hir_to_string(lifetime_ref.hir_id),
self.tcx.hir().node_to_string(lifetime_ref.hir_id),
def,
self.tcx.sess.source_map().span_to_string(lifetime_ref.span)
);

View file

@ -105,7 +105,7 @@ impl_stable_hash_for!(struct self::Index<'tcx> {
});
// A private tree-walker for producing an Index.
struct Annotator<'a, 'tcx: 'a> {
struct Annotator<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
index: &'a mut Index<'tcx>,
parent_stab: Option<&'tcx Stability>,
@ -113,7 +113,7 @@ struct Annotator<'a, 'tcx: 'a> {
in_trait_impl: bool,
}
impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
impl<'a, 'tcx> Annotator<'a, 'tcx> {
// Determine the stability for a node based on its attributes and inherited
// stability. The stability is recorded in the index and used as the parent.
fn annotate<F>(&mut self, hir_id: HirId, attrs: &[Attribute],
@ -316,12 +316,12 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
}
}
struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
struct MissingStabilityAnnotations<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
access_levels: &'a AccessLevels,
}
impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
impl<'a, 'tcx> MissingStabilityAnnotations<'a, 'tcx> {
fn check_missing_stability(&self, hir_id: HirId, span: Span, name: &str) {
let stab = self.tcx.stability().local_stability(hir_id);
let is_error = !self.tcx.sess.opts.test &&

View file

@ -17,7 +17,7 @@ use crate::ty::TyCtxt;
macro_rules! weak_lang_items {
($($name:ident, $item:ident, $sym:ident;)*) => (
struct Context<'a, 'tcx: 'a> {
struct Context<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
items: &'a mut lang_items::LanguageItems,
}

View file

@ -2,7 +2,7 @@ use std::fmt;
use rustc_macros::HashStable;
use rustc_apfloat::{Float, ieee::{Double, Single}};
use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size, Align}, subst::SubstsRef};
use crate::ty::PlaceholderConst;
use crate::hir::def_id::DefId;
@ -45,7 +45,12 @@ pub enum ConstValue<'tcx> {
/// An allocation together with a pointer into the allocation.
/// Invariant: the pointer's `AllocId` resolves to the allocation.
ByRef(Pointer, &'tcx Allocation),
/// The alignment exists to allow `const_field` to have `ByRef` access to nonprimitive fields
/// of `repr(packed)` structs. The alignment may be lower than the type of this constant.
/// This permits reads with lower alignment than what the type would normally require.
/// FIXME(RalfJ,oli-obk): The alignment checks are part of miri, but const eval doesn't really
/// need them. Disabling them may be too hard though.
ByRef(Pointer, Align, &'tcx Allocation),
/// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
/// variants when the code is monomorphic enough for that.

View file

@ -2104,7 +2104,7 @@ impl<'tcx> Place<'tcx> {
/// 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.
pub enum Projections<'p, 'tcx: 'p> {
pub enum Projections<'p, 'tcx> {
Empty,
List {
@ -2143,7 +2143,7 @@ impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
/// 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.
pub struct ProjectionsIter<'p, 'tcx: 'p> {
pub struct ProjectionsIter<'p, 'tcx> {
pub value: &'p Projections<'p, 'tcx>,
}
@ -2565,7 +2565,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
let name = if tcx.sess.opts.debugging_opts.span_free_formats {
format!("[closure@{:?}]", hir_id)
} else {
format!("[closure@{:?}]", tcx.hir().span_by_hir_id(hir_id))
format!("[closure@{:?}]", tcx.hir().span(hir_id))
};
let mut struct_fmt = fmt.debug_struct(&name);
@ -2585,7 +2585,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
let name = format!("[generator@{:?}]",
tcx.hir().span_by_hir_id(hir_id));
tcx.hir().span(hir_id));
let mut struct_fmt = fmt.debug_struct(&name);
if let Some(upvars) = tcx.upvars(def_id) {

View file

@ -218,7 +218,7 @@ impl<'tcx> MonoItem<'tcx> {
MonoItem::GlobalAsm(hir_id) => {
Some(hir_id)
}
}.map(|hir_id| tcx.hir().span_by_hir_id(hir_id))
}.map(|hir_id| tcx.hir().span(hir_id))
}
}

View file

@ -122,13 +122,25 @@ impl<'tcx> Place<'tcx> {
where
D: HasLocalDecls<'tcx>,
{
match *self {
Place::Base(PlaceBase::Local(index)) =>
PlaceTy::from_ty(local_decls.local_decls()[index].ty),
Place::Base(PlaceBase::Static(ref data)) =>
PlaceTy::from_ty(data.ty),
Place::Projection(ref proj) =>
proj.base.ty(local_decls, tcx).projection_ty(tcx, &proj.elem),
self.iterate(|place_base, place_projections| {
let mut place_ty = place_base.ty(local_decls);
for proj in place_projections {
place_ty = place_ty.projection_ty(tcx, &proj.elem);
}
place_ty
})
}
}
impl<'tcx> PlaceBase<'tcx> {
pub fn ty<D>(&self, local_decls: &D) -> PlaceTy<'tcx>
where D: HasLocalDecls<'tcx>
{
match self {
PlaceBase::Local(index) => PlaceTy::from_ty(local_decls.local_decls()[*index].ty),
PlaceBase::Static(data) => PlaceTy::from_ty(data.ty),
}
}
}

View file

@ -20,7 +20,7 @@ use super::*;
///
/// A preorder traversal of this graph is either `A B D C` or `A C D B`
#[derive(Clone)]
pub struct Preorder<'a, 'tcx: 'a> {
pub struct Preorder<'a, 'tcx> {
body: &'a Body<'tcx>,
visited: BitSet<BasicBlock>,
worklist: Vec<BasicBlock>,
@ -98,7 +98,7 @@ impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> {
/// ```
///
/// A Postorder traversal of this graph is `D B C A` or `D C B A`
pub struct Postorder<'a, 'tcx: 'a> {
pub struct Postorder<'a, 'tcx> {
body: &'a Body<'tcx>,
visited: BitSet<BasicBlock>,
visit_stack: Vec<(BasicBlock, Successors<'a>)>,
@ -251,7 +251,7 @@ impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> {
/// constructed as few times as possible. Use the `reset` method to be able
/// to re-use the traversal
#[derive(Clone)]
pub struct ReversePostorder<'a, 'tcx: 'a> {
pub struct ReversePostorder<'a, 'tcx> {
body: &'a Body<'tcx>,
blocks: Vec<BasicBlock>,
idx: usize

View file

@ -141,9 +141,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
&self,
fulfill_cx: &mut FulfillmentContext<'tcx>,
result: &T,
) -> T::Lifted
) -> T
where
T: TypeFoldable<'tcx> + ty::Lift<'tcx>,
T: TypeFoldable<'tcx>,
{
debug!("drain_fulfillment_cx_or_panic()");
@ -155,10 +155,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
let result = self.resolve_vars_if_possible(result);
let result = self.tcx.erase_regions(&result);
self.tcx.lift_to_global(&result).unwrap_or_else(||
bug!("Uninferred types/regions/consts in `{:?}`", result)
)
self.tcx.erase_regions(&result)
}
}

View file

@ -1013,10 +1013,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
) {
let hir = self.tcx.hir();
let parent_node = hir.get_parent_node(
hir.hir_to_node_id(obligation.cause.body_id),
);
let node = hir.find(parent_node);
let parent_node = hir.get_parent_node_by_hir_id(obligation.cause.body_id);
let node = hir.find_by_hir_id(parent_node);
if let Some(hir::Node::Item(hir::Item {
node: hir::ItemKind::Fn(decl, _, _, body_id),
..
@ -1052,10 +1050,10 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
(self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter()
.map(|arg| {
if let hir::Pat {
node: hir::PatKind::Tuple(args, _),
node: hir::PatKind::Tuple(ref args, _),
span,
..
} = arg.pat.clone().into_inner() {
} = *arg.pat {
ArgKind::Tuple(
Some(span),
args.iter().map(|pat| {
@ -1098,7 +1096,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
Node::Ctor(ref variant_data) => {
let span = variant_data.ctor_hir_id()
.map(|hir_id| self.tcx.hir().span_by_hir_id(hir_id))
.map(|hir_id| self.tcx.hir().span(hir_id))
.unwrap_or(DUMMY_SP);
let span = self.tcx.sess.source_map().def_span(span);
@ -1451,7 +1449,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
param_env: ty::ParamEnv<'tcx>,
pred: ty::PolyTraitRef<'tcx>,
) -> bool {
struct ParamToVarFolder<'a, 'tcx: 'a> {
struct ParamToVarFolder<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
}

View file

@ -224,7 +224,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
}
}
struct FulfillProcessor<'a, 'b: 'a, 'tcx: 'b> {
struct FulfillProcessor<'a, 'b, 'tcx> {
selcx: &'a mut SelectionContext<'b, 'tcx>,
register_region_obligations: bool,
}

View file

@ -285,7 +285,7 @@ where
}
}
struct AssocTypeNormalizer<'a, 'b: 'a, 'tcx: 'b> {
struct AssocTypeNormalizer<'a, 'b, 'tcx> {
selcx: &'a mut SelectionContext<'b, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
cause: ObligationCause<'tcx>,
@ -409,7 +409,6 @@ impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> {
promoted: None
};
if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
let substs = tcx.lift_to_global(&substs).unwrap();
let evaluated = evaluated.subst(tcx, substs);
return evaluated;
}

View file

@ -73,7 +73,7 @@ pub struct NormalizationResult<'tcx> {
pub normalized_ty: Ty<'tcx>,
}
struct QueryNormalizer<'cx, 'tcx: 'cx> {
struct QueryNormalizer<'cx, 'tcx> {
infcx: &'cx InferCtxt<'cx, 'tcx>,
cause: &'cx ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
@ -203,7 +203,6 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for QueryNormalizer<'cx, 'tcx> {
promoted: None,
};
if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
let substs = tcx.lift_to_global(&substs).unwrap();
let evaluated = evaluated.subst(tcx, substs);
return evaluated;
}

View file

@ -8,7 +8,7 @@ use std::rc::Rc;
use crate::traits::query::Fallible;
use crate::traits::ObligationCause;
use crate::ty::fold::TypeFoldable;
use crate::ty::{Lift, ParamEnvAnd, TyCtxt};
use crate::ty::{ParamEnvAnd, TyCtxt};
pub mod ascribe_user_type;
pub mod custom;
@ -44,8 +44,8 @@ pub trait TypeOp<'tcx>: Sized + fmt::Debug {
/// which produces the resulting query region constraints.
///
/// [c]: https://rust-lang.github.io/rustc-guide/traits/canonicalization.html
pub trait QueryTypeOp<'tcx>: fmt::Debug + Sized + TypeFoldable<'tcx> + Lift<'tcx> {
type QueryResponse: TypeFoldable<'tcx> + Lift<'tcx>;
pub trait QueryTypeOp<'tcx>: fmt::Debug + Sized + TypeFoldable<'tcx> + 'tcx {
type QueryResponse: TypeFoldable<'tcx>;
/// Give query the option for a simple fast path that never
/// actually hits the tcx cache lookup etc. Return `Some(r)` with

View file

@ -20,7 +20,7 @@ where
impl<'tcx, T> super::QueryTypeOp<'tcx> for Normalize<T>
where
T: Normalizable<'tcx>,
T: Normalizable<'tcx> + 'tcx,
{
type QueryResponse = T;

View file

@ -50,7 +50,7 @@ use std::iter;
use std::rc::Rc;
use crate::util::nodemap::{FxHashMap, FxHashSet};
pub struct SelectionContext<'cx, 'tcx: 'cx> {
pub struct SelectionContext<'cx, 'tcx> {
infcx: &'cx InferCtxt<'cx, 'tcx>,
/// Freshener used specifically for entries on the obligation
@ -144,7 +144,7 @@ impl IntercrateAmbiguityCause {
}
// A stack that walks back up the stack frame.
struct TraitObligationStack<'prev, 'tcx: 'prev> {
struct TraitObligationStack<'prev, 'tcx> {
obligation: &'prev TraitObligation<'tcx>,
/// Trait ref from `obligation` but "freshened" with the
@ -690,14 +690,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
/// Evaluates the predicates in `predicates` recursively. Note that
/// this applies projections in the predicates, and therefore
/// is run within an inference probe.
fn evaluate_predicates_recursively<'a, 'o, I>(
fn evaluate_predicates_recursively<'o, I>(
&mut self,
stack: TraitObligationStackList<'o, 'tcx>,
predicates: I,
) -> Result<EvaluationResult, OverflowError>
where
I: IntoIterator<Item = PredicateObligation<'tcx>>,
'tcx: 'a,
{
let mut result = EvaluatedToOk;
for obligation in predicates {
@ -3789,9 +3788,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
matcher.relate(previous, current).is_ok()
}
fn push_stack<'o, 's: 'o>(
fn push_stack<'o>(
&mut self,
previous_stack: TraitObligationStackList<'s, 'tcx>,
previous_stack: TraitObligationStackList<'o, 'tcx>,
obligation: &'o TraitObligation<'tcx>,
) -> TraitObligationStack<'o, 'tcx> {
let fresh_trait_ref = obligation
@ -4252,7 +4251,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> {
}
#[derive(Copy, Clone)]
struct TraitObligationStackList<'o, 'tcx: 'o> {
struct TraitObligationStackList<'o, 'tcx> {
cache: &'o ProvisionalEvaluationCache<'tcx>,
head: Option<&'o TraitObligationStack<'o, 'tcx>>,
}

View file

@ -132,12 +132,7 @@ pub fn find_associated_item<'tcx>(
let substs = substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
let substs = translate_substs(&infcx, param_env, impl_data.impl_def_id,
substs, node_item.node);
let substs = infcx.tcx.erase_regions(&substs);
tcx.lift(&substs).unwrap_or_else(||
bug!("find_method: translate_substs \
returned {:?} which contains inference types/regions",
substs)
)
infcx.tcx.erase_regions(&substs)
});
(node_item.item.def_id, substs)
}

View file

@ -654,7 +654,7 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
match self.hir().as_local_hir_id(node_item_def_id) {
Some(hir_id) => {
let item = self.hir().expect_item_by_hir_id(hir_id);
let item = self.hir().expect_item(hir_id);
if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
defaultness.is_default()
} else {

View file

@ -250,11 +250,9 @@ fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,
if let Some(local_id_root) = local_id_root {
if hir_id.owner != local_id_root.index {
ty::tls::with(|tcx| {
let node_id = tcx.hir().hir_to_node_id(hir_id);
bug!("node {} with HirId::owner {:?} cannot be placed in \
TypeckTables with local_id_root {:?}",
tcx.hir().node_to_string(node_id),
tcx.hir().node_to_string(hir_id),
DefId::local(hir_id.owner),
local_id_root)
});
@ -556,7 +554,7 @@ impl<'tcx> TypeckTables<'tcx> {
pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
self.node_type_opt(id).unwrap_or_else(||
bug!("node_type: no type for node `{}`",
tls::with(|tcx| tcx.hir().hir_to_string(id)))
tls::with(|tcx| tcx.hir().node_to_string(id)))
)
}

View file

@ -192,9 +192,12 @@ impl<'tcx> ty::TyS<'tcx> {
ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
ty::Array(_, n) => match n.assert_usize(tcx) {
Some(n) => format!("array of {} elements", n).into(),
None => "array".into(),
ty::Array(_, n) => {
let n = tcx.lift_to_global(&n).unwrap();
match n.assert_usize(tcx) {
Some(n) => format!("array of {} elements", n).into(),
None => "array".into(),
}
}
ty::Slice(_) => "slice".into(),
ty::RawPtr(_) => "*-ptr".into(),

View file

@ -2711,7 +2711,7 @@ where
}
// If this is a C-variadic function, this is not the return value,
// and there is one or more fixed arguments; ensure that the `VaList`
// and there is one or more fixed arguments; ensure that the `VaListImpl`
// is ignored as an argument.
if sig.c_variadic {
match (last_arg_idx, arg_idx) {
@ -2722,7 +2722,7 @@ where
};
match ty.sty {
ty::Adt(def, _) if def.did == va_list_did => {
// This is the "spoofed" `VaList`. Set the arguments mode
// This is the "spoofed" `VaListImpl`. Set the arguments mode
// so that it will be ignored.
arg.mode = PassMode::Ignore(IgnoreMode::CVarArgs);
}

View file

@ -277,7 +277,7 @@ impl Visibility {
def => Visibility::Restricted(def.def_id()),
},
hir::VisibilityKind::Inherited => {
Visibility::Restricted(tcx.hir().get_module_parent_by_hir_id(id))
Visibility::Restricted(tcx.hir().get_module_parent(id))
}
}
}
@ -3016,7 +3016,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// Gets the attributes of a definition.
pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
if let Some(id) = self.hir().as_local_hir_id(did) {
Attributes::Borrowed(self.hir().attrs_by_hir_id(id))
Attributes::Borrowed(self.hir().attrs(id))
} else {
Attributes::Owned(self.item_attrs(did))
}
@ -3068,7 +3068,7 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
if impl_did.is_local() {
let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
Ok(self.hir().span_by_hir_id(hir_id))
Ok(self.hir().span(hir_id))
} else {
Err(self.crate_name(impl_did.krate))
}
@ -3103,7 +3103,7 @@ impl<'tcx> TyCtxt<'tcx> {
let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
Some(actual_expansion) =>
self.hir().definitions().parent_module_of_macro_def(actual_expansion),
None => self.hir().get_module_parent_by_hir_id(block),
None => self.hir().get_module_parent(block),
};
(ident, scope)
}
@ -3129,7 +3129,7 @@ fn associated_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> AssocItem {
let id = tcx.hir().as_local_hir_id(def_id).unwrap();
let parent_id = tcx.hir().get_parent_item(id);
let parent_def_id = tcx.hir().local_def_id_from_hir_id(parent_id);
let parent_item = tcx.hir().expect_item_by_hir_id(parent_id);
let parent_item = tcx.hir().expect_item(parent_id);
match parent_item.node {
hir::ItemKind::Impl(.., ref impl_item_refs) => {
if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.hir_id == id) {
@ -3186,7 +3186,7 @@ fn adt_sized_constraint<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> AdtSizedConst
fn associated_item_def_ids<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx [DefId] {
let id = tcx.hir().as_local_hir_id(def_id).unwrap();
let item = tcx.hir().expect_item_by_hir_id(id);
let item = tcx.hir().expect_item(id);
match item.node {
hir::ItemKind::Trait(.., ref trait_item_refs) => {
tcx.arena.alloc_from_iter(
@ -3266,7 +3266,7 @@ fn param_env<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ParamEnv<'tcx> {
);
let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::DUMMY_HIR_ID, |id| {
tcx.hir().maybe_body_owned_by_by_hir_id(id).map_or(id, |body| body.hir_id)
tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
});
let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)

View file

@ -589,7 +589,7 @@ pub trait PrettyPrinter<'tcx>:
// FIXME(eddyb) should use `def_span`.
if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
p!(write("@{:?}", self.tcx().hir().span(hir_id)));
let mut sep = " ";
for (&var_id, upvar_ty) in self.tcx().upvars(did)
.as_ref()
@ -631,7 +631,7 @@ pub trait PrettyPrinter<'tcx>:
if self.tcx().sess.opts.debugging_opts.span_free_formats {
p!(write("@{:?}", hir_id));
} else {
p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
p!(write("@{:?}", self.tcx().hir().span(hir_id)));
}
let mut sep = " ";
for (&var_id, upvar_ty) in self.tcx().upvars(did)

View file

@ -505,13 +505,11 @@ impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
// Decode something that was encoded with encode_tagged() and verify that the
// tag matches and the correct amount of bytes was read.
fn decode_tagged<'a, 'tcx, D, T, V>(decoder: &mut D,
expected_tag: T)
-> Result<V, D::Error>
where T: Decodable + Eq + ::std::fmt::Debug,
V: Decodable,
D: DecoderWithPosition,
'tcx: 'a,
fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
where
T: Decodable + Eq + ::std::fmt::Debug,
V: Decodable,
D: DecoderWithPosition,
{
let start_pos = decoder.position();

View file

@ -89,7 +89,7 @@ macro_rules! profq_query_msg {
/// A type representing the responsibility to execute the job in the `job` field.
/// This will poison the relevant query if dropped.
pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx> + 'a> {
cache: &'a Lock<QueryCache<'tcx, Q>>,
key: Q::Key,
job: Lrc<QueryJob<'tcx>>,
@ -230,7 +230,7 @@ pub struct CycleError<'tcx> {
}
/// The result of `try_get_lock`
pub(super) enum TryGetJob<'a, 'tcx: 'a, D: QueryDescription<'tcx> + 'a> {
pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx> + 'a> {
/// The query is not yet started. Contains a guard to the cache eventually used to start it.
NotYetStarted(JobOwner<'a, 'tcx, D>),

View file

@ -1335,7 +1335,7 @@ impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::Const<'tcx> {
impl<'tcx> TypeFoldable<'tcx> for ConstValue<'tcx> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
match *self {
ConstValue::ByRef(ptr, alloc) => ConstValue::ByRef(ptr, alloc),
ConstValue::ByRef(ptr, align, alloc) => ConstValue::ByRef(ptr, align, alloc),
ConstValue::Infer(ic) => ConstValue::Infer(ic.fold_with(folder)),
ConstValue::Param(p) => ConstValue::Param(p.fold_with(folder)),
ConstValue::Placeholder(p) => ConstValue::Placeholder(p),

View file

@ -2262,7 +2262,6 @@ impl<'tcx> Const<'tcx> {
#[inline]
pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
let ty = tcx.lift_to_global(&ty).unwrap();
let size = tcx.layout_of(ty).unwrap_or_else(|e| {
panic!("could not compute layout for {:?}: {:?}", ty, e)
}).size;
@ -2289,7 +2288,6 @@ impl<'tcx> Const<'tcx> {
if self.ty != ty.value {
return None;
}
let ty = tcx.lift_to_global(&ty).unwrap();
let size = tcx.layout_of(ty).ok()?.size;
self.val.try_to_bits(size)
}
@ -2300,15 +2298,14 @@ impl<'tcx> Const<'tcx> {
}
#[inline]
pub fn assert_bits(&self, tcx: TyCtxt<'_>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Option<u128> {
pub fn assert_bits(&self, tcx: TyCtxt<'tcx>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Option<u128> {
assert_eq!(self.ty, ty.value);
let ty = tcx.lift_to_global(&ty).unwrap();
let size = tcx.layout_of(ty).ok()?.size;
self.val.try_to_bits(size)
}
#[inline]
pub fn assert_bool(&self, tcx: TyCtxt<'_>) -> Option<bool> {
pub fn assert_bool(&self, tcx: TyCtxt<'tcx>) -> Option<bool> {
self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.bool)).and_then(|v| match v {
0 => Some(false),
1 => Some(true),
@ -2317,18 +2314,18 @@ impl<'tcx> Const<'tcx> {
}
#[inline]
pub fn assert_usize(&self, tcx: TyCtxt<'_>) -> Option<u64> {
pub fn assert_usize(&self, tcx: TyCtxt<'tcx>) -> Option<u64> {
self.assert_bits(tcx, ParamEnv::empty().and(tcx.types.usize)).map(|v| v as u64)
}
#[inline]
pub fn unwrap_bits(&self, tcx: TyCtxt<'_>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> u128 {
pub fn unwrap_bits(&self, tcx: TyCtxt<'tcx>, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> u128 {
self.assert_bits(tcx, ty).unwrap_or_else(||
bug!("expected bits of {}, got {:#?}", ty.value, self))
}
#[inline]
pub fn unwrap_usize(&self, tcx: TyCtxt<'_>) -> u64 {
pub fn unwrap_usize(&self, tcx: TyCtxt<'tcx>) -> u64 {
self.assert_usize(tcx).unwrap_or_else(||
bug!("expected constant usize, got {:#?}", self))
}

Some files were not shown because too many files have changed in this diff Show more