Rollup merge of #70112 - Centril:rollup-gpi5tbq, r=Centril

Rollup of 10 pull requests

Successful merges:

 - #67749 (keyword docs for else and inkeyword docs for else and in.)
 - #69139 (clean up E0308 explanation)
 - #69189 (Erase regions in writeback)
 - #69837 (Use smaller discriminants for generators)
 - #69838 (Expansion-driven outline module parsing)
 - #69839 (Miri error reform)
 - #69899 (Make methods declared by `newtype_index` macro `const`)
 - #69920 (Remove some imports to the rustc crate)
 - #70075 (Fix repr pretty display)
 - #70106 (Tidy: fix running rustfmt twice)

Failed merges:

 - #70051 (Allow `hir().find` to return `None`)
 - #70074 (Expand: nix all fatal errors)

r? @ghost
This commit is contained in:
Pietro Albini 2020-03-18 21:11:07 +01:00 committed by GitHub
commit 11053bafac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
284 changed files with 2042 additions and 1855 deletions

View File

@ -3624,6 +3624,7 @@ dependencies = [
"rustc_data_structures",
"rustc_hir",
"rustc_metadata",
"rustc_session",
"rustc_span",
"rustc_target",
]
@ -3677,6 +3678,7 @@ dependencies = [
"rustc_parse",
"rustc_plugin_impl",
"rustc_save_analysis",
"rustc_session",
"rustc_span",
"rustc_target",
"serialize",
@ -3791,6 +3793,7 @@ dependencies = [
"rustc_hir",
"rustc_index",
"rustc_macros",
"rustc_session",
"rustc_span",
"rustc_target",
"smallvec 1.0.0",
@ -3903,6 +3906,7 @@ dependencies = [
"rustc_expand",
"rustc_hir",
"rustc_index",
"rustc_session",
"rustc_span",
"rustc_target",
"serialize",
@ -3933,6 +3937,7 @@ dependencies = [
"rustc_infer",
"rustc_lexer",
"rustc_macros",
"rustc_session",
"rustc_span",
"rustc_target",
"rustc_trait_selection",
@ -4013,6 +4018,7 @@ dependencies = [
"rustc_hir",
"rustc_lint",
"rustc_metadata",
"rustc_session",
"rustc_span",
]
@ -4027,6 +4033,7 @@ dependencies = [
"rustc_data_structures",
"rustc_errors",
"rustc_hir",
"rustc_session",
"rustc_span",
"rustc_typeck",
]
@ -4068,6 +4075,7 @@ dependencies = [
"rustc_data_structures",
"rustc_hir",
"rustc_parse",
"rustc_session",
"rustc_span",
"serde_json",
]
@ -4174,6 +4182,7 @@ dependencies = [
"rustc_data_structures",
"rustc_hir",
"rustc_infer",
"rustc_session",
"rustc_span",
"rustc_target",
"rustc_trait_selection",
@ -4193,6 +4202,7 @@ dependencies = [
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_session",
"rustc_span",
"rustc_target",
"rustc_trait_selection",

View File

@ -37,6 +37,9 @@ struct RustfmtConfig {
}
pub fn format(build: &Build, check: bool) {
if build.config.dry_run {
return;
}
let mut builder = ignore::types::TypesBuilder::new();
builder.add_defaults();
builder.select("rust");

View File

@ -6,8 +6,6 @@
//! Emscripten's runtime always implements those APIs and does not
//! implement libunwind.
#![allow(private_no_mangle_fns)]
use alloc::boxed::Box;
use core::any::Any;
use core::mem;

View File

@ -36,8 +36,6 @@
//! Once stack has been unwound down to the handler frame level, unwinding stops
//! and the last personality routine transfers control to the catch block.
#![allow(private_no_mangle_fns)]
use alloc::boxed::Box;
use core::any::Any;

View File

@ -45,7 +45,6 @@
//! [llvm]: http://llvm.org/docs/ExceptionHandling.html#background-on-windows-exceptions
#![allow(nonstandard_style)]
#![allow(private_no_mangle_fns)]
use alloc::boxed::Box;
use core::any::Any;

View File

@ -346,7 +346,7 @@ impl<'hir> Map<'hir> {
}
fn get_entry(&self, id: HirId) -> Entry<'hir> {
if id.local_id == ItemLocalId::from_u32_const(0) {
if id.local_id == ItemLocalId::from_u32(0) {
let owner = self.tcx.hir_owner(id.owner_def_id());
Entry { parent: owner.parent, node: owner.node }
} else {

View File

@ -1,8 +1,6 @@
use crate::hir::map::definitions::Definitions;
use crate::hir::map::DefPathHash;
use crate::hir::map::definitions::{DefPathHash, Definitions};
use crate::ich::{self, CachingSourceMapView};
use crate::middle::cstore::CrateStore;
use crate::session::Session;
use crate::ty::{fast_reject, TyCtxt};
use rustc_ast::ast;
@ -11,6 +9,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::Lrc;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, DefIndex};
use rustc_session::Session;
use rustc_span::source_map::SourceMap;
use rustc_span::symbol::Symbol;
use rustc_span::{BytePos, SourceFile};

View File

@ -26,6 +26,9 @@
#![feature(bool_to_option)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(const_if_match)]
#![feature(const_fn)]
#![feature(const_panic)]
#![feature(const_transmute)]
#![feature(core_intrinsics)]
#![feature(drain_filter)]
@ -80,7 +83,6 @@ pub mod infer;
pub mod lint;
pub mod middle;
pub mod mir;
pub use rustc_session as session;
pub mod traits;
pub mod ty;

View File

@ -5,7 +5,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::{pluralize, Applicability, DiagnosticBuilder, DiagnosticId};
use rustc_hir::HirId;
pub use rustc_session::lint::{builtin, Level, Lint, LintId, LintPass};
use rustc_session::lint::{builtin, Level, Lint, LintId};
use rustc_session::{DiagnosticMessageId, Session};
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpan};

View File

@ -2,10 +2,9 @@
//! are *mostly* used as a part of that interface, but these should
//! probably get a better home if someone can find one.
use crate::hir::map as hir_map;
use crate::hir::map::definitions::{DefKey, DefPathTable};
use crate::session::search_paths::PathKind;
use crate::session::CrateDisambiguator;
pub use self::NativeLibraryKind::*;
use crate::hir::map::definitions::{DefKey, DefPath, DefPathHash, DefPathTable};
use crate::ty::TyCtxt;
use rustc_ast::ast;
@ -14,15 +13,16 @@ use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{self, MetadataRef};
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_macros::HashStable;
use rustc_session::search_paths::PathKind;
pub use rustc_session::utils::NativeLibraryKind;
use rustc_session::CrateDisambiguator;
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use rustc_target::spec::Target;
use std::any::Any;
use std::path::{Path, PathBuf};
pub use self::NativeLibraryKind::*;
pub use rustc_session::utils::NativeLibraryKind;
// lonely orphan structs and enums looking for a better home
/// Where a crate came from on the local filesystem. One of these three options
@ -197,8 +197,8 @@ pub trait CrateStore {
// resolve
fn def_key(&self, def: DefId) -> DefKey;
fn def_path(&self, def: DefId) -> hir_map::DefPath;
fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
fn def_path(&self, def: DefId) -> DefPath;
fn def_path_hash(&self, def: DefId) -> DefPathHash;
fn def_path_table(&self, cnum: CrateNum) -> &DefPathTable;
// "queries" used in resolve that aren't tracked for incremental compilation

View File

@ -4,7 +4,7 @@
//! For all the gory details, see the provider of the `dependency_formats`
//! query.
use crate::session::config;
use rustc_session::config;
/// A list of dependencies for a certain crate type.
///

View File

@ -5,13 +5,13 @@
//! this via an attribute on the crate like `#![recursion_limit="22"]`. This pass
//! just peeks and looks for that attribute.
use crate::session::Session;
use core::num::IntErrorKind;
use rustc::bug;
use rustc_ast::ast;
use rustc_data_structures::sync::Once;
use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol};
use rustc_data_structures::sync::Once;
use std::num::IntErrorKind;
pub fn update_limits(sess: &Session, krate: &ast::Crate) {
update_limit(sess, krate, &sess.recursion_limit, sym::recursion_limit, 128);

View File

@ -3,7 +3,6 @@
pub use self::StabilityLevel::*;
use crate::session::{DiagnosticMessageId, Session};
use crate::ty::{self, TyCtxt};
use rustc_ast::ast::CRATE_NODE_ID;
use rustc_attr::{self as attr, ConstStability, Deprecation, RustcDeprecation, Stability};
@ -17,6 +16,7 @@ use rustc_hir::{self, HirId};
use rustc_session::lint::builtin::{DEPRECATED, DEPRECATED_IN_FUTURE, SOFT_UNSTABLE};
use rustc_session::lint::{BuiltinLintDiagnostics, Lint, LintBuffer};
use rustc_session::parse::feature_err_issue;
use rustc_session::{DiagnosticMessageId, Session};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{MultiSpan, Span};

View File

@ -41,6 +41,7 @@ pub struct Allocation<Tag = (), Extra = ()> {
/// The size of the allocation. Currently, must always equal `bytes.len()`.
pub size: Size,
/// The alignment of the allocation to detect unaligned reads.
/// (`Align` guarantees that this is a power of two.)
pub align: Align,
/// `true` if the allocation is mutable.
/// Also used by codegen to determine if a static should be put into mutable memory,
@ -314,7 +315,7 @@ impl<'tcx, Tag: Copy, Extra: AllocationExtra<Tag>> Allocation<Tag, Extra> {
&self.get_bytes(cx, ptr, size_with_null)?[..size]
}
// This includes the case where `offset` is out-of-bounds to begin with.
None => throw_unsup!(UnterminatedCString(ptr.erase_tag())),
None => throw_ub!(UnterminatedCString(ptr.erase_tag())),
})
}
@ -573,7 +574,7 @@ impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
fn check_defined(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
self.undef_mask
.is_range_defined(ptr.offset, ptr.offset + size)
.or_else(|idx| throw_unsup!(ReadUndefBytes(idx)))
.or_else(|idx| throw_ub!(InvalidUndefBytes(Some(Pointer::new(ptr.alloc_id, idx)))))
}
pub fn mark_definedness(&mut self, ptr: Pointer<Tag>, size: Size, new_state: bool) {

View File

@ -1,7 +1,6 @@
use super::{CheckInAllocMsg, Pointer, RawConst, ScalarMaybeUndef};
use super::{AllocId, CheckInAllocMsg, Pointer, RawConst, ScalarMaybeUndef};
use crate::hir::map::definitions::DefPathData;
use crate::mir;
use crate::mir::interpret::ConstValue;
use crate::ty::layout::{Align, LayoutError, Size};
use crate::ty::query::TyCtxtAt;
@ -14,8 +13,7 @@ use rustc_errors::{struct_span_err, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_macros::HashStable;
use rustc_session::CtfeBacktrace;
use rustc_span::{Pos, Span};
use rustc_target::spec::abi::Abi;
use rustc_span::{def_id::DefId, Pos, Span};
use std::{any::Any, fmt};
#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)]
@ -296,6 +294,8 @@ pub enum InvalidProgramInfo<'tcx> {
TypeckError,
/// An error occurred during layout computation.
Layout(layout::LayoutError<'tcx>),
/// An invalid transmute happened.
TransmuteSizeDiff(Ty<'tcx>, Ty<'tcx>),
}
impl fmt::Debug for InvalidProgramInfo<'_> {
@ -306,6 +306,11 @@ impl fmt::Debug for InvalidProgramInfo<'_> {
ReferencedConstant => write!(f, "referenced constant has errors"),
TypeckError => write!(f, "encountered constants with type errors, stopping evaluation"),
Layout(ref err) => write!(f, "{}", err),
TransmuteSizeDiff(from_ty, to_ty) => write!(
f,
"tried to transmute from {:?} to {:?}, but their sizes differed",
from_ty, to_ty
),
}
}
}
@ -321,7 +326,10 @@ pub enum UndefinedBehaviorInfo {
/// An enum discriminant was set to a value which was outside the range of valid values.
InvalidDiscriminant(ScalarMaybeUndef),
/// A slice/array index projection went out-of-bounds.
BoundsCheckFailed { len: u64, index: u64 },
BoundsCheckFailed {
len: u64,
index: u64,
},
/// Something was divided by 0 (x / 0).
DivisionByZero,
/// Something was "remainded" by 0 (x % 0).
@ -330,6 +338,43 @@ pub enum UndefinedBehaviorInfo {
PointerArithOverflow,
/// Invalid metadata in a wide pointer (using `str` to avoid allocations).
InvalidMeta(&'static str),
/// Reading a C string that does not end within its allocation.
UnterminatedCString(Pointer),
/// Dereferencing a dangling pointer after it got freed.
PointerUseAfterFree(AllocId),
/// Used a pointer outside the bounds it is valid for.
PointerOutOfBounds {
ptr: Pointer,
msg: CheckInAllocMsg,
allocation_size: Size,
},
/// Used a pointer with bad alignment.
AlignmentCheckFailed {
required: Align,
has: Align,
},
/// Using an integer as a pointer in the wrong way.
InvalidIntPointerUsage(u64),
/// Writing to read-only memory.
WriteToReadOnly(AllocId),
/// Using a pointer-not-to-a-function as function pointer.
InvalidFunctionPointer(Pointer),
// Trying to access the data behind a function pointer.
DerefFunctionPointer(AllocId),
/// The value validity check found a problem.
/// Should only be thrown by `validity.rs` and always point out which part of the value
/// is the problem.
ValidationFailure(String),
/// Using a non-boolean `u8` as bool.
InvalidBool(u8),
/// Using a non-character `u32` as character.
InvalidChar(u32),
/// Using uninitialized data where it is not allowed.
InvalidUndefBytes(Option<Pointer>),
/// Working with a local that is not currently live.
DeadLocal,
/// Trying to read from the return place of a function.
ReadFromReturnPlace,
}
impl fmt::Debug for UndefinedBehaviorInfo {
@ -348,6 +393,50 @@ impl fmt::Debug for UndefinedBehaviorInfo {
RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"),
PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"),
InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {}", msg),
UnterminatedCString(p) => write!(
f,
"reading a null-terminated string starting at {:?} with no null found before end of allocation",
p,
),
PointerUseAfterFree(a) => {
write!(f, "pointer to {:?} was dereferenced after this allocation got freed", a)
}
PointerOutOfBounds { ptr, msg, allocation_size } => write!(
f,
"{} failed: pointer must be in-bounds at offset {}, \
but is outside bounds of {} which has size {}",
msg,
ptr.offset.bytes(),
ptr.alloc_id,
allocation_size.bytes()
),
InvalidIntPointerUsage(0) => write!(f, "invalid use of NULL pointer"),
InvalidIntPointerUsage(i) => write!(f, "invalid use of {} as a pointer", i),
AlignmentCheckFailed { required, has } => write!(
f,
"accessing memory with alignment {}, but alignment {} is required",
has.bytes(),
required.bytes()
),
WriteToReadOnly(a) => write!(f, "writing to {:?} which is read-only", a),
InvalidFunctionPointer(p) => {
write!(f, "using {:?} as function pointer but it does not point to a function", p)
}
DerefFunctionPointer(a) => write!(f, "accessing {:?} which contains a function", a),
ValidationFailure(ref err) => write!(f, "type validation failed: {}", err),
InvalidBool(b) => write!(f, "interpreting an invalid 8-bit value as a bool: {}", b),
InvalidChar(c) => write!(f, "interpreting an invalid 32-bit value as a char: {}", c),
InvalidUndefBytes(Some(p)) => write!(
f,
"reading uninitialized memory at {:?}, but this operation requires initialized memory",
p
),
InvalidUndefBytes(None) => write!(
f,
"using uninitialized data, but this operation requires initialized memory"
),
DeadLocal => write!(f, "accessing a dead local variable"),
ReadFromReturnPlace => write!(f, "tried to read from the return place"),
}
}
}
@ -359,203 +448,45 @@ impl fmt::Debug for UndefinedBehaviorInfo {
///
/// Currently, we also use this as fall-back error kind for errors that have not been
/// categorized yet.
pub enum UnsupportedOpInfo<'tcx> {
pub enum UnsupportedOpInfo {
/// Free-form case. Only for errors that are never caught!
Unsupported(String),
/// When const-prop encounters a situation it does not support, it raises this error.
/// This must not allocate for performance reasons (hence `str`, not `String`).
ConstPropUnsupported(&'static str),
// -- Everything below is not categorized yet --
FunctionAbiMismatch(Abi, Abi),
FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionArgCountMismatch,
UnterminatedCString(Pointer),
DanglingPointerDeref,
DoubleFree,
InvalidMemoryAccess,
InvalidFunctionPointer,
InvalidBool,
PointerOutOfBounds {
ptr: Pointer,
msg: CheckInAllocMsg,
allocation_size: Size,
},
InvalidNullPointerUsage,
ReadPointerAsBytes,
ReadBytesAsPointer,
ReadForeignStatic,
InvalidPointerMath,
ReadUndefBytes(Size),
DeadLocal,
InvalidBoolOp(mir::BinOp),
UnimplementedTraitSelection,
CalledClosureAsFunction,
NoMirFor(String),
DerefFunctionPointer,
ExecuteMemory,
InvalidChar(u128),
OutOfTls,
TlsOutOfBounds,
AlignmentCheckFailed {
required: Align,
has: Align,
},
ValidationFailure(String),
VtableForArgumentlessMethod,
ModifiedConstantMemory,
/// Accessing an unsupported foreign static.
ReadForeignStatic(DefId),
/// Could not find MIR for a function.
NoMirFor(DefId),
/// Modified a static during const-eval.
/// FIXME: move this to `ConstEvalErrKind` through a machine hook.
ModifiedStatic,
TypeNotPrimitive(Ty<'tcx>),
ReallocatedWrongMemoryKind(String, String),
DeallocatedWrongMemoryKind(String, String),
ReallocateNonBasePtr,
DeallocateNonBasePtr,
IncorrectAllocationInformation(Size, Size, Align, Align),
HeapAllocZeroBytes,
HeapAllocNonPowerOfTwoAlignment(u64),
ReadFromReturnPointer,
PathNotFound(Vec<String>),
TransmuteSizeDiff(Ty<'tcx>, Ty<'tcx>),
/// Encountered a pointer where we needed raw bytes.
ReadPointerAsBytes,
/// Encountered raw bytes where we needed a pointer.
ReadBytesAsPointer,
}
impl fmt::Debug for UnsupportedOpInfo<'tcx> {
impl fmt::Debug for UnsupportedOpInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use UnsupportedOpInfo::*;
match self {
PointerOutOfBounds { ptr, msg, allocation_size } => write!(
f,
"{} failed: pointer must be in-bounds at offset {}, \
but is outside bounds of allocation {} which has size {}",
msg,
ptr.offset.bytes(),
ptr.alloc_id,
allocation_size.bytes()
),
ValidationFailure(ref err) => write!(f, "type validation failed: {}", err),
NoMirFor(ref func) => write!(f, "no MIR for `{}`", func),
FunctionAbiMismatch(caller_abi, callee_abi) => write!(
f,
"tried to call a function with ABI {:?} using caller ABI {:?}",
callee_abi, caller_abi
),
FunctionArgMismatch(caller_ty, callee_ty) => write!(
f,
"tried to call a function with argument of type {:?} \
passing data of type {:?}",
callee_ty, caller_ty
),
TransmuteSizeDiff(from_ty, to_ty) => write!(
f,
"tried to transmute from {:?} to {:?}, but their sizes differed",
from_ty, to_ty
),
FunctionRetMismatch(caller_ty, callee_ty) => write!(
f,
"tried to call a function with return type {:?} \
passing return place of type {:?}",
callee_ty, caller_ty
),
FunctionArgCountMismatch => {
write!(f, "tried to call a function with incorrect number of arguments")
Unsupported(ref msg) => write!(f, "{}", msg),
ConstPropUnsupported(ref msg) => {
write!(f, "Constant propagation encountered an unsupported situation: {}", msg)
}
ReallocatedWrongMemoryKind(ref old, ref new) => {
write!(f, "tried to reallocate memory from `{}` to `{}`", old, new)
ReadForeignStatic(did) => {
write!(f, "tried to read from foreign (extern) static {:?}", did)
}
DeallocatedWrongMemoryKind(ref old, ref new) => {
write!(f, "tried to deallocate `{}` memory but gave `{}` as the kind", old, new)
}
InvalidChar(c) => {
write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c)
}
AlignmentCheckFailed { required, has } => write!(
f,
"tried to access memory with alignment {}, but alignment {} is required",
has.bytes(),
required.bytes()
),
TypeNotPrimitive(ty) => write!(f, "expected primitive type, got {}", ty),
PathNotFound(ref path) => write!(f, "cannot find path {:?}", path),
IncorrectAllocationInformation(size, size2, align, align2) => write!(
f,
"incorrect alloc info: expected size {} and align {}, \
got size {} and align {}",
size.bytes(),
align.bytes(),
size2.bytes(),
align2.bytes()
),
InvalidMemoryAccess => write!(f, "tried to access memory through an invalid pointer"),
DanglingPointerDeref => write!(f, "dangling pointer was dereferenced"),
DoubleFree => write!(f, "tried to deallocate dangling pointer"),
InvalidFunctionPointer => {
write!(f, "tried to use a function pointer after offsetting it")
}
InvalidBool => write!(f, "invalid boolean value read"),
InvalidNullPointerUsage => write!(f, "invalid use of NULL pointer"),
ReadPointerAsBytes => write!(
f,
"a raw memory access tried to access part of a pointer value as raw \
bytes"
),
ReadBytesAsPointer => {
write!(f, "a memory access tried to interpret some bytes as a pointer")
}
ReadForeignStatic => write!(f, "tried to read from foreign (extern) static"),
InvalidPointerMath => write!(
f,
"attempted to do invalid arithmetic on pointers that would leak base \
addresses, e.g., comparing pointers into different allocations"
),
DeadLocal => write!(f, "tried to access a dead local variable"),
DerefFunctionPointer => write!(f, "tried to dereference a function pointer"),
ExecuteMemory => write!(f, "tried to treat a memory pointer as a function pointer"),
OutOfTls => write!(f, "reached the maximum number of representable TLS keys"),
TlsOutOfBounds => write!(f, "accessed an invalid (unallocated) TLS key"),
CalledClosureAsFunction => {
write!(f, "tried to call a closure through a function pointer")
}
VtableForArgumentlessMethod => {
write!(f, "tried to call a vtable function without arguments")
}
ModifiedConstantMemory => write!(f, "tried to modify constant memory"),
NoMirFor(did) => write!(f, "could not load MIR for {:?}", did),
ModifiedStatic => write!(
f,
"tried to modify a static's initial value from another static's \
initializer"
),
ReallocateNonBasePtr => write!(
f,
"tried to reallocate with a pointer not to the beginning of an \
existing object"
),
DeallocateNonBasePtr => write!(
f,
"tried to deallocate with a pointer not to the beginning of an \
existing object"
),
HeapAllocZeroBytes => write!(f, "tried to re-, de- or allocate zero bytes on the heap"),
ReadFromReturnPointer => write!(f, "tried to read from the return pointer"),
UnimplementedTraitSelection => {
write!(f, "there were unresolved type arguments during trait selection")
}
InvalidBoolOp(_) => write!(f, "invalid boolean operation"),
UnterminatedCString(_) => write!(
f,
"attempted to get length of a null-terminated string, but no null \
found before end of allocation"
),
ReadUndefBytes(_) => write!(f, "attempted to read undefined bytes"),
HeapAllocNonPowerOfTwoAlignment(_) => write!(
f,
"tried to re-, de-, or allocate heap memory with alignment that is \
not a power of two"
),
Unsupported(ref msg) => write!(f, "{}", msg),
ConstPropUnsupported(ref msg) => {
write!(f, "Constant propagation encountered an unsupported situation: {}", msg)
}
ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes",),
ReadBytesAsPointer => write!(f, "unable to turn bytes into a pointer"),
}
}
}
@ -590,7 +521,7 @@ pub enum InterpError<'tcx> {
UndefinedBehavior(UndefinedBehaviorInfo),
/// The program did something the interpreter does not support (some of these *might* be UB
/// but the interpreter is not sure).
Unsupported(UnsupportedOpInfo<'tcx>),
Unsupported(UnsupportedOpInfo),
/// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
InvalidProgram(InvalidProgramInfo<'tcx>),
/// The program exhausted the interpreter's resources (stack/heap too big,
@ -606,7 +537,7 @@ pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
impl fmt::Display for InterpError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Forward `Display` to `Debug`.
write!(f, "{:?}", self)
fmt::Debug::fmt(self, f)
}
}
@ -631,7 +562,7 @@ impl InterpError<'_> {
match self {
InterpError::MachineStop(_)
| InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_))
| InterpError::Unsupported(UnsupportedOpInfo::ValidationFailure(_))
| InterpError::UndefinedBehavior(UndefinedBehaviorInfo::ValidationFailure(_))
| InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
| InterpError::UndefinedBehavior(UndefinedBehaviorInfo::UbExperimental(_)) => true,
_ => false,

View File

@ -161,7 +161,13 @@ pub struct AllocId(pub u64);
impl fmt::Debug for AllocId {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "alloc{}", self.0)
fmt::Display::fmt(self, fmt)
}
}
impl fmt::Display for AllocId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "alloc{}", self.0)
}
}
@ -351,12 +357,6 @@ impl<'s> AllocDecodingSession<'s> {
}
}
impl fmt::Display for AllocId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// An allocation in the global (tcx-managed) memory can be either a function pointer,
/// a static, or a "real" allocation with some data in it.
#[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]

View File

@ -213,20 +213,4 @@ impl<'tcx, Tag> Pointer<Tag> {
pub fn erase_tag(self) -> Pointer {
Pointer { alloc_id: self.alloc_id, offset: self.offset, tag: () }
}
/// Test if the pointer is "inbounds" of an allocation of the given size.
/// A pointer is "inbounds" even if its offset is equal to the size; this is
/// a "one-past-the-end" pointer.
#[inline(always)]
pub fn check_inbounds_alloc(
self,
allocation_size: Size,
msg: CheckInAllocMsg,
) -> InterpResult<'tcx, ()> {
if self.offset > allocation_size {
throw_unsup!(PointerOutOfBounds { ptr: self.erase_tag(), msg, allocation_size })
} else {
Ok(())
}
}
}

View File

@ -455,10 +455,11 @@ impl<'tcx, Tag> Scalar<Tag> {
}
pub fn to_bool(self) -> InterpResult<'tcx, bool> {
match self {
Scalar::Raw { data: 0, size: 1 } => Ok(false),
Scalar::Raw { data: 1, size: 1 } => Ok(true),
_ => throw_unsup!(InvalidBool),
let val = self.to_u8()?;
match val {
0 => Ok(false),
1 => Ok(true),
_ => throw_ub!(InvalidBool(val)),
}
}
@ -466,7 +467,7 @@ impl<'tcx, Tag> Scalar<Tag> {
let val = self.to_u32()?;
match ::std::char::from_u32(val) {
Some(c) => Ok(c),
None => throw_unsup!(InvalidChar(val as u128)),
None => throw_ub!(InvalidChar(val)),
}
}
@ -609,7 +610,7 @@ impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
pub fn not_undef(self) -> InterpResult<'static, Scalar<Tag>> {
match self {
ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
ScalarMaybeUndef::Undef => throw_unsup!(ReadUndefBytes(Size::ZERO)),
ScalarMaybeUndef::Undef => throw_ub!(InvalidUndefBytes(None)),
}
}

View File

@ -1,6 +1,5 @@
use crate::dep_graph::{DepConstructor, DepNode, WorkProduct, WorkProductId};
use crate::ich::{Fingerprint, NodeIdHashingMode, StableHashingContext};
use crate::session::config::OptLevel;
use crate::ty::print::obsolete::DefPathBasedNames;
use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt};
use rustc_attr::InlineAttr;
@ -9,6 +8,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_hir::HirId;
use rustc_session::config::OptLevel;
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
use std::fmt;

View File

@ -23,7 +23,6 @@ use crate::mir::{
};
use crate::traits;
use crate::traits::{Clause, Clauses, Goal, GoalKind, Goals};
use crate::ty::free_region_map::FreeRegionMap;
use crate::ty::layout::{LayoutDetails, TargetDataLayout, VariantIdx};
use crate::ty::query;
use crate::ty::steal::Steal;
@ -416,11 +415,6 @@ pub struct TypeckTables<'tcx> {
/// this field will be set to `true`.
pub tainted_by_errors: bool,
/// Stores the free-region relationships that were deduced from
/// its where-clauses and parameter types. These are then
/// read-again by borrowck.
pub free_region_map: FreeRegionMap<'tcx>,
/// All the opaque types that are restricted to concrete types
/// by this function.
pub concrete_opaque_types: FxHashMap<DefId, ResolvedOpaqueTy<'tcx>>,
@ -456,7 +450,6 @@ impl<'tcx> TypeckTables<'tcx> {
coercion_casts: Default::default(),
used_trait_imports: Lrc::new(Default::default()),
tainted_by_errors: false,
free_region_map: Default::default(),
concrete_opaque_types: Default::default(),
upvar_list: Default::default(),
generator_interior_types: Default::default(),
@ -719,7 +712,6 @@ impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
ref used_trait_imports,
tainted_by_errors,
ref free_region_map,
ref concrete_opaque_types,
ref upvar_list,
ref generator_interior_types,
@ -757,7 +749,6 @@ impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TypeckTables<'tcx> {
coercion_casts.hash_stable(hcx, hasher);
used_trait_imports.hash_stable(hcx, hasher);
tainted_by_errors.hash_stable(hcx, hasher);
free_region_map.hash_stable(hcx, hasher);
concrete_opaque_types.hash_stable(hcx, hasher);
upvar_list.hash_stable(hcx, hasher);
generator_interior_types.hash_stable(hcx, hasher);

View File

@ -1,9 +1,21 @@
use crate::session::{self, DataTypeKind};
use crate::ich::StableHashingContext;
use crate::mir::{GeneratorLayout, GeneratorSavedLocal};
use crate::ty::subst::Subst;
use crate::ty::{self, subst::SubstsRef, ReprOptions, Ty, TyCtxt, TypeFoldable};
use rustc_ast::ast::{self, Ident, IntTy, UintTy};
use rustc_attr as attr;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_session::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
use rustc_span::DUMMY_SP;
use rustc_target::abi::call::{
ArgAbi, ArgAttribute, ArgAttributes, Conv, FnAbi, PassMode, Reg, RegKind,
};
pub use rustc_target::abi::*;
use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec};
use std::cmp;
use std::fmt;
@ -11,20 +23,6 @@ use std::iter;
use std::mem;
use std::ops::Bound;
use crate::ich::StableHashingContext;
use crate::mir::{GeneratorLayout, GeneratorSavedLocal};
use crate::ty::subst::Subst;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_target::abi::call::{
ArgAbi, ArgAttribute, ArgAttributes, Conv, FnAbi, PassMode, Reg, RegKind,
};
pub use rustc_target::abi::*;
use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec};
pub trait IntegerExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx>;
fn from_attr<C: HasDataLayout>(cx: &C, ity: attr::IntType) -> Integer;
@ -1409,12 +1407,15 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
// locals as part of the prefix. We compute the layout of all of
// these fields at once to get optimal packing.
let discr_index = substs.as_generator().prefix_tys(def_id, tcx).count();
// FIXME(eddyb) set the correct vaidity range for the discriminant.
let discr_layout = self.layout_of(substs.as_generator().discr_ty(tcx))?;
let discr = match &discr_layout.abi {
Abi::Scalar(s) => s.clone(),
_ => bug!(),
};
// `info.variant_fields` already accounts for the reserved variants, so no need to add them.
let max_discr = (info.variant_fields.len() - 1) as u128;
let discr_int = Integer::fit_unsigned(max_discr);
let discr_int_ty = discr_int.to_ty(tcx, false);
let discr = Scalar { value: Primitive::Int(discr_int, false), valid_range: 0..=max_discr };
let discr_layout = self.tcx.intern_layout(LayoutDetails::scalar(self, discr.clone()));
let discr_layout = TyLayout { ty: discr_int_ty, details: discr_layout };
let promoted_layouts = ineligible_locals
.iter()
.map(|local| subst_field(info.field_tys[local]))
@ -1648,7 +1649,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
if min_size < field_end {
min_size = field_end;
}
session::FieldInfo {
FieldInfo {
name: name.to_string(),
offset: offset.bytes(),
size: field_layout.size.bytes(),
@ -1658,13 +1659,9 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
})
.collect();
session::VariantInfo {
VariantInfo {
name: n.map(|n| n.to_string()),
kind: if layout.is_unsized() {
session::SizeKind::Min
} else {
session::SizeKind::Exact
},
kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
align: layout.align.abi.bytes(),
size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
fields: field_info,

View File

@ -9,7 +9,6 @@ pub use self::Variance::*;
use crate::arena::Arena;
use crate::hir::exports::ExportMap;
use crate::hir::map as hir_map;
use crate::ich::Fingerprint;
use crate::ich::StableHashingContext;
use crate::infer::canonical::Canonical;
@ -19,7 +18,6 @@ use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
use crate::mir::interpret::ErrorHandled;
use crate::mir::GeneratorLayout;
use crate::mir::ReadOnlyBodyAndCache;
use crate::session::DataTypeKind;
use crate::traits::{self, Reveal};
use crate::ty;
use crate::ty::layout::VariantIdx;
@ -42,6 +40,7 @@ use rustc_hir::{Constness, GlobMap, Node, TraitMap};
use rustc_index::vec::{Idx, IndexVec};
use rustc_macros::HashStable;
use rustc_serialize::{self, Encodable, Encoder};
use rustc_session::DataTypeKind;
use rustc_span::hygiene::ExpnId;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::Span;
@ -1700,7 +1699,7 @@ rustc_index::newtype_index! {
}
impl UniverseIndex {
pub const ROOT: UniverseIndex = UniverseIndex::from_u32_const(0);
pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
/// Returns the "next" universe index in order -- this new index
/// is considered to extend all previous universes. This

View File

@ -19,8 +19,6 @@ use crate::mir::interpret::GlobalId;
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult, ConstValue};
use crate::mir::interpret::{LitToConstError, LitToConstInput};
use crate::mir::mono::CodegenUnit;
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
use crate::session::CrateDisambiguator;
use crate::traits::query::{
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal,
@ -49,6 +47,8 @@ use rustc_hir::def::DefKind;
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, DefIndex};
use rustc_hir::{Crate, HirIdSet, ItemLocalId, TraitCandidate};
use rustc_index::vec::IndexVec;
use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
use rustc_session::CrateDisambiguator;
use rustc_target::spec::PanicStrategy;
use rustc_ast::ast;

View File

@ -3,7 +3,6 @@ use crate::hir::map::definitions::DefPathHash;
use crate::ich::{CachingSourceMapView, Fingerprint};
use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
use crate::mir::{self, interpret};
use crate::session::{CrateDisambiguator, Session};
use crate::ty::codec::{self as ty_codec, TyDecoder, TyEncoder};
use crate::ty::context::TyCtxt;
use crate::ty::{self, Ty};
@ -19,6 +18,7 @@ use rustc_serialize::{
opaque, Decodable, Decoder, Encodable, Encoder, SpecializedDecoder, SpecializedEncoder,
UseSpecializedDecodable, UseSpecializedEncodable,
};
use rustc_session::{CrateDisambiguator, Session};
use rustc_span::hygiene::{ExpnId, SyntaxContext};
use rustc_span::source_map::{SourceMap, StableSourceFileId};
use rustc_span::{BytePos, SourceFile, Span, DUMMY_SP};

View File

@ -2153,7 +2153,7 @@ impl FnRetTy {
/// Module declaration.
///
/// E.g., `mod foo;` or `mod foo { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
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

View File

@ -7,7 +7,9 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", test(attr(deny(warnings))))]
#![feature(bool_to_option)]
#![feature(box_syntax)]
#![feature(const_if_match)]
#![feature(const_fn)] // For the `transmute` in `P::new`
#![feature(const_panic)]
#![feature(const_transmute)]
#![feature(crate_visibility_modifier)]
#![feature(label_break_value)]

View File

@ -12,7 +12,7 @@ rustc_index::newtype_index! {
rustc_data_structures::define_id_collections!(NodeMap, NodeSet, NodeId);
/// `NodeId` used to represent the root of the crate.
pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
pub const CRATE_NODE_ID: NodeId = NodeId::from_u32(0);
/// When parsing and doing expansions, we initially give all AST nodes this AST
/// node value. Then later, in the renumber pass, we renumber them to have

View File

@ -37,7 +37,6 @@
use rustc::arena::Arena;
use rustc::dep_graph::DepGraph;
use rustc::hir::map::definitions::{DefKey, DefPathData, Definitions};
use rustc::hir::map::Map;
use rustc::{bug, span_bug};
use rustc_ast::ast;
use rustc_ast::ast::*;
@ -1463,7 +1462,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
impl<'r, 'a, 'v, 'hir> intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> {
type Map = Map<'v>;
type Map = intravisit::ErasedMap<'v>;
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
intravisit::NestedVisitorMap::None

View File

@ -1,7 +1,6 @@
use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
use super::{GenericArgsCtor, ParenthesizedGenericArgs};
use rustc::lint::builtin::ELIDED_LIFETIMES_IN_PATHS;
use rustc::span_bug;
use rustc_ast::ast::{self, *};
use rustc_errors::{struct_span_err, Applicability};
@ -9,6 +8,7 @@ use rustc_hir as hir;
use rustc_hir::def::{DefKind, PartialRes, Res};
use rustc_hir::def_id::DefId;
use rustc_hir::GenericArg;
use rustc_session::lint::builtin::ELIDED_LIFETIMES_IN_PATHS;
use rustc_session::lint::BuiltinLintDiagnostics;
use rustc_span::Span;

View File

@ -148,12 +148,19 @@ pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
// This makes comma-separated lists look slightly nicer,
// and also addresses a specific regression described in issue #63896.
fn tt_prepend_space(tt: &TokenTree) -> bool {
fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool {
match tt {
TokenTree::Token(token) => match token.kind {
token::Comma => false,
_ => true,
},
TokenTree::Delimited(_, DelimToken::Paren, _) => match prev {
TokenTree::Token(token) => match token.kind {
token::Ident(_, _) => false,
_ => true,
},
_ => true,
},
_ => true,
}
}
@ -650,11 +657,14 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
}
fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
for (i, tt) in tts.into_trees().enumerate() {
if i != 0 && tt_prepend_space(&tt) {
let mut iter = tts.into_trees().peekable();
while let Some(tt) = iter.next() {
let show_space =
if let Some(next) = iter.peek() { tt_prepend_space(next, &tt) } else { false };
self.print_tt(tt, convert_dollar_crate);
if show_space {
self.space();
}
self.print_tt(tt, convert_dollar_crate);
}
}

View File

@ -59,7 +59,7 @@ pub fn inject(
handler: &rustc_errors::Handler,
) -> ast::Crate {
let ecfg = ExpansionConfig::default("proc_macro".to_string());
let mut cx = ExtCtxt::new(sess, ecfg, resolver);
let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
let mut collect = CollectProcMacros {
macros: Vec::new(),

View File

@ -5,7 +5,7 @@ use rustc_ast::tokenstream::TokenStream;
use rustc_ast_pretty::pprust;
use rustc_expand::base::{self, *};
use rustc_expand::panictry;
use rustc_parse::{self, new_sub_parser_from_file, parser::Parser, DirectoryOwnership};
use rustc_parse::{self, new_sub_parser_from_file, parser::Parser};
use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
use rustc_span::symbol::Symbol;
use rustc_span::{self, Pos, Span};
@ -108,8 +108,7 @@ pub fn expand_include<'cx>(
return DummyResult::any(sp);
}
};
let directory_ownership = DirectoryOwnership::Owned { relative: None };
let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
let p = new_sub_parser_from_file(cx.parse_sess(), &file, None, sp);
struct ExpandResult<'a> {
p: Parser<'a>,

View File

@ -39,7 +39,7 @@ pub fn inject(
let call_site = DUMMY_SP.with_call_site_ctxt(expn_id);
let ecfg = ExpansionConfig::default("std_lib_injection".to_string());
let cx = ExtCtxt::new(sess, ecfg, resolver);
let cx = ExtCtxt::new(sess, ecfg, resolver, None);
// .rev() to preserve ordering above in combination with insert(0, ...)
for &name in names.iter().rev() {

View File

@ -202,7 +202,7 @@ fn generate_test_harness(
let mut econfig = ExpansionConfig::default("test".to_string());
econfig.features = Some(features);
let ext_cx = ExtCtxt::new(sess, econfig, resolver);
let ext_cx = ExtCtxt::new(sess, econfig, resolver, None);
let expn_id = ext_cx.resolver.expansion_for_ast_pass(
DUMMY_SP,

View File

@ -3,8 +3,6 @@
use std::ffi::CString;
use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc::session::config::{OptLevel, Sanitizer};
use rustc::session::Session;
use rustc::ty::layout::HasTyCtxt;
use rustc::ty::query::Providers;
use rustc::ty::{self, Ty, TyCtxt};
@ -13,6 +11,8 @@ use rustc_data_structures::const_cstr;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_session::config::{OptLevel, Sanitizer};
use rustc_session::Session;
use rustc_target::abi::call::Conv;
use rustc_target::spec::PanicStrategy;

View File

@ -9,9 +9,9 @@ use std::str;
use crate::llvm::archive_ro::{ArchiveRO, Child};
use crate::llvm::{self, ArchiveKind};
use rustc::session::Session;
use rustc_codegen_ssa::back::archive::{find_library, ArchiveBuilder};
use rustc_codegen_ssa::{looks_like_rust_object_file, METADATA_FILENAME, RLIB_BYTECODE_EXTENSION};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
struct ArchiveConfig<'a> {

View File

@ -9,7 +9,6 @@ use log::{debug, info};
use rustc::bug;
use rustc::dep_graph::WorkProduct;
use rustc::middle::exported_symbols::SymbolExportLevel;
use rustc::session::config::{self, Lto};
use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared};
use rustc_codegen_ssa::back::symbol_export;
use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
@ -19,6 +18,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{FatalError, Handler};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_session::cgu_reuse_tracker::CguReuse;
use rustc_session::config::{self, Lto};
use std::ffi::{CStr, CString};
use std::fs::File;

View File

@ -15,8 +15,6 @@ use crate::LlvmCodegenBackend;
use crate::ModuleLlvm;
use log::debug;
use rustc::bug;
use rustc::session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
use rustc::session::Session;
use rustc::ty::TyCtxt;
use rustc_codegen_ssa::back::write::{run_assembler, CodegenContext, ModuleConfig};
use rustc_codegen_ssa::traits::*;
@ -25,6 +23,8 @@ use rustc_data_structures::small_c_str::SmallCStr;
use rustc_errors::{FatalError, Handler};
use rustc_fs_util::{link_or_copy, path_to_c_string};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
use rustc_session::Session;
use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::ffi::CString;

View File

@ -28,13 +28,13 @@ use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
use rustc::middle::cstore::EncodedMetadata;
use rustc::middle::exported_symbols;
use rustc::mir::mono::{Linkage, Visibility};
use rustc::session::config::DebugInfo;
use rustc::ty::TyCtxt;
use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
use rustc_codegen_ssa::mono_item::MonoItemExt;
use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_session::config::DebugInfo;
use rustc_span::symbol::Symbol;
use std::ffi::CString;

View File

@ -7,7 +7,6 @@ use crate::type_of::LayoutLlvmExt;
use crate::value::Value;
use libc::{c_char, c_uint};
use log::debug;
use rustc::session::config::{self, Sanitizer};
use rustc::ty::layout::{self, Align, Size, TyLayout};
use rustc::ty::{self, Ty, TyCtxt};
use rustc_codegen_ssa::base::to_immediate;
@ -19,6 +18,7 @@ use rustc_codegen_ssa::MemFlags;
use rustc_data_structures::const_cstr;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_hir::def_id::DefId;
use rustc_session::config::{self, Sanitizer};
use rustc_target::spec::{HasTargetSpec, Target};
use std::borrow::Cow;
use std::ffi::CStr;

View File

@ -1,31 +1,30 @@
use crate::attributes;
use crate::callee::get_fn;
use crate::debuginfo;
use crate::llvm;
use crate::llvm_util;
use crate::value::Value;
use rustc::dep_graph::DepGraphSafe;
use crate::type_::Type;
use rustc_codegen_ssa::traits::*;
use crate::value::Value;
use crate::callee::get_fn;
use rustc::bug;
use rustc::dep_graph::DepGraphSafe;
use rustc::mir::mono::CodegenUnit;
use rustc::session::config::{self, CFGuard, DebugInfo};
use rustc::session::Session;
use rustc::ty::layout::{
HasParamEnv, LayoutError, LayoutOf, PointeeInfo, Size, TyLayout, VariantIdx,
};
use rustc::ty::{self, Instance, Ty, TyCtxt};
use rustc_codegen_ssa::base::wants_msvc_seh;
use rustc_codegen_ssa::traits::*;
use rustc_data_structures::base_n;
use rustc_data_structures::const_cstr;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_target::spec::{HasTargetSpec, Target};
use rustc_session::config::{self, CFGuard, DebugInfo};
use rustc_session::Session;
use rustc_span::source_map::{Span, DUMMY_SP};
use rustc_span::symbol::Symbol;
use rustc_target::spec::{HasTargetSpec, Target};
use std::cell::{Cell, RefCell};
use std::ffi::CStr;
use std::str;

View File

@ -6,8 +6,8 @@ use crate::builder::Builder;
use crate::common::CodegenCx;
use crate::value::Value;
use rustc::bug;
use rustc::session::config::DebugInfo;
use rustc_codegen_ssa::traits::*;
use rustc_session::config::DebugInfo;
use rustc_ast::attr;
use rustc_span::symbol::sym;

View File

@ -24,7 +24,6 @@ use rustc::ich::NodeIdHashingMode;
use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc::mir::interpret::truncate;
use rustc::mir::{self, Field, GeneratorLayout};
use rustc::session::config::{self, DebugInfo};
use rustc::ty::layout::{
self, Align, Integer, IntegerExt, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
};
@ -42,6 +41,7 @@ use rustc_fs_util::path_to_c_string;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_index::vec::{Idx, IndexVec};
use rustc_session::config::{self, DebugInfo};
use rustc_span::symbol::{Interner, Symbol};
use rustc_span::{self, FileName, Span};
use rustc_target::abi::HasDataLayout;

View File

@ -20,12 +20,12 @@ use crate::builder::Builder;
use crate::common::CodegenCx;
use crate::value::Value;
use rustc::mir;
use rustc::session::config::{self, DebugInfo};
use rustc::ty::{self, Instance, ParamEnv, Ty};
use rustc_codegen_ssa::debuginfo::type_names;
use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_index::vec::IndexVec;
use rustc_session::config::{self, DebugInfo};
use libc::c_uint;
use log::debug;

View File

@ -15,31 +15,30 @@
#![recursion_limit = "256"]
use back::write::{create_informational_target_machine, create_target_machine};
use rustc_span::symbol::Symbol;
pub use llvm_util::target_features;
use rustc::dep_graph::WorkProduct;
use rustc::dep_graph::{DepGraph, WorkProduct};
use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
use rustc::ty::{self, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc_ast::expand::allocator::AllocatorKind;
use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::ModuleCodegen;
use rustc_codegen_ssa::{CodegenResults, CompiledModule};
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_errors::{FatalError, Handler};
use rustc_serialize::json;
use rustc_session::config::{self, OptLevel, OutputFilenames, PrintRequest};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::any::Any;
use std::ffi::CStr;
use std::fs;
use std::sync::Arc;
use rustc::dep_graph::DepGraph;
use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
use rustc::session::config::{self, OptLevel, OutputFilenames, PrintRequest};
use rustc::session::Session;
use rustc::ty::{self, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc_codegen_ssa::ModuleCodegen;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_serialize::json;
mod back {
pub mod archive;
pub mod bytecode;

View File

@ -694,8 +694,8 @@ pub mod debuginfo {
}
impl DebugEmissionKind {
pub fn from_generic(kind: rustc::session::config::DebugInfo) -> Self {
use rustc::session::config::DebugInfo;
pub fn from_generic(kind: rustc_session::config::DebugInfo) -> Self {
use rustc_session::config::DebugInfo;
match kind {
DebugInfo::None => DebugEmissionKind::NoDebug,
DebugInfo::Limited => DebugEmissionKind::LineTablesOnly,

View File

@ -2,10 +2,10 @@ use crate::back::write::create_informational_target_machine;
use crate::llvm;
use libc::c_int;
use rustc::bug;
use rustc::session::config::PrintRequest;
use rustc::session::Session;
use rustc_data_structures::fx::FxHashSet;
use rustc_feature::UnstableFeatures;
use rustc_session::config::PrintRequest;
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::symbol::Symbol;
use rustc_target::spec::{MergeFunctions, PanicStrategy};

View File

@ -1,4 +1,4 @@
use rustc::session::Session;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;

View File

@ -1,15 +1,15 @@
use rustc::middle::cstore::{EncodedMetadata, LibSource, NativeLibrary, NativeLibraryKind};
use rustc::middle::dependency_format::Linkage;
use rustc::session::config::{
self, CFGuard, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer,
};
use rustc::session::search_paths::PathKind;
/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.
use rustc::session::{filesearch, Session};
use rustc_data_structures::fx::FxHashSet;
use rustc_fs_util::fix_windows_verbatim_for_gcc;
use rustc_hir::def_id::CrateNum;
use rustc_session::config::{
self, CFGuard, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer,
};
use rustc_session::search_paths::PathKind;
/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.
use rustc_session::{filesearch, Session};
use rustc_span::symbol::Symbol;
use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};

View File

@ -2,7 +2,6 @@ use super::archive;
use super::command::Command;
use super::symbol_export;
use rustc_data_structures::fx::FxHashMap;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File};
use std::io::prelude::*;
@ -10,11 +9,12 @@ use std::io::{self, BufWriter};
use std::path::{Path, PathBuf};
use rustc::middle::dependency_format::Linkage;
use rustc::session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
use rustc::session::Session;
use rustc::ty::TyCtxt;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_serialize::{json, Encoder};
use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use rustc_target::spec::{LinkerFlavor, LldFlavor};

View File

@ -3,7 +3,6 @@ use std::sync::Arc;
use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
use rustc::session::config::{self, Sanitizer};
use rustc::ty::query::Providers;
use rustc::ty::subst::{GenericArgKind, SubstsRef};
use rustc::ty::Instance;
@ -16,6 +15,7 @@ use rustc_hir as hir;
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::Node;
use rustc_index::vec::IndexVec;
use rustc_session::config::{self, Sanitizer};
pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
crates_export_threshold(&tcx.sess.crate_types.borrow())

View File

@ -14,10 +14,6 @@ use jobserver::{Acquired, Client};
use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
use rustc::middle::cstore::EncodedMetadata;
use rustc::middle::exported_symbols::SymbolExportLevel;
use rustc::session::config::{
self, Lto, OutputFilenames, OutputType, Passes, Sanitizer, SwitchWithOptPath,
};
use rustc::session::Session;
use rustc::ty::TyCtxt;
use rustc_ast::attr;
use rustc_data_structures::fx::FxHashMap;
@ -34,6 +30,10 @@ use rustc_incremental::{
copy_cgu_workproducts_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
};
use rustc_session::cgu_reuse_tracker::CguReuseTracker;
use rustc_session::config::{
self, Lto, OutputFilenames, OutputType, Passes, Sanitizer, SwitchWithOptPath,
};
use rustc_session::Session;
use rustc_span::hygiene::ExpnId;
use rustc_span::source_map::SourceMap;
use rustc_span::symbol::{sym, Symbol};

View File

@ -31,8 +31,6 @@ use rustc::middle::cstore::{self, LinkagePreference};
use rustc::middle::lang_items;
use rustc::middle::lang_items::StartFnLangItem;
use rustc::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
use rustc::session::config::{self, EntryFnType, Lto};
use rustc::session::Session;
use rustc::ty::layout::{self, Align, HasTyCtxt, LayoutOf, TyLayout, VariantIdx};
use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
use rustc::ty::query::Providers;
@ -46,6 +44,8 @@ use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_index::vec::Idx;
use rustc_session::cgu_reuse_tracker::CguReuse;
use rustc_session::config::{self, EntryFnType, Lto};
use rustc_session::Session;
use rustc_span::Span;
use std::cmp;

View File

@ -1,8 +1,8 @@
#![allow(non_camel_case_types, non_snake_case)]
use rustc::session::Session;
use rustc::ty::{Ty, TyCtxt};
use rustc_errors::struct_span_err;
use rustc_session::Session;
use rustc_span::Span;
use crate::base;

View File

@ -21,12 +21,12 @@ use rustc::dep_graph::WorkProduct;
use rustc::middle::cstore::{CrateSource, LibSource, NativeLibrary};
use rustc::middle::dependency_format::Dependencies;
use rustc::middle::lang_items::LangItem;
use rustc::session::config::{OutputFilenames, OutputType, RUST_CGU_EXT};
use rustc::ty::query::Providers;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::Lrc;
use rustc_hir::def_id::CrateNum;
use rustc_session::config::{OutputFilenames, OutputType, RUST_CGU_EXT};
use rustc_span::symbol::Symbol;
use std::path::{Path, PathBuf};

View File

@ -1,10 +1,10 @@
use crate::traits::*;
use rustc::mir;
use rustc::session::config::DebugInfo;
use rustc::ty;
use rustc::ty::layout::{LayoutOf, Size};
use rustc_hir::def_id::CrateNum;
use rustc_index::vec::IndexVec;
use rustc_session::config::DebugInfo;
use rustc_span::symbol::{kw, Symbol};
use rustc_span::{BytePos, Span};

View File

@ -3,12 +3,12 @@ use super::CodegenObject;
use crate::ModuleCodegen;
use rustc::middle::cstore::EncodedMetadata;
use rustc::session::{config, Session};
use rustc::ty::layout::{HasTyCtxt, LayoutOf, TyLayout};
use rustc::ty::Ty;
use rustc::ty::TyCtxt;
use rustc_ast::expand::allocator::AllocatorKind;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_session::{config, Session};
use rustc_span::symbol::Symbol;
use std::sync::Arc;

View File

@ -1,8 +1,8 @@
use super::BackendTypes;
use rustc::mir::mono::CodegenUnit;
use rustc::session::Session;
use rustc::ty::{self, Instance, Ty};
use rustc_data_structures::fx::FxHashMap;
use rustc_session::Session;
use std::cell::RefCell;
use std::sync::Arc;

View File

@ -21,3 +21,4 @@ rustc_hir = { path = "../librustc_hir" }
rustc_target = { path = "../librustc_target" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_metadata = { path = "../librustc_metadata" }
rustc_session = { path = "../librustc_session" }

View File

@ -10,11 +10,11 @@ use std::any::Any;
use rustc::dep_graph::DepGraph;
use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
use rustc::session::config::{OutputFilenames, PrintRequest};
use rustc::session::Session;
use rustc::ty::query::Providers;
use rustc::ty::TyCtxt;
use rustc::util::common::ErrorReported;
use rustc_session::config::{OutputFilenames, PrintRequest};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
pub use rustc_data_structures::sync::MetadataRef;

View File

@ -1,6 +1,6 @@
use rustc::session::config::{self, Input, OutputFilenames, OutputType};
use rustc::session::Session;
use rustc_ast::{ast, attr};
use rustc_session::config::{self, Input, OutputFilenames, OutputType};
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::Span;
use std::path::{Path, PathBuf};

View File

@ -89,12 +89,12 @@
use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc::mir::mono::{InstantiationMode, MonoItem};
use rustc::session::config::SymbolManglingVersion;
use rustc::ty::query::Providers;
use rustc::ty::subst::SubstsRef;
use rustc::ty::{self, Instance, TyCtxt};
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_hir::Node;
use rustc_session::config::SymbolManglingVersion;
use rustc_span::symbol::Symbol;

View File

@ -33,6 +33,7 @@ rustc_interface = { path = "../librustc_interface" }
rustc_serialize = { path = "../libserialize", package = "serialize" }
rustc_ast = { path = "../librustc_ast" }
rustc_span = { path = "../librustc_span" }
rustc_session = { path = "../librustc_session" }
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["consoleapi", "debugapi", "processenv"] }

View File

@ -18,12 +18,7 @@ extern crate lazy_static;
pub extern crate rustc_plugin_impl as plugin;
use rustc::lint::{Lint, LintId};
use rustc::middle::cstore::MetadataLoader;
use rustc::session::config::nightly_options;
use rustc::session::config::{ErrorOutputType, Input, OutputType, PrintRequest};
use rustc::session::{config, DiagnosticOutput, Session};
use rustc::session::{early_error, early_warn};
use rustc::ty::TyCtxt;
use rustc::util::common::ErrorReported;
use rustc_codegen_ssa::CodegenResults;
@ -43,6 +38,11 @@ use rustc_metadata::locator;
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
use rustc_serialize::json::{self, ToJson};
use rustc_session::config::nightly_options;
use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest};
use rustc_session::lint::{Lint, LintId};
use rustc_session::{config, DiagnosticOutput, Session};
use rustc_session::{early_error, early_warn};
use std::borrow::Cow;
use std::cmp::max;
@ -652,7 +652,7 @@ impl RustcDefaultCalls {
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
) -> Compilation {
use rustc::session::config::PrintRequest::*;
use rustc_session::config::PrintRequest::*;
// PrintRequest::NativeStaticLibs is special - printed during linking
// (empty iterator returns true)
if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {

View File

@ -1,8 +1,6 @@
//! The various pretty-printing routines.
use rustc::hir::map as hir_map;
use rustc::session::config::{Input, PpMode, PpSourceMode};
use rustc::session::Session;
use rustc::ty::{self, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc_ast::ast;
@ -11,6 +9,8 @@ use rustc_hir as hir;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_hir::print as pprust_hir;
use rustc_mir::util::{write_mir_graphviz, write_mir_pretty};
use rustc_session::config::{Input, PpMode, PpSourceMode};
use rustc_session::Session;
use rustc_span::FileName;
use std::cell::Cell;

View File

@ -1,10 +1,6 @@
This error occurs when the compiler was unable to infer the concrete type of a
variable. It can occur for several cases, the most common of which is a
mismatch in the expected type that the compiler inferred for a variable's
initializing expression, and the actual type explicitly assigned to the
variable.
Expected type did not match the received type.
For example:
Erroneous code example:
```compile_fail,E0308
let x: i32 = "I am not a number!";
@ -15,3 +11,9 @@ let x: i32 = "I am not a number!";
// |
// type `i32` assigned to variable `x`
```
This error occurs when the compiler was unable to infer the concrete type of a
variable. It can occur for several cases, the most common of which is a
mismatch in the expected type that the compiler inferred for a variable's
initializing expression, and the actual type explicitly assigned to the
variable.

View File

@ -5,7 +5,7 @@
//! There are various `Emitter` implementations that generate different output formats such as
//! JSON and human readable output.
//!
//! The output types are defined in `librustc::session::config::ErrorOutputType`.
//! The output types are defined in `rustc_session::config::ErrorOutputType`.
use Destination::*;

View File

@ -1,4 +1,5 @@
use crate::expand::{self, AstFragment, Invocation};
use crate::module::DirectoryOwnership;
use rustc_ast::ast::{self, Attribute, Name, NodeId, PatKind};
use rustc_ast::mut_visit::{self, MutVisitor};
@ -10,7 +11,7 @@ use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{self, Lrc};
use rustc_errors::{DiagnosticBuilder, DiagnosticId};
use rustc_parse::{self, parser, DirectoryOwnership, MACRO_ARGUMENTS};
use rustc_parse::{self, parser, MACRO_ARGUMENTS};
use rustc_session::parse::ParseSess;
use rustc_span::edition::Edition;
use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
@ -925,6 +926,8 @@ pub struct ExtCtxt<'a> {
pub resolver: &'a mut dyn Resolver,
pub current_expansion: ExpansionData,
pub expansions: FxHashMap<Span, Vec<String>>,
/// Called directly after having parsed an external `mod foo;` in expansion.
pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
}
impl<'a> ExtCtxt<'a> {
@ -932,12 +935,14 @@ impl<'a> ExtCtxt<'a> {
parse_sess: &'a ParseSess,
ecfg: expand::ExpansionConfig<'a>,
resolver: &'a mut dyn Resolver,
extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
) -> ExtCtxt<'a> {
ExtCtxt {
parse_sess,
ecfg,
root_path: PathBuf::new(),
resolver,
extern_mod_loaded,
root_path: PathBuf::new(),
current_expansion: ExpansionData {
id: ExpnId::root(),
depth: 0,

View File

@ -1,14 +1,5 @@
//! Process the potential `cfg` attributes on a module.
//! Also determine if the module should be included in this configuration.
//!
//! This module properly belongs in rustc_expand, but for now it's tied into
//! parsing, so we leave it here to avoid complicated out-of-line dependencies.
//!
//! A principled solution to this wrong location would be to implement [#64197].
//!
//! [#64197]: https://github.com/rust-lang/rust/issues/64197
//! Conditional compilation stripping.
use crate::{parse_in, validate_attr};
use rustc_ast::ast::{self, AttrItem, Attribute, MetaItem};
use rustc_ast::attr::HasAttrs;
use rustc_ast::mut_visit::*;
@ -21,6 +12,7 @@ use rustc_feature::{Feature, Features, State as FeatureState};
use rustc_feature::{
ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
};
use rustc_parse::{parse_in, validate_attr};
use rustc_session::parse::{feature_err, ParseSess};
use rustc_span::edition::{Edition, ALL_EDITIONS};
use rustc_span::symbol::{sym, Symbol};
@ -538,12 +530,3 @@ impl<'a> MutVisitor for StripUnconfigured<'a> {
fn is_cfg(attr: &Attribute) -> bool {
attr.check_name(sym::cfg)
}
/// Process the potential `cfg` attributes on a module.
/// Also determine if the module should be included in this configuration.
pub fn process_configure_mod(sess: &ParseSess, cfg_mods: bool, attrs: &mut Vec<Attribute>) -> bool {
// Don't perform gated feature checking.
let mut strip_unconfigured = StripUnconfigured { sess, features: None };
strip_unconfigured.process_cfg_attrs(attrs);
!cfg_mods || strip_unconfigured.in_cfg(&attrs)
}

View File

@ -1,7 +1,9 @@
use crate::base::*;
use crate::config::StripUnconfigured;
use crate::configure;
use crate::hygiene::{ExpnData, ExpnId, ExpnKind, SyntaxContext};
use crate::mbe::macro_rules::annotate_err_with_kind;
use crate::module::{parse_external_mod, push_directory, Directory, DirectoryOwnership};
use crate::placeholders::{placeholder, PlaceholderExpander};
use crate::proc_macro::collect_derives;
@ -17,10 +19,8 @@ use rustc_ast_pretty::pprust;
use rustc_attr::{self as attr, is_builtin_attr, HasAttrs};
use rustc_errors::{Applicability, FatalError, PResult};
use rustc_feature::Features;
use rustc_parse::configure;
use rustc_parse::parser::Parser;
use rustc_parse::validate_attr;
use rustc_parse::DirectoryOwnership;
use rustc_session::lint::builtin::UNUSED_DOC_COMMENTS;
use rustc_session::lint::BuiltinLintDiagnostics;
use rustc_session::parse::{feature_err, ParseSess};
@ -1427,59 +1427,83 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
.make_items();
}
let mut attrs = mem::take(&mut item.attrs); // We do this to please borrowck.
let ident = item.ident;
let span = item.span;
match item.kind {
ast::ItemKind::MacCall(..) => {
item.attrs = attrs;
self.check_attributes(&item.attrs);
item.and_then(|item| match item.kind {
ItemKind::MacCall(mac) => self
.collect(
AstFragmentKind::Items,
InvocationKind::Bang { mac, span: item.span },
)
.collect(AstFragmentKind::Items, InvocationKind::Bang { mac, span })
.make_items(),
_ => unreachable!(),
})
}
ast::ItemKind::Mod(ast::Mod { inner, inline, .. })
if item.ident != Ident::invalid() =>
{
let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
ast::ItemKind::Mod(ref mut old_mod @ ast::Mod { .. }) if ident != Ident::invalid() => {
let sess = self.cx.parse_sess;
let orig_ownership = self.cx.current_expansion.directory_ownership;
let mut module = (*self.cx.current_expansion.module).clone();
module.mod_path.push(item.ident);
if inline {
if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
self.cx.current_expansion.directory_ownership =
DirectoryOwnership::Owned { relative: None };
module.directory.push(&*path.as_str());
} else {
module.directory.push(&*item.ident.as_str());
}
let pushed = &mut false; // Record `parse_external_mod` pushing so we can pop.
let dir = Directory { ownership: orig_ownership, path: module.directory };
let Directory { ownership, path } = if old_mod.inline {
// Inline `mod foo { ... }`, but we still need to push directories.
item.attrs = attrs;
push_directory(ident, &item.attrs, dir)
} else {
let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
let mut path = match path {
FileName::Real(path) => path,
other => PathBuf::from(other.to_string()),
};
let directory_ownership = match path.file_name().unwrap().to_str() {
Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
Some(_) => DirectoryOwnership::Owned { relative: Some(item.ident) },
None => DirectoryOwnership::UnownedViaMod,
};
path.pop();
module.directory = path;
self.cx.current_expansion.directory_ownership = directory_ownership;
}
// We have an outline `mod foo;` so we need to parse the file.
let (new_mod, dir) =
parse_external_mod(sess, ident, span, dir, &mut attrs, pushed);
let krate = ast::Crate {
span: new_mod.inner,
module: new_mod,
attrs,
proc_macros: vec![],
};
if let Some(extern_mod_loaded) = self.cx.extern_mod_loaded {
extern_mod_loaded(&krate);
}
*old_mod = krate.module;
item.attrs = krate.attrs;
// File can have inline attributes, e.g., `#![cfg(...)]` & co. => Reconfigure.
item = match self.configure(item) {
Some(node) => node,
None => {
if *pushed {
sess.included_mod_stack.borrow_mut().pop();
}
return Default::default();
}
};
dir
};
// Set the module info before we flat map.
self.cx.current_expansion.directory_ownership = ownership;
module.directory = path;
module.mod_path.push(ident);
let orig_module =
mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
let result = noop_flat_map_item(item, self);
// Restore the module info.
self.cx.current_expansion.module = orig_module;
self.cx.current_expansion.directory_ownership = orig_directory_ownership;
self.cx.current_expansion.directory_ownership = orig_ownership;
if *pushed {
sess.included_mod_stack.borrow_mut().pop();
}
result
}
_ => noop_flat_map_item(item, self),
_ => {
item.attrs = attrs;
noop_flat_map_item(item, self)
}
}
}

View File

@ -1,9 +1,11 @@
#![feature(bool_to_option)]
#![feature(cow_is_borrowed)]
#![feature(crate_visibility_modifier)]
#![feature(decl_macro)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_span)]
#![feature(try_blocks)]
extern crate proc_macro as pm;
@ -33,8 +35,10 @@ pub use mbe::macro_rules::compile_declarative_macro;
crate use rustc_span::hygiene;
pub mod base;
pub mod build;
#[macro_use]
pub mod config;
pub mod expand;
pub use rustc_parse::config;
pub mod module;
pub mod proc_macro;
crate mod mbe;

View File

@ -1,4 +1,4 @@
use crate::base::{DummyResult, ExpansionData, ExtCtxt, MacResult, TTMacroExpander};
use crate::base::{DummyResult, ExtCtxt, MacResult, TTMacroExpander};
use crate::base::{SyntaxExtension, SyntaxExtensionKind};
use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind};
use crate::mbe;
@ -18,7 +18,6 @@ use rustc_data_structures::sync::Lrc;
use rustc_errors::{Applicability, DiagnosticBuilder, FatalError};
use rustc_feature::Features;
use rustc_parse::parser::Parser;
use rustc_parse::Directory;
use rustc_session::parse::ParseSess;
use rustc_span::edition::Edition;
use rustc_span::hygiene::Transparency;
@ -182,6 +181,8 @@ fn generic_extension<'cx>(
lhses: &[mbe::TokenTree],
rhses: &[mbe::TokenTree],
) -> Box<dyn MacResult + 'cx> {
let sess = cx.parse_sess;
if cx.trace_macros() {
let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(arg.clone()));
trace_macros_note(&mut cx.expansions, sp, msg);
@ -209,7 +210,7 @@ fn generic_extension<'cx>(
// hacky, but speeds up the `html5ever` benchmark significantly. (Issue
// 68836 suggests a more comprehensive but more complex change to deal with
// this situation.)
let parser = parser_from_cx(&cx.current_expansion, &cx.parse_sess, arg.clone());
let parser = parser_from_cx(sess, arg.clone());
for (i, lhs) in lhses.iter().enumerate() {
// try each arm's matchers
@ -222,14 +223,13 @@ fn generic_extension<'cx>(
// This is used so that if a matcher is not `Success(..)`ful,
// then the spans which became gated when parsing the unsuccessful matcher
// are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
let mut gated_spans_snapshot =
mem::take(&mut *cx.parse_sess.gated_spans.spans.borrow_mut());
let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut());
match parse_tt(&mut Cow::Borrowed(&parser), lhs_tt) {
Success(named_matches) => {
// The matcher was `Success(..)`ful.
// Merge the gated spans from parsing the matcher with the pre-existing ones.
cx.parse_sess.gated_spans.merge(gated_spans_snapshot);
sess.gated_spans.merge(gated_spans_snapshot);
let rhs = match rhses[i] {
// ignore delimiters
@ -258,11 +258,7 @@ fn generic_extension<'cx>(
trace_macros_note(&mut cx.expansions, sp, msg);
}
let directory = Directory {
path: cx.current_expansion.module.directory.clone(),
ownership: cx.current_expansion.directory_ownership,
};
let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false, None);
let mut p = Parser::new(sess, tts, false, None);
p.root_module_name =
cx.current_expansion.module.mod_path.last().map(|id| id.to_string());
p.last_type_ascription = cx.current_expansion.prior_type_ascription;
@ -289,7 +285,7 @@ fn generic_extension<'cx>(
// The matcher was not `Success(..)`ful.
// Restore to the state before snapshotting and maybe try again.
mem::swap(&mut gated_spans_snapshot, &mut cx.parse_sess.gated_spans.spans.borrow_mut());
mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut());
}
drop(parser);
@ -309,8 +305,7 @@ fn generic_extension<'cx>(
mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
_ => continue,
};
let parser = parser_from_cx(&cx.current_expansion, &cx.parse_sess, arg.clone());
match parse_tt(&mut Cow::Borrowed(&parser), lhs_tt) {
match parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt) {
Success(_) => {
if comma_span.is_dummy() {
err.note("you might be missing a comma");
@ -392,7 +387,7 @@ pub fn compile_declarative_macro(
),
];
let parser = Parser::new(sess, body, None, true, true, rustc_parse::MACRO_ARGUMENTS);
let parser = Parser::new(sess, body, true, rustc_parse::MACRO_ARGUMENTS);
let argument_map = match parse_tt(&mut Cow::Borrowed(&parser), &argument_gram) {
Success(m) => m,
Failure(token, msg) => {
@ -1209,16 +1204,8 @@ fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
}
}
fn parser_from_cx<'cx>(
current_expansion: &'cx ExpansionData,
sess: &'cx ParseSess,
tts: TokenStream,
) -> Parser<'cx> {
let directory = Directory {
path: current_expansion.module.directory.clone(),
ownership: current_expansion.directory_ownership,
};
Parser::new(sess, tts, Some(directory), true, true, rustc_parse::MACRO_ARGUMENTS)
fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> {
Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS)
}
/// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For

View File

@ -0,0 +1,306 @@
use rustc_ast::ast::{self, Attribute, Ident, Mod};
use rustc_ast::{attr, token};
use rustc_errors::{struct_span_err, PResult};
use rustc_parse::new_sub_parser_from_file;
use rustc_session::parse::ParseSess;
use rustc_span::source_map::{FileName, Span};
use rustc_span::symbol::sym;
use std::path::{self, Path, PathBuf};
#[derive(Clone)]
pub struct Directory {
pub path: PathBuf,
pub ownership: DirectoryOwnership,
}
#[derive(Copy, Clone)]
pub enum DirectoryOwnership {
Owned {
// None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
relative: Option<ast::Ident>,
},
UnownedViaBlock,
UnownedViaMod,
}
/// Information about the path to a module.
// Public for rustfmt usage.
pub struct ModulePath<'a> {
name: String,
path_exists: bool,
pub result: PResult<'a, ModulePathSuccess>,
}
// Public for rustfmt usage.
pub struct ModulePathSuccess {
pub path: PathBuf,
pub ownership: DirectoryOwnership,
}
crate fn parse_external_mod(
sess: &ParseSess,
id: ast::Ident,
span: Span, // The span to blame on errors.
Directory { mut ownership, path }: Directory,
attrs: &mut Vec<Attribute>,
pop_mod_stack: &mut bool,
) -> (Mod, Directory) {
// We bail on the first error, but that error does not cause a fatal error... (1)
let result: PResult<'_, _> = try {
// Extract the file path and the new ownership.
let mp = submod_path(sess, id, span, &attrs, ownership, &path)?;
ownership = mp.ownership;
// Ensure file paths are acyclic.
let mut included_mod_stack = sess.included_mod_stack.borrow_mut();
error_on_circular_module(sess, span, &mp.path, &included_mod_stack)?;
included_mod_stack.push(mp.path.clone());
*pop_mod_stack = true; // We have pushed, so notify caller.
drop(included_mod_stack);
// Actually parse the external file as amodule.
let mut p0 = new_sub_parser_from_file(sess, &mp.path, Some(id.to_string()), span);
let mut module = p0.parse_mod(&token::Eof)?;
module.0.inline = false;
module
};
// (1) ...instead, we return a dummy module.
let (module, mut new_attrs) = result.map_err(|mut err| err.emit()).unwrap_or_default();
attrs.append(&mut new_attrs);
// Extract the directory path for submodules of `module`.
let path = sess.source_map().span_to_unmapped_path(module.inner);
let mut path = match path {
FileName::Real(path) => path,
other => PathBuf::from(other.to_string()),
};
path.pop();
(module, Directory { ownership, path })
}
fn error_on_circular_module<'a>(
sess: &'a ParseSess,
span: Span,
path: &Path,
included_mod_stack: &[PathBuf],
) -> PResult<'a, ()> {
if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
let mut err = String::from("circular modules: ");
for p in &included_mod_stack[i..] {
err.push_str(&p.to_string_lossy());
err.push_str(" -> ");
}
err.push_str(&path.to_string_lossy());
return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
}
Ok(())
}
crate fn push_directory(
id: Ident,
attrs: &[Attribute],
Directory { mut ownership, mut path }: Directory,
) -> Directory {
if let Some(filename) = attr::first_attr_value_str_by_name(attrs, sym::path) {
path.push(&*filename.as_str());
ownership = DirectoryOwnership::Owned { relative: None };
} else {
// We have to push on the current module name in the case of relative
// paths in order to ensure that any additional module paths from inline
// `mod x { ... }` come after the relative extension.
//
// For example, a `mod z { ... }` inside `x/y.rs` should set the current
// directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
if let DirectoryOwnership::Owned { relative } = &mut ownership {
if let Some(ident) = relative.take() {
// Remove the relative offset.
path.push(&*ident.as_str());
}
}
path.push(&*id.as_str());
}
Directory { ownership, path }
}
fn submod_path<'a>(
sess: &'a ParseSess,
id: ast::Ident,
span: Span,
attrs: &[Attribute],
ownership: DirectoryOwnership,
dir_path: &Path,
) -> PResult<'a, ModulePathSuccess> {
if let Some(path) = submod_path_from_attr(attrs, dir_path) {
let ownership = match path.file_name().and_then(|s| s.to_str()) {
// All `#[path]` files are treated as though they are a `mod.rs` file.
// This means that `mod foo;` declarations inside `#[path]`-included
// files are siblings,
//
// Note that this will produce weirdness when a file named `foo.rs` is
// `#[path]` included and contains a `mod foo;` declaration.
// If you encounter this, it's your own darn fault :P
Some(_) => DirectoryOwnership::Owned { relative: None },
_ => DirectoryOwnership::UnownedViaMod,
};
return Ok(ModulePathSuccess { ownership, path });
}
let relative = match ownership {
DirectoryOwnership::Owned { relative } => relative,
DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
};
let ModulePath { path_exists, name, result } =
default_submod_path(sess, id, span, relative, dir_path);
match ownership {
DirectoryOwnership::Owned { .. } => Ok(result?),
DirectoryOwnership::UnownedViaBlock => {
let _ = result.map_err(|mut err| err.cancel());
error_decl_mod_in_block(sess, span, path_exists, &name)
}
DirectoryOwnership::UnownedViaMod => {
let _ = result.map_err(|mut err| err.cancel());
error_cannot_declare_mod_here(sess, span, path_exists, &name)
}
}
}
fn error_decl_mod_in_block<'a, T>(
sess: &'a ParseSess,
span: Span,
path_exists: bool,
name: &str,
) -> PResult<'a, T> {
let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
let mut err = sess.span_diagnostic.struct_span_err(span, msg);
if path_exists {
let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
err.span_note(span, &msg);
}
Err(err)
}
fn error_cannot_declare_mod_here<'a, T>(
sess: &'a ParseSess,
span: Span,
path_exists: bool,
name: &str,
) -> PResult<'a, T> {
let mut err =
sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
if !span.is_dummy() {
if let FileName::Real(src_path) = sess.source_map().span_to_filename(span) {
if let Some(stem) = src_path.file_stem() {
let mut dest_path = src_path.clone();
dest_path.set_file_name(stem);
dest_path.push("mod.rs");
err.span_note(
span,
&format!(
"maybe move this module `{}` to its own directory via `{}`",
src_path.display(),
dest_path.display()
),
);
}
}
}
if path_exists {
err.span_note(
span,
&format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
);
}
Err(err)
}
/// Derive a submodule path from the first found `#[path = "path_string"]`.
/// The provided `dir_path` is joined with the `path_string`.
// Public for rustfmt usage.
pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
// Extract path string from first `#[path = "path_string"]` attribute.
let path_string = attr::first_attr_value_str_by_name(attrs, sym::path)?;
let path_string = path_string.as_str();
// On windows, the base path might have the form
// `\\?\foo\bar` in which case it does not tolerate
// mixed `/` and `\` separators, so canonicalize
// `/` to `\`.
#[cfg(windows)]
let path_string = path_string.replace("/", "\\");
Some(dir_path.join(&*path_string))
}
/// Returns a path to a module.
// Public for rustfmt usage.
pub fn default_submod_path<'a>(
sess: &'a ParseSess,
id: ast::Ident,
span: Span,
relative: Option<ast::Ident>,
dir_path: &Path,
) -> ModulePath<'a> {
// If we're in a foo.rs file instead of a mod.rs file,
// we need to look for submodules in
// `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
// `./<id>.rs` and `./<id>/mod.rs`.
let relative_prefix_string;
let relative_prefix = if let Some(ident) = relative {
relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
&relative_prefix_string
} else {
""
};
let mod_name = id.name.to_string();
let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
let secondary_path_str =
format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
let default_path = dir_path.join(&default_path_str);
let secondary_path = dir_path.join(&secondary_path_str);
let default_exists = sess.source_map().file_exists(&default_path);
let secondary_exists = sess.source_map().file_exists(&secondary_path);
let result = match (default_exists, secondary_exists) {
(true, false) => Ok(ModulePathSuccess {
path: default_path,
ownership: DirectoryOwnership::Owned { relative: Some(id) },
}),
(false, true) => Ok(ModulePathSuccess {
path: secondary_path,
ownership: DirectoryOwnership::Owned { relative: None },
}),
(false, false) => {
let mut err = struct_span_err!(
sess.span_diagnostic,
span,
E0583,
"file not found for module `{}`",
mod_name,
);
err.help(&format!(
"to create the module `{}`, create file \"{}\"",
mod_name,
default_path.display(),
));
Err(err)
}
(true, true) => {
let mut err = struct_span_err!(
sess.span_diagnostic,
span,
E0584,
"file for module `{}` found at both {} and {}",
mod_name,
default_path_str,
secondary_path_str,
);
err.help("delete or rename one of them to remove the ambiguity");
Err(err)
}
};
ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
}

View File

@ -71,7 +71,7 @@ rustc_data_structures::impl_stable_hash_via_hash!(ItemLocalId);
/// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
pub const CRATE_HIR_ID: HirId =
HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32_const(0) };
HirId { owner: CRATE_DEF_INDEX, local_id: ItemLocalId::from_u32(0) };
pub const DUMMY_HIR_ID: HirId = HirId { owner: CRATE_DEF_INDEX, local_id: DUMMY_ITEM_LOCAL_ID };

View File

@ -127,6 +127,25 @@ pub trait Map<'hir> {
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
}
/// An erased version of `Map<'hir>`, using dynamic dispatch.
/// NOTE: This type is effectively only usable with `NestedVisitorMap::None`.
pub struct ErasedMap<'hir>(&'hir dyn Map<'hir>);
impl<'hir> Map<'hir> for ErasedMap<'hir> {
fn body(&self, id: BodyId) -> &'hir Body<'hir> {
self.0.body(id)
}
fn item(&self, id: HirId) -> &'hir Item<'hir> {
self.0.item(id)
}
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
self.0.trait_item(id)
}
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
self.0.impl_item(id)
}
}
/// Specifies what nested things a visitor wants to visit. The most
/// common choice is `OnlyBodies`, which will cause the visitor to
/// visit fn bodies for fns that it encounters, but skip over nested

View File

@ -3,7 +3,9 @@
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
#![feature(crate_visibility_modifier)]
#![feature(const_if_match)]
#![feature(const_fn)] // For the unsizing cast on `&[]`
#![feature(const_panic)]
#![feature(in_band_lifetimes)]
#![feature(specialization)]
#![recursion_limit = "256"]

View File

@ -14,8 +14,8 @@ use std::fs;
use std::io::{self, Read};
use std::path::Path;
use rustc::session::config::nightly_options;
use rustc_serialize::opaque::Encoder;
use rustc_session::config::nightly_options;
/// The first few bytes of files generated by incremental compilation.
const FILE_MAGIC: &[u8] = b"RSIC";

View File

@ -103,11 +103,11 @@
//! unsupported file system and emit a warning in that case. This is not yet
//! implemented.
use rustc::session::{CrateDisambiguator, Session};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::svh::Svh;
use rustc_data_structures::{base_n, flock};
use rustc_fs_util::{link_or_copy, LinkOrCopy};
use rustc_session::{CrateDisambiguator, Session};
use std::fs as std_fs;
use std::io;

View File

@ -1,12 +1,12 @@
//! Code to save/load the dep-graph from files.
use rustc::dep_graph::{PreviousDepGraph, SerializedDepGraph, WorkProduct, WorkProductId};
use rustc::session::Session;
use rustc::ty::query::OnDiskCache;
use rustc::ty::TyCtxt;
use rustc_data_structures::fx::FxHashMap;
use rustc_serialize::opaque::Decoder;
use rustc_serialize::Decodable as RustcDecodable;
use rustc_session::Session;
use std::path::Path;
use super::data::*;

View File

@ -1,10 +1,10 @@
use rustc::dep_graph::{DepGraph, DepKind, WorkProduct, WorkProductId};
use rustc::session::Session;
use rustc::ty::TyCtxt;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::join;
use rustc_serialize::opaque::Encoder;
use rustc_serialize::Encodable as RustcEncodable;
use rustc_session::Session;
use std::fs;
use std::path::PathBuf;

View File

@ -2,8 +2,8 @@
use crate::persist::fs::*;
use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
use rustc::session::Session;
use rustc_fs_util::link_or_copy;
use rustc_session::Session;
use std::fs as std_fs;
use std::path::PathBuf;

View File

@ -1,4 +1,7 @@
#![feature(allow_internal_unstable)]
#![feature(const_if_match)]
#![feature(const_fn)]
#![feature(const_panic)]
#![feature(unboxed_closures)]
#![feature(test)]
#![feature(fn_traits)]

View File

@ -120,10 +120,10 @@ macro_rules! newtype_index {
impl $type {
$v const MAX_AS_U32: u32 = $max;
$v const MAX: Self = Self::from_u32_const($max);
$v const MAX: Self = Self::from_u32($max);
#[inline]
$v fn from_usize(value: usize) -> Self {
$v const fn from_usize(value: usize) -> Self {
assert!(value <= ($max as usize));
unsafe {
Self::from_u32_unchecked(value as u32)
@ -131,31 +131,13 @@ macro_rules! newtype_index {
}
#[inline]
$v fn from_u32(value: u32) -> Self {
$v const fn from_u32(value: u32) -> Self {
assert!(value <= $max);
unsafe {
Self::from_u32_unchecked(value)
}
}
/// Hacky variant of `from_u32` for use in constants.
/// This version checks the "max" constraint by using an
/// invalid array dereference.
#[inline]
$v const fn from_u32_const(value: u32) -> Self {
// This will fail at const eval time unless `value <=
// max` is true (in which case we get the index 0).
// It will also fail at runtime, of course, but in a
// kind of wacky way.
let _ = ["out of range value used"][
!(value <= $max) as usize
];
unsafe {
Self { private: value }
}
}
#[inline]
$v const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self { private: value }
@ -163,19 +145,19 @@ macro_rules! newtype_index {
/// Extracts the value of this index as an integer.
#[inline]
$v fn index(self) -> usize {
$v const fn index(self) -> usize {
self.as_usize()
}
/// Extracts the value of this index as a `u32`.
#[inline]
$v fn as_u32(self) -> u32 {
$v const fn as_u32(self) -> u32 {
self.private
}
/// Extracts the value of this index as a `usize`.
#[inline]
$v fn as_usize(self) -> usize {
$v const fn as_usize(self) -> usize {
self.as_u32() as usize
}
}
@ -500,7 +482,7 @@ macro_rules! newtype_index {
const $name:ident = $constant:expr,
$($tokens:tt)*) => (
$(#[doc = $doc])*
$v const $name: $type = $type::from_u32_const($constant);
$v const $name: $type = $type::from_u32($constant);
$crate::newtype_index!(
@derives [$($derives,)*]
@attrs [$(#[$attrs])*]

View File

@ -18,6 +18,7 @@ rustc_errors = { path = "../librustc_errors" }
rustc_hir = { path = "../librustc_hir" }
rustc_index = { path = "../librustc_index" }
rustc_macros = { path = "../librustc_macros" }
rustc_session = { path = "../librustc_session" }
rustc_span = { path = "../librustc_span" }
rustc_target = { path = "../librustc_target" }
smallvec = { version = "1.0", features = ["union", "may_dangle"] }

View File

@ -49,7 +49,7 @@ use super::lexical_region_resolve::RegionResolutionError;
use super::region_constraints::GenericKind;
use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
use crate::infer::{self, SuppressRegionErrors};
use crate::infer;
use crate::traits::error_reporting::report_object_safety_error;
use crate::traits::{
IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
@ -372,17 +372,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
&self,
region_scope_tree: &region::ScopeTree,
errors: &Vec<RegionResolutionError<'tcx>>,
suppress: SuppressRegionErrors,
) {
debug!(
"report_region_errors(): {} errors to start, suppress = {:?}",
errors.len(),
suppress
);
if suppress.suppressed() {
return;
}
debug!("report_region_errors(): {} errors to start", errors.len());
// try to pre-process the errors, which will group some of them
// together into a `ProcessedErrors` group:

View File

@ -3,6 +3,8 @@
use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo;
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::SubregionOrigin;
use rustc::util::common::ErrorReported;
use rustc_errors::struct_span_err;
@ -47,6 +49,15 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
pub(super) fn try_report_anon_anon_conflict(&self) -> Option<ErrorReported> {
let (span, sub, sup) = self.regions()?;
if let Some(RegionResolutionError::ConcreteFailure(
SubregionOrigin::ReferenceOutlivesReferent(..),
..,
)) = self.error
{
// This error doesn't make much sense in this case.
return None;
}
// Determine whether the sub and sup consist of both anonymous (elided) regions.
let anon_reg_sup = self.tcx().is_suitable_region(sup)?;

View File

@ -17,12 +17,7 @@ mod util;
impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
pub fn try_report_nice_region_error(&self, error: &RegionResolutionError<'tcx>) -> bool {
if let Some(tables) = self.in_progress_tables {
let tables = tables.borrow();
NiceRegionError::new(self, error.clone(), Some(&tables)).try_report().is_some()
} else {
NiceRegionError::new(self, error.clone(), None).try_report().is_some()
}
NiceRegionError::new(self, error.clone()).try_report().is_some()
}
}
@ -30,16 +25,11 @@ pub struct NiceRegionError<'cx, 'tcx> {
infcx: &'cx InferCtxt<'cx, 'tcx>,
error: Option<RegionResolutionError<'tcx>>,
regions: Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
}
impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> {
pub fn new(
infcx: &'cx InferCtxt<'cx, 'tcx>,
error: RegionResolutionError<'tcx>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
) -> Self {
Self { infcx, error: Some(error), regions: None, tables }
pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>, error: RegionResolutionError<'tcx>) -> Self {
Self { infcx, error: Some(error), regions: None }
}
pub fn new_from_span(
@ -47,9 +37,8 @@ impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> {
span: Span,
sub: ty::Region<'tcx>,
sup: ty::Region<'tcx>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
) -> Self {
Self { infcx, error: None, regions: Some((span, sub, sup)), tables }
Self { infcx, error: None, regions: Some((span, sub, sup)) }
}
fn tcx(&self) -> TyCtxt<'tcx> {

View File

@ -51,52 +51,44 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
};
let hir = &self.tcx().hir();
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_by_hir_id(owner_id).unwrap();
if let Some(tables) = self.tables {
body.params
.iter()
.enumerate()
.filter_map(|(index, param)| {
// May return None; sometimes the tables are not yet populated.
let ty_hir_id = fn_decl.inputs[index].hir_id;
let param_ty_span = hir.span(ty_hir_id);
let ty = tables.node_type_opt(param.hir_id)?;
let mut found_anon_region = false;
let new_param_ty = self.tcx().fold_regions(&ty, &mut false, |r, _| {
if *r == *anon_region {
found_anon_region = true;
replace_region
} else {
r
}
});
if found_anon_region {
let is_first = index == 0;
Some(AnonymousParamInfo {
param,
param_ty: new_param_ty,
param_ty_span,
bound_region,
is_first,
})
} else {
None
}
})
.next()
let hir_id = hir.as_local_hir_id(id)?;
let 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_by_hir_id(owner_id).unwrap();
let poly_fn_sig = self.tcx().fn_sig(id);
let fn_sig = self.tcx().liberate_late_bound_regions(id, &poly_fn_sig);
body.params
.iter()
.enumerate()
.filter_map(|(index, param)| {
// May return None; sometimes the tables are not yet populated.
let ty = fn_sig.inputs()[index];
let mut found_anon_region = false;
let new_param_ty = self.tcx().fold_regions(&ty, &mut false, |r, _| {
if *r == *anon_region {
found_anon_region = true;
replace_region
} else {
r
}
});
if found_anon_region {
let ty_hir_id = fn_decl.inputs[index].hir_id;
let param_ty_span = hir.span(ty_hir_id);
let is_first = index == 0;
Some(AnonymousParamInfo {
param,
param_ty: new_param_ty,
param_ty_span,
bound_region,
is_first,
})
} else {
None
}
} else {
None
}
} else {
None
}
})
.next()
}
// Here, we check for the case where the anonymous region

View File

@ -7,6 +7,7 @@ use crate::infer::region_constraints::RegionConstraintData;
use crate::infer::region_constraints::VarInfos;
use crate::infer::region_constraints::VerifyBound;
use crate::infer::RegionVariableOrigin;
use crate::infer::RegionckMode;
use crate::infer::SubregionOrigin;
use rustc::middle::free_region::RegionRelations;
use rustc::ty::fold::TypeFoldable;
@ -33,12 +34,29 @@ pub fn resolve<'tcx>(
region_rels: &RegionRelations<'_, 'tcx>,
var_infos: VarInfos,
data: RegionConstraintData<'tcx>,
mode: RegionckMode,
) -> (LexicalRegionResolutions<'tcx>, Vec<RegionResolutionError<'tcx>>) {
debug!("RegionConstraintData: resolve_regions()");
let mut errors = vec![];
let mut resolver = LexicalResolver { region_rels, var_infos, data };
let values = resolver.infer_variable_values(&mut errors);
(values, errors)
match mode {
RegionckMode::Solve => {
let values = resolver.infer_variable_values(&mut errors);
(values, errors)
}
RegionckMode::Erase { suppress_errors: false } => {
// Do real inference to get errors, then erase the results.
let mut values = resolver.infer_variable_values(&mut errors);
let re_erased = region_rels.tcx.lifetimes.re_erased;
values.values.iter_mut().for_each(|v| *v = VarValue::Value(re_erased));
(values, errors)
}
RegionckMode::Erase { suppress_errors: true } => {
// Skip region inference entirely.
(resolver.erased_data(region_rels.tcx), Vec::new())
}
}
}
/// Contains the result of lexical region resolution. Offers methods
@ -163,6 +181,19 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
}
}
/// An erased version of the lexical region resolutions. Used when we're
/// erasing regions and suppressing errors: in item bodies with
/// `-Zborrowck=mir`.
fn erased_data(&self, tcx: TyCtxt<'tcx>) -> LexicalRegionResolutions<'tcx> {
LexicalRegionResolutions {
error_region: tcx.lifetimes.re_static,
values: IndexVec::from_elem_n(
VarValue::Value(tcx.lifetimes.re_erased),
self.num_vars(),
),
}
}
fn dump_constraints(&self, free_regions: &RegionRelations<'_, 'tcx>) {
debug!("----() Start constraint listing (context={:?}) ()----", free_regions.context);
for (idx, (constraint, _)) in self.data.constraints.iter().enumerate() {

View File

@ -5,7 +5,6 @@ pub use self::LateBoundRegionConversionTime::*;
pub use self::RegionVariableOrigin::*;
pub use self::SubregionOrigin::*;
pub use self::ValuePairs::*;
pub use rustc::ty::IntVarValue;
use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
@ -16,15 +15,14 @@ use rustc::middle::free_region::RegionRelations;
use rustc::middle::region;
use rustc::mir;
use rustc::mir::interpret::ConstEvalResult;
use rustc::session::config::BorrowckMode;
use rustc::traits::select;
use rustc::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
use rustc::ty::fold::{TypeFoldable, TypeFolder};
use rustc::ty::relate::RelateResult;
use rustc::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
pub use rustc::ty::IntVarValue;
use rustc::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
use rustc::ty::{ConstVid, FloatVid, IntVid, TyVid};
use rustc_ast::ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
@ -32,8 +30,10 @@ use rustc_data_structures::unify as ut;
use rustc_errors::DiagnosticBuilder;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_session::config::BorrowckMode;
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use std::cell::{Cell, Ref, RefCell};
use std::collections::BTreeMap;
use std::fmt;
@ -79,31 +79,50 @@ pub type Bound<T> = Option<T>;
pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
/// A flag that is used to suppress region errors. This is normally
/// false, but sometimes -- when we are doing region checks that the
/// NLL borrow checker will also do -- it might be set to true.
#[derive(Copy, Clone, Default, Debug)]
pub struct SuppressRegionErrors {
suppressed: bool,
/// How we should handle region solving.
///
/// This is used so that the region values inferred by HIR region solving are
/// not exposed, and so that we can avoid doing work in HIR typeck that MIR
/// typeck will also do.
#[derive(Copy, Clone, Debug)]
pub enum RegionckMode {
/// The default mode: report region errors, don't erase regions.
Solve,
/// Erase the results of region after solving.
Erase {
/// A flag that is used to suppress region errors, when we are doing
/// region checks that the NLL borrow checker will also do -- it might
/// be set to true.
suppress_errors: bool,
},
}
impl SuppressRegionErrors {
impl Default for RegionckMode {
fn default() -> Self {
RegionckMode::Solve
}
}
impl RegionckMode {
pub fn suppressed(self) -> bool {
self.suppressed
match self {
Self::Solve => false,
Self::Erase { suppress_errors } => suppress_errors,
}
}
/// Indicates that the MIR borrowck will repeat these region
/// checks, so we should ignore errors if NLL is (unconditionally)
/// enabled.
pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
// FIXME(Centril): Once we actually remove `::Migrate` also make
// this always `true` and then proceed to eliminate the dead code.
match tcx.borrowck_mode() {
// If we're on Migrate mode, report AST region errors
BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
// If we're on MIR, don't report AST region errors as they should be reported by NLL
BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
}
}
}
@ -1207,20 +1226,13 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
region_context: DefId,
region_map: &region::ScopeTree,
outlives_env: &OutlivesEnvironment<'tcx>,
suppress: SuppressRegionErrors,
mode: RegionckMode,
) {
assert!(
self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
"region_obligations not empty: {:#?}",
self.inner.borrow().region_obligations
);
let region_rels = &RegionRelations::new(
self.tcx,
region_context,
region_map,
outlives_env.free_region_map(),
);
let (var_infos, data) = self
.inner
.borrow_mut()
@ -1228,8 +1240,16 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
.take()
.expect("regions already resolved")
.into_infos_and_data();
let region_rels = &RegionRelations::new(
self.tcx,
region_context,
region_map,
outlives_env.free_region_map(),
);
let (lexical_region_resolutions, errors) =
lexical_region_resolve::resolve(region_rels, var_infos, data);
lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
assert!(old_value.is_none());
@ -1240,7 +1260,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// this infcx was in use. This is totally hokey but
// otherwise we have a hard time separating legit region
// errors from silly ones.
self.report_region_errors(region_map, &errors, suppress);
self.report_region_errors(region_map, &errors);
}
}

View File

@ -1,10 +1,6 @@
pub use crate::passes::BoxedResolver;
use crate::util;
use rustc::lint;
use rustc::session::config::{self, ErrorOutputType, Input, OutputFilenames};
use rustc::session::early_error;
use rustc::session::{DiagnosticOutput, Session};
use rustc::ty;
use rustc::util::common::ErrorReported;
use rustc_ast::ast::{self, MetaItemKind};
@ -16,7 +12,11 @@ use rustc_data_structures::OnDrop;
use rustc_errors::registry::Registry;
use rustc_lint::LintStore;
use rustc_parse::new_parser_from_source_str;
use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
use rustc_session::early_error;
use rustc_session::lint;
use rustc_session::parse::{CrateConfig, ParseSess};
use rustc_session::{DiagnosticOutput, Session};
use rustc_span::edition;
use rustc_span::source_map::{FileLoader, FileName, SourceMap};
use std::path::PathBuf;

View File

@ -6,13 +6,8 @@ use log::{info, log_enabled, warn};
use rustc::arena::Arena;
use rustc::dep_graph::DepGraph;
use rustc::hir::map::Definitions;
use rustc::lint;
use rustc::middle;
use rustc::middle::cstore::{CrateStore, MetadataLoader, MetadataLoaderDyn};
use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType};
use rustc::session::config::{PpMode, PpSourceMode};
use rustc::session::search_paths::PathKind;
use rustc::session::Session;
use rustc::ty::steal::Steal;
use rustc::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
use rustc::util::common::ErrorReported;
@ -34,6 +29,11 @@ use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
use rustc_passes::{self, hir_stats, layout_test};
use rustc_plugin_impl as plugin;
use rustc_resolve::{Resolver, ResolverArenas};
use rustc_session::config::{self, CrateType, Input, OutputFilenames, OutputType};
use rustc_session::config::{PpMode, PpSourceMode};
use rustc_session::lint;
use rustc_session::search_paths::PathKind;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use rustc_span::FileName;
use rustc_trait_selection::traits;
@ -210,14 +210,7 @@ pub fn register_plugins<'a>(
Ok((krate, Lrc::new(lint_store)))
}
fn configure_and_expand_inner<'a>(
sess: &'a Session,
lint_store: &'a LintStore,
mut krate: ast::Crate,
crate_name: &str,
resolver_arenas: &'a ResolverArenas<'a>,
metadata_loader: &'a MetadataLoaderDyn,
) -> Result<(ast::Crate, Resolver<'a>)> {
fn pre_expansion_lint(sess: &Session, lint_store: &LintStore, krate: &ast::Crate) {
sess.time("pre_AST_expansion_lint_checks", || {
rustc_lint::check_ast_crate(
sess,
@ -228,6 +221,17 @@ fn configure_and_expand_inner<'a>(
rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
);
});
}
fn configure_and_expand_inner<'a>(
sess: &'a Session,
lint_store: &'a LintStore,
mut krate: ast::Crate,
crate_name: &str,
resolver_arenas: &'a ResolverArenas<'a>,
metadata_loader: &'a MetadataLoaderDyn,
) -> Result<(ast::Crate, Resolver<'a>)> {
pre_expansion_lint(sess, lint_store, &krate);
let mut resolver = Resolver::new(sess, &krate, crate_name, metadata_loader, &resolver_arenas);
rustc_builtin_macros::register_builtin_macros(&mut resolver, sess.edition());
@ -291,7 +295,8 @@ fn configure_and_expand_inner<'a>(
..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string())
};
let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
let extern_mod_loaded = |k: &ast::Crate| pre_expansion_lint(sess, lint_store, k);
let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver, Some(&extern_mod_loaded));
// Expand macros now!
let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));

View File

@ -3,8 +3,6 @@ use crate::passes::{self, BoxedResolver, QueryContext};
use rustc::arena::Arena;
use rustc::dep_graph::DepGraph;
use rustc::session::config::{OutputFilenames, OutputType};
use rustc::session::Session;
use rustc::ty::steal::Steal;
use rustc::ty::{GlobalCtxt, ResolverOutputs};
use rustc::util::common::ErrorReported;
@ -15,6 +13,8 @@ use rustc_hir::def_id::LOCAL_CRATE;
use rustc_hir::Crate;
use rustc_incremental::DepGraphFuture;
use rustc_lint::LintStore;
use rustc_session::config::{OutputFilenames, OutputType};
use rustc_session::Session;
use std::any::Any;
use std::cell::{Ref, RefCell, RefMut};
use std::mem;

View File

@ -2,16 +2,16 @@ extern crate getopts;
use crate::interface::parse_cfgspecs;
use rustc::lint::Level;
use rustc::middle::cstore;
use rustc::session::config::{build_configuration, build_session_options, to_crate_config};
use rustc::session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes};
use rustc::session::config::{ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath};
use rustc::session::config::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
use rustc::session::search_paths::SearchPath;
use rustc::session::{build_session, Session};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
use rustc_session::config::{build_configuration, build_session_options, to_crate_config};
use rustc_session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes};
use rustc_session::config::{ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath};
use rustc_session::config::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
use rustc_session::lint::Level;
use rustc_session::search_paths::SearchPath;
use rustc_session::{build_session, Session};
use rustc_span::edition::{Edition, DEFAULT_EDITION};
use rustc_span::symbol::sym;
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};

View File

@ -1,5 +1,4 @@
use log::info;
use rustc::lint;
use rustc::ty;
use rustc_ast::ast::{AttrVec, BlockCheckMode};
use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *};
@ -18,7 +17,7 @@ use rustc_metadata::dynamic_lib::DynamicLibrary;
use rustc_resolve::{self, Resolver};
use rustc_session as session;
use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
use rustc_session::parse::CrateConfig;
use rustc_session::CrateDisambiguator;
use rustc_session::{config, early_error, filesearch, DiagnosticOutput, Session};

View File

@ -22,7 +22,6 @@
//! `late_lint_methods!` invocation in `lib.rs`.
use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
use rustc::hir::map::Map;
use rustc::lint::LintDiagnosticBuilder;
use rustc::ty::{self, layout::VariantIdx, Ty, TyCtxt};
use rustc_ast::ast::{self, Expr};
@ -1071,7 +1070,7 @@ impl TypeAliasBounds {
err: &'a mut DiagnosticBuilder<'db>,
}
impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
type Map = Map<'v>;
type Map = intravisit::ErasedMap<'v>;
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
intravisit::NestedVisitorMap::None

View File

@ -18,7 +18,7 @@ use crate::context::{EarlyContext, LintContext, LintStore};
use crate::passes::{EarlyLintPass, EarlyLintPassObject};
use rustc_ast::ast;
use rustc_ast::visit as ast_visit;
use rustc_session::lint::{LintBuffer, LintPass};
use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
use rustc_session::Session;
use rustc_span::Span;
@ -37,13 +37,7 @@ struct EarlyContextAndPass<'a, T: EarlyLintPass> {
impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
fn check_id(&mut self, id: ast::NodeId) {
for early_lint in self.context.buffered.take(id) {
let rustc_session::lint::BufferedEarlyLint {
span,
msg,
node_id: _,
lint_id,
diagnostic,
} = early_lint;
let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
self.context.lookup_with_diagnostics(
lint_id.lint,
Some(span),
@ -326,11 +320,9 @@ pub fn check_ast_crate<T: EarlyLintPass>(
lint_buffer: Option<LintBuffer>,
builtin_lints: T,
) {
let mut passes: Vec<_> = if pre_expansion {
lint_store.pre_expansion_passes.iter().map(|p| (p)()).collect()
} else {
lint_store.early_passes.iter().map(|p| (p)()).collect()
};
let passes =
if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
let mut buffered = lint_buffer.unwrap_or_default();
if !sess.opts.debugging_opts.no_interleave_lints {

View File

@ -26,6 +26,7 @@ stable_deref_trait = "1.0.0"
rustc_ast = { path = "../librustc_ast" }
rustc_expand = { path = "../librustc_expand" }
rustc_span = { path = "../librustc_span" }
rustc_session = { path = "../librustc_session" }
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["errhandlingapi", "libloaderapi"] }

View File

@ -6,19 +6,18 @@ use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob
use rustc::hir::map::Definitions;
use rustc::middle::cstore::DepKind;
use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
use rustc::session::config;
use rustc::session::search_paths::PathKind;
use rustc::session::{CrateDisambiguator, Session};
use rustc::ty::TyCtxt;
use rustc_ast::ast;
use rustc_ast::attr;
use rustc_ast::expand::allocator::{global_allocator_spans, AllocatorKind};
use rustc_ast::{ast, attr};
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::Lrc;
use rustc_errors::struct_span_err;
use rustc_expand::base::SyntaxExtension;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_index::vec::IndexVec;
use rustc_session::config;
use rustc_session::search_paths::PathKind;
use rustc_session::{CrateDisambiguator, Session};
use rustc_span::edition::Edition;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{Span, DUMMY_SP};

View File

@ -56,10 +56,10 @@ use crate::creader::CStore;
use rustc::middle::cstore::LinkagePreference::{self, RequireDynamic, RequireStatic};
use rustc::middle::cstore::{self, DepKind};
use rustc::middle::dependency_format::{Dependencies, DependencyList, Linkage};
use rustc::session::config;
use rustc::ty::TyCtxt;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::CrateNum;
use rustc_session::config;
use rustc_target::spec::PanicStrategy;
crate fn calculate(tcx: TyCtxt<'_>) -> Dependencies {

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