Auto merge of #55746 - kennytm:rollup, r=kennytm

Rollup of 14 pull requests

Successful merges:

 - #55377 (Slight copy-editing for `std::cell::Cell` docs)
 - #55441 (Remove unused re import in gdb_rust_pretty_printing)
 - #55453 (Choose predicates without inference variables over those with them)
 - #55495 (Don't print opt fuel messages to stdout because it breaks Rustbuild)
 - #55501 (Make `process_obligations`' computation of `completed` optional.)
 - #55510 (Fix feature gate only being checked on first repr attr.)
 - #55609 (Run name-anon-globals after LTO passes as well)
 - #55645 (do not print wrapping ranges like normal ranges in validity diagnostics)
 - #55688 (Standardised names and location of ui issue tests)
 - #55692 (-C remark: fix incorrect warning about requiring "--debuginfo" instead of "-C debuginfo=n")
 - #55702 (Add `aarch64-pc-windows-msvc` to deployed targets)
 - #55728 (Update lldb)
 - #55730 (Use trait impl method span when type param mismatch is due to impl Trait)
 - #55734 (refactor: use shorthand fields)
This commit is contained in:
bors 2018-11-07 17:14:34 +00:00
commit 25a42b2ceb
169 changed files with 505 additions and 268 deletions

View file

@ -9,7 +9,6 @@
# except according to those terms.
import gdb
import re
import sys
import debugger_pretty_printers_common as rustpp

View file

@ -502,7 +502,7 @@ impl String {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(&vec) {
Ok(..) => Ok(String { vec: vec }),
Ok(..) => Ok(String { vec }),
Err(e) => {
Err(FromUtf8Error {
bytes: vec,

View file

@ -207,8 +207,8 @@ use ptr;
///
/// # Examples
///
/// Here you can see how using `Cell<T>` allows to use mutable field inside
/// immutable struct (which is also called 'interior mutability').
/// In this example, you can see that `Cell<T>` enables mutation inside an
/// immutable struct. In other words, it enables "interior mutability".
///
/// ```
/// use std::cell::Cell;
@ -225,10 +225,11 @@ use ptr;
///
/// let new_value = 100;
///
/// // ERROR, because my_struct is immutable
/// // ERROR: `my_struct` is immutable
/// // my_struct.regular_field = new_value;
///
/// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
/// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
/// // which can always be mutated
/// my_struct.special_field.set(new_value);
/// assert_eq!(my_struct.special_field.get(), new_value);
/// ```

View file

@ -29,7 +29,7 @@ struct Unaligned<T>(T);
impl DwarfReader {
pub fn new(ptr: *const u8) -> DwarfReader {
DwarfReader { ptr: ptr }
DwarfReader { ptr }
}
// DWARF streams are packed, so e.g. a u32 would not necessarily be aligned

View file

@ -41,7 +41,7 @@ struct PanicData {
}
pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
let panic_ctx = Box::new(PanicData { data: data });
let panic_ctx = Box::new(PanicData { data });
let params = [Box::into_raw(panic_ctx) as c::ULONG_PTR];
c::RaiseException(RUST_PANIC,
c::EXCEPTION_NONCONTINUABLE,

View file

@ -26,7 +26,7 @@ pub struct OpportunisticTypeResolver<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
impl<'a, 'gcx, 'tcx> OpportunisticTypeResolver<'a, 'gcx, 'tcx> {
pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>) -> Self {
OpportunisticTypeResolver { infcx: infcx }
OpportunisticTypeResolver { infcx }
}
}
@ -54,7 +54,7 @@ pub struct OpportunisticTypeAndRegionResolver<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
impl<'a, 'gcx, 'tcx> OpportunisticTypeAndRegionResolver<'a, 'gcx, 'tcx> {
pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>) -> Self {
OpportunisticTypeAndRegionResolver { infcx: infcx }
OpportunisticTypeAndRegionResolver { infcx }
}
}

View file

@ -169,7 +169,7 @@ impl<'tcx> TypeVariableTable<'tcx> {
// Hack: we only need this so that `types_escaping_snapshot`
// can see what has been unified; see the Delegate impl for
// more details.
self.values.record(Instantiate { vid: vid });
self.values.record(Instantiate { vid });
}
/// Creates a new type variable.

View file

@ -43,7 +43,7 @@ impl UnifyValue for RegionVidKey {
value2.min_vid
};
Ok(RegionVidKey { min_vid: min_vid })
Ok(RegionVidKey { min_vid })
}
}

View file

@ -469,7 +469,7 @@ impl<'a, 'tcx> Index<'tcx> {
/// Cross-references the feature names of unstable APIs with enabled
/// features and possibly prints errors.
pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let mut checker = Checker { tcx: tcx };
let mut checker = Checker { tcx };
tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
}

View file

@ -2986,7 +2986,7 @@ impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
use mir::TerminatorKind::*;
let kind = match self.kind {
Goto { target } => Goto { target: target },
Goto { target } => Goto { target },
SwitchInt {
ref discr,
switch_ty,

View file

@ -32,7 +32,7 @@ pub enum PlaceTy<'tcx> {
impl<'a, 'gcx, 'tcx> PlaceTy<'tcx> {
pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
PlaceTy::Ty { ty: ty }
PlaceTy::Ty { ty }
}
pub fn to_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {

View file

@ -2202,8 +2202,7 @@ pub fn build_session_options_and_crate_config(
if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
early_warn(
error_format,
"-C remark will not show source locations without \
--debuginfo",
"-C remark requires \"-C debuginfo=n\" to show source locations",
);
}

View file

@ -868,7 +868,7 @@ impl Session {
let fuel = self.optimization_fuel_limit.get();
ret = fuel != 0;
if fuel == 0 && !self.out_of_fuel.get() {
println!("optimization-fuel-exhausted: {}", msg());
eprintln!("optimization-fuel-exhausted: {}", msg());
self.out_of_fuel.set(true);
} else if fuel > 0 {
self.optimization_fuel_limit.set(fuel - 1);

View file

@ -447,27 +447,51 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
ty::RegionKind::ReLateBound(_, _),
) => {}
(ty::RegionKind::ReLateBound(_, _), _) => {
(ty::RegionKind::ReLateBound(_, _), _) |
(_, ty::RegionKind::ReVar(_)) => {
// One of these is true:
// The new predicate has a HRTB in a spot where the old
// predicate does not (if they both had a HRTB, the previous
// match arm would have executed).
// match arm would have executed). A HRBT is a 'stricter'
// bound than anything else, so we want to keep the newer
// predicate (with the HRBT) in place of the old predicate.
//
// The means we want to remove the older predicate from
// user_computed_preds, since having both it and the new
// OR
//
// The old predicate has a region variable where the new
// predicate has some other kind of region. An region
// variable isn't something we can actually display to a user,
// so we choose ther new predicate (which doesn't have a region
// varaible).
//
// In both cases, we want to remove the old predicate,
// from user_computed_preds, and replace it with the new
// one. Having both the old and the new
// predicate in a ParamEnv would confuse SelectionContext
//
// We're currently in the predicate passed to 'retain',
// so we return 'false' to remove the old predicate from
// user_computed_preds
return false;
}
(_, ty::RegionKind::ReLateBound(_, _)) => {
// This is the opposite situation as the previous arm - the
// old predicate has a HRTB lifetime in a place where the
// new predicate does not. We want to leave the old
(_, ty::RegionKind::ReLateBound(_, _)) |
(ty::RegionKind::ReVar(_), _) => {
// This is the opposite situation as the previous arm.
// One of these is true:
//
// The old predicate has a HRTB lifetime in a place where the
// new predicate does not.
//
// OR
//
// The new predicate has a region variable where the old
// predicate has some other type of region.
//
// We want to leave the old
// predicate in user_computed_preds, and skip adding
// new_pred to user_computed_params.
should_add_new = false
}
},
_ => {}
}
}

View file

@ -12,8 +12,9 @@ use infer::InferCtxt;
use mir::interpret::{GlobalId, ErrorHandled};
use ty::{self, Ty, TypeFoldable, ToPolyTraitRef, ToPredicate};
use ty::error::ExpectedFound;
use rustc_data_structures::obligation_forest::{Error, ForestObligation, ObligationForest};
use rustc_data_structures::obligation_forest::{ObligationProcessor, ProcessResult};
use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
use rustc_data_structures::obligation_forest::{ProcessResult};
use std::marker::PhantomData;
use hir::def_id::DefId;
@ -98,7 +99,7 @@ impl<'a, 'gcx, 'tcx> FulfillmentContext<'tcx> {
let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
selcx,
register_region_obligations: self.register_region_obligations
});
}, DoCompleted::No);
debug!("select: outcome={:#?}", outcome);
// FIXME: if we kept the original cache key, we could mark projection

View file

@ -266,7 +266,7 @@ fn project_and_unify_type<'cx, 'gcx, 'tcx>(
},
Err(err) => {
debug!("project_and_unify_type: equating types encountered error {:?}", err);
Err(MismatchedProjectionTypes { err: err })
Err(MismatchedProjectionTypes { err })
}
}
}

View file

@ -3526,7 +3526,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
_ => bug!(),
};
Ok(VtableBuiltinData { nested: nested })
Ok(VtableBuiltinData { nested })
}
///////////////////////////////////////////////////////////////////////////

View file

@ -34,7 +34,7 @@ pub struct Match<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
impl<'a, 'gcx, 'tcx> Match<'a, 'gcx, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Match<'a, 'gcx, 'tcx> {
Match { tcx: tcx }
Match { tcx }
}
}

View file

@ -82,7 +82,7 @@ pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
}
fn has_type_flags(&self, flags: TypeFlags) -> bool {
self.visit_with(&mut HasTypeFlagsVisitor { flags: flags })
self.visit_with(&mut HasTypeFlagsVisitor { flags })
}
fn has_projections(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_PROJECTION)

View file

@ -605,6 +605,13 @@ fn run_pass_manager(cgcx: &CodegenContext,
}
});
// We always generate bitcode through ThinLTOBuffers,
// which do not support anonymous globals
if config.bitcode_needed() {
let pass = llvm::LLVMRustFindAndCreatePass("name-anon-globals\0".as_ptr() as *const _);
llvm::LLVMRustAddPass(pm, pass.unwrap());
}
if config.verify_llvm_ir {
let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
llvm::LLVMRustAddPass(pm, pass.unwrap());

View file

@ -337,6 +337,11 @@ impl ModuleConfig {
self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
sess.opts.optimize == config::OptLevel::Aggressive;
}
pub fn bitcode_needed(&self) -> bool {
self.emit_bc || self.obj_is_bitcode
|| self.emit_bc_compressed || self.embed_bitcode
}
}
/// Assembler name and command used by codegen when no_integrated_as is enabled
@ -564,8 +569,7 @@ unsafe fn optimize(cgcx: &CodegenContext,
// Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
// to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
// we'll get errors in LLVM.
let using_thin_buffers = config.emit_bc || config.obj_is_bitcode
|| config.emit_bc_compressed || config.embed_bitcode;
let using_thin_buffers = config.bitcode_needed();
let mut have_name_anon_globals_pass = false;
if !config.no_prepopulate_passes {
llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);

View file

@ -190,7 +190,7 @@ impl ObjectFile {
pub fn new(llmb: &'static mut MemoryBuffer) -> Option<ObjectFile> {
unsafe {
let llof = LLVMCreateObjectFile(llmb)?;
Some(ObjectFile { llof: llof })
Some(ObjectFile { llof })
}
}
}

View file

@ -346,7 +346,7 @@ pub fn cleanup_kinds<'a, 'tcx>(mir: &mir::Mir<'tcx>) -> IndexVec<mir::BasicBlock
funclet, succ, kind);
match kind {
CleanupKind::NotCleanup => {
result[succ] = CleanupKind::Internal { funclet: funclet };
result[succ] = CleanupKind::Internal { funclet };
}
CleanupKind::Funclet => {
if funclet != succ {

View file

@ -32,7 +32,7 @@ pub fn report_symbol_names<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
}
tcx.dep_graph.with_ignore(|| {
let mut visitor = SymbolNamesTest { tcx: tcx };
let mut visitor = SymbolNamesTest { tcx };
tcx.hir.krate().visit_all_item_likes(&mut visitor);
})
}

View file

@ -214,7 +214,7 @@ cfg_if! {
unsafe { libc::close(fd); }
Err(err)
} else {
Ok(Lock { fd: fd })
Ok(Lock { fd })
}
}
}

View file

@ -162,8 +162,8 @@ enum NodeState {
#[derive(Debug)]
pub struct Outcome<O, E> {
/// Obligations that were completely evaluated, including all
/// (transitive) subobligations.
pub completed: Vec<O>,
/// (transitive) subobligations. Only computed if requested.
pub completed: Option<Vec<O>>,
/// Backtrace of obligations that were found to be in error.
pub errors: Vec<Error<O, E>>,
@ -177,6 +177,14 @@ pub struct Outcome<O, E> {
pub stalled: bool,
}
/// Should `process_obligations` compute the `Outcome::completed` field of its
/// result?
#[derive(PartialEq)]
pub enum DoCompleted {
No,
Yes,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Error<O, E> {
pub error: E,
@ -282,8 +290,8 @@ impl<O: ForestObligation> ObligationForest<O> {
});
}
}
let successful_obligations = self.compress();
assert!(successful_obligations.is_empty());
let successful_obligations = self.compress(DoCompleted::Yes);
assert!(successful_obligations.unwrap().is_empty());
errors
}
@ -311,7 +319,8 @@ impl<O: ForestObligation> ObligationForest<O> {
/// be called in a loop until `outcome.stalled` is false.
///
/// This CANNOT be unrolled (presently, at least).
pub fn process_obligations<P>(&mut self, processor: &mut P) -> Outcome<O, P::Error>
pub fn process_obligations<P>(&mut self, processor: &mut P, do_completed: DoCompleted)
-> Outcome<O, P::Error>
where P: ObligationProcessor<Obligation=O>
{
debug!("process_obligations(len={})", self.nodes.len());
@ -366,7 +375,7 @@ impl<O: ForestObligation> ObligationForest<O> {
// There's no need to perform marking, cycle processing and compression when nothing
// changed.
return Outcome {
completed: vec![],
completed: if do_completed == DoCompleted::Yes { Some(vec![]) } else { None },
errors,
stalled,
};
@ -376,12 +385,12 @@ impl<O: ForestObligation> ObligationForest<O> {
self.process_cycles(processor);
// Now we have to compress the result
let completed_obligations = self.compress();
let completed = self.compress(do_completed);
debug!("process_obligations: complete");
Outcome {
completed: completed_obligations,
completed,
errors,
stalled,
}
@ -524,7 +533,7 @@ impl<O: ForestObligation> ObligationForest<O> {
/// Beforehand, all nodes must be marked as `Done` and no cycles
/// on these nodes may be present. This is done by e.g. `process_cycles`.
#[inline(never)]
fn compress(&mut self) -> Vec<O> {
fn compress(&mut self, do_completed: DoCompleted) -> Option<Vec<O>> {
let nodes_len = self.nodes.len();
let mut node_rewrites: Vec<_> = self.scratch.take().unwrap();
node_rewrites.extend(0..nodes_len);
@ -573,21 +582,26 @@ impl<O: ForestObligation> ObligationForest<O> {
if dead_nodes == 0 {
node_rewrites.truncate(0);
self.scratch = Some(node_rewrites);
return vec![];
return if do_completed == DoCompleted::Yes { Some(vec![]) } else { None };
}
// Pop off all the nodes we killed and extract the success
// stories.
let successful = (0..dead_nodes)
.map(|_| self.nodes.pop().unwrap())
.flat_map(|node| {
match node.state.get() {
NodeState::Error => None,
NodeState::Done => Some(node.obligation),
_ => unreachable!()
}
})
.collect();
let successful = if do_completed == DoCompleted::Yes {
Some((0..dead_nodes)
.map(|_| self.nodes.pop().unwrap())
.flat_map(|node| {
match node.state.get() {
NodeState::Error => None,
NodeState::Done => Some(node.obligation),
_ => unreachable!()
}
})
.collect())
} else {
self.nodes.truncate(self.nodes.len() - dead_nodes);
None
};
self.apply_rewrites(&node_rewrites);
node_rewrites.truncate(0);

View file

@ -10,7 +10,7 @@
#![cfg(test)]
use super::{Error, ObligationForest, ObligationProcessor, Outcome, ProcessResult};
use super::{Error, DoCompleted, ObligationForest, ObligationProcessor, Outcome, ProcessResult};
use std::fmt;
use std::marker::PhantomData;
@ -84,8 +84,8 @@ fn push_pop() {
"C" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["C"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["C"]);
assert_eq!(err,
vec![Error {
error: "B is for broken",
@ -108,8 +108,8 @@ fn push_pop() {
"D" => ProcessResult::Changed(vec!["D.1", "D.2"]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, Vec::<&'static str>::new());
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), Vec::<&'static str>::new());
assert_eq!(err, Vec::new());
@ -127,8 +127,8 @@ fn push_pop() {
"D.2" => ProcessResult::Changed(vec!["D.2.i"]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.3", "A.1", "A.3.i"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["A.3", "A.1", "A.3.i"]);
assert_eq!(err,
vec![Error {
error: "A is for apple",
@ -143,8 +143,8 @@ fn push_pop() {
"D.2.i" => ProcessResult::Changed(vec![]),
_ => panic!("unexpected obligation {:?}", obligation),
}
}, |_| {}));
assert_eq!(ok, vec!["D.2.i", "D.2"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["D.2.i", "D.2"]);
assert_eq!(err,
vec![Error {
error: "D is for dumb",
@ -171,8 +171,8 @@ fn success_in_grandchildren() {
"A" => ProcessResult::Changed(vec!["A.1", "A.2", "A.3"]),
_ => unreachable!(),
}
}, |_| {}));
assert!(ok.is_empty());
}, |_| {}), DoCompleted::Yes);
assert!(ok.unwrap().is_empty());
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
@ -183,8 +183,8 @@ fn success_in_grandchildren() {
"A.3" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.3", "A.1"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["A.3", "A.1"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
@ -194,8 +194,8 @@ fn success_in_grandchildren() {
"A.2.ii" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.2.ii"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["A.2.ii"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
@ -204,14 +204,15 @@ fn success_in_grandchildren() {
"A.2.i.a" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_| {}));
assert_eq!(ok, vec!["A.2.i.a", "A.2.i", "A.2", "A"]);
}, |_| {}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["A.2.i.a", "A.2.i", "A.2", "A"]);
assert!(err.is_empty());
let Outcome { completed: ok, errors: err, .. } =
forest.process_obligations(&mut C(|_| unreachable!(), |_| {}));
forest.process_obligations(&mut C(|_| unreachable!(), |_| {}),
DoCompleted::Yes);
assert!(ok.is_empty());
assert!(ok.unwrap().is_empty());
assert!(err.is_empty());
}
@ -227,8 +228,8 @@ fn to_errors_no_throw() {
"A" => ProcessResult::Changed(vec!["A.1", "A.2", "A.3"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let errors = forest.to_errors(());
assert_eq!(errors[0].backtrace, vec!["A.1", "A"]);
@ -248,8 +249,8 @@ fn diamond() {
"A" => ProcessResult::Changed(vec!["A.1", "A.2"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
@ -259,8 +260,8 @@ fn diamond() {
"A.2" => ProcessResult::Changed(vec!["D"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let mut d_count = 0;
@ -270,9 +271,9 @@ fn diamond() {
"D" => { d_count += 1; ProcessResult::Changed(vec![]) },
_ => unreachable!(),
}
}, |_|{}));
}, |_|{}), DoCompleted::Yes);
assert_eq!(d_count, 1);
assert_eq!(ok, vec!["D", "A.2", "A.1", "A"]);
assert_eq!(ok.unwrap(), vec!["D", "A.2", "A.1", "A"]);
assert_eq!(err.len(), 0);
let errors = forest.to_errors(());
@ -285,8 +286,8 @@ fn diamond() {
"A'" => ProcessResult::Changed(vec!["A'.1", "A'.2"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
@ -296,8 +297,8 @@ fn diamond() {
"A'.2" => ProcessResult::Changed(vec!["D'"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let mut d_count = 0;
@ -307,9 +308,9 @@ fn diamond() {
"D'" => { d_count += 1; ProcessResult::Error("operation failed") },
_ => unreachable!(),
}
}, |_|{}));
}, |_|{}), DoCompleted::Yes);
assert_eq!(d_count, 1);
assert_eq!(ok.len(), 0);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err, vec![super::Error {
error: "operation failed",
backtrace: vec!["D'", "A'.1", "A'"]
@ -333,8 +334,8 @@ fn done_dependency() {
"A: Sized" | "B: Sized" | "C: Sized" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["C: Sized", "B: Sized", "A: Sized"]);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["C: Sized", "B: Sized", "A: Sized"]);
assert_eq!(err.len(), 0);
forest.register_obligation("(A,B,C): Sized");
@ -348,8 +349,8 @@ fn done_dependency() {
]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["(A,B,C): Sized"]);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["(A,B,C): Sized"]);
assert_eq!(err.len(), 0);
}
@ -371,8 +372,8 @@ fn orphan() {
"C2" => ProcessResult::Changed(vec![]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok, vec!["C2", "C1"]);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap(), vec!["C2", "C1"]);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
@ -382,8 +383,8 @@ fn orphan() {
"B" => ProcessResult::Changed(vec!["D"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err.len(), 0);
let Outcome { completed: ok, errors: err, .. } =
@ -393,8 +394,8 @@ fn orphan() {
"E" => ProcessResult::Error("E is for error"),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err, vec![super::Error {
error: "E is for error",
backtrace: vec!["E", "A"]
@ -406,8 +407,8 @@ fn orphan() {
"D" => ProcessResult::Error("D is dead"),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err, vec![super::Error {
error: "D is dead",
backtrace: vec!["D"]
@ -431,8 +432,8 @@ fn simultaneous_register_and_error() {
"B" => ProcessResult::Changed(vec!["A"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err, vec![super::Error {
error: "An error",
backtrace: vec!["A"]
@ -449,8 +450,8 @@ fn simultaneous_register_and_error() {
"B" => ProcessResult::Changed(vec!["A"]),
_ => unreachable!(),
}
}, |_|{}));
assert_eq!(ok.len(), 0);
}, |_|{}), DoCompleted::Yes);
assert_eq!(ok.unwrap().len(), 0);
assert_eq!(err, vec![super::Error {
error: "An error",
backtrace: vec!["A"]

View file

@ -31,7 +31,7 @@ impl Svh {
/// compute the SVH from some HIR, you want the `calculate_svh`
/// function found in `librustc_incremental`.
pub fn new(hash: u64) -> Svh {
Svh { hash: hash }
Svh { hash }
}
pub fn as_u64(&self) -> u64 {

View file

@ -952,7 +952,7 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
control.compilation_done.callback = box move |state| {
old_callback(state);
let sess = state.session;
println!("Fuel used by {}: {}",
eprintln!("Fuel used by {}: {}",
sess.print_fuel_crate.as_ref().unwrap(),
sess.print_fuel.get());
}

View file

@ -795,7 +795,7 @@ impl LintPass for ImproperCTypes {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
fn check_foreign_item(&mut self, cx: &LateContext, it: &hir::ForeignItem) {
let mut vis = ImproperCTypesVisitor { cx: cx };
let mut vis = ImproperCTypesVisitor { cx };
let abi = cx.tcx.hir.get_foreign_abi(it.id);
if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
match it.node {

View file

@ -323,7 +323,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
index.record(DefId::local(CRATE_DEF_INDEX),
IsolatedEncoder::encode_info_for_mod,
FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &vis)));
let mut visitor = EncodeVisitor { index: index };
let mut visitor = EncodeVisitor { index };
krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
for macro_def in &krate.exported_macros {
visitor.visit_macro_def(macro_def);

View file

@ -453,7 +453,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
}
let scope = &self.scopes[len - scope_count];
self.cfg.terminate(block, scope.source_info(span),
TerminatorKind::Goto { target: target });
TerminatorKind::Goto { target });
}
/// Creates a path that performs all required cleanup for dropping a generator.
@ -1019,7 +1019,7 @@ fn build_diverge_scope<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
} else {
let block = cfg.start_new_cleanup_block();
cfg.push_end_region(tcx, block, source_info(span), scope.region_scope);
cfg.terminate(block, source_info(span), TerminatorKind::Goto { target: target });
cfg.terminate(block, source_info(span), TerminatorKind::Goto { target });
*cached_block = Some(block);
block
}

View file

@ -28,7 +28,7 @@ pub struct HaveBeenBorrowedLocals<'a, 'tcx: 'a> {
impl<'a, 'tcx: 'a> HaveBeenBorrowedLocals<'a, 'tcx> {
pub fn new(mir: &'a Mir<'tcx>)
-> Self {
HaveBeenBorrowedLocals { mir: mir }
HaveBeenBorrowedLocals { mir }
}
pub fn mir(&self) -> &Mir<'tcx> {

View file

@ -21,7 +21,7 @@ pub struct MaybeStorageLive<'a, 'tcx: 'a> {
impl<'a, 'tcx: 'a> MaybeStorageLive<'a, 'tcx> {
pub fn new(mir: &'a Mir<'tcx>)
-> Self {
MaybeStorageLive { mir: mir }
MaybeStorageLive { mir }
}
pub fn mir(&self) -> &Mir<'tcx> {

View file

@ -52,7 +52,7 @@ impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
}
pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx }.as_deep_visitor());
tcx.sess.abort_if_errors();
}

View file

@ -571,7 +571,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> {
})
.collect();
PatternKind::Leaf { subpatterns: subpatterns }
PatternKind::Leaf { subpatterns }
}
ty::Error => { // Avoid ICE (#50577)
return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
@ -778,13 +778,13 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> {
subpatterns,
}
} else {
PatternKind::Leaf { subpatterns: subpatterns }
PatternKind::Leaf { subpatterns }
}
}
Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
PatternKind::Leaf { subpatterns: subpatterns }
PatternKind::Leaf { subpatterns }
}
_ => {

View file

@ -10,6 +10,7 @@
use std::fmt::Write;
use std::hash::Hash;
use std::ops::RangeInclusive;
use syntax_pos::symbol::Symbol;
use rustc::ty::layout::{self, Size, Align, TyLayout, LayoutOf};
@ -122,6 +123,37 @@ fn path_format(path: &Vec<PathElem>) -> String {
out
}
// Test if a range that wraps at overflow contains `test`
fn wrapping_range_contains(r: &RangeInclusive<u128>, test: u128) -> bool {
let (lo, hi) = r.clone().into_inner();
if lo > hi {
// Wrapped
(..=hi).contains(&test) || (lo..).contains(&test)
} else {
// Normal
r.contains(&test)
}
}
// Formats such that a sentence like "expected something {}" to mean
// "expected something <in the given range>" makes sense.
fn wrapping_range_format(r: &RangeInclusive<u128>, max_hi: u128) -> String {
let (lo, hi) = r.clone().into_inner();
debug_assert!(hi <= max_hi);
if lo > hi {
format!("less or equal to {}, or greater or equal to {}", hi, lo)
} else {
if lo == 0 {
debug_assert!(hi < max_hi, "should not be printing if the range covers everything");
format!("less or equal to {}", hi)
} else if hi == max_hi {
format!("greater or equal to {}", lo)
} else {
format!("in the range {:?}", r)
}
}
}
struct ValidityVisitor<'rt, 'a: 'rt, 'mir: 'rt, 'tcx: 'a+'rt+'mir, M: Machine<'a, 'mir, 'tcx>+'rt> {
/// The `path` may be pushed to, but the part that is present when a function
/// starts must not be changed! `visit_fields` and `visit_array` rely on
@ -428,8 +460,8 @@ impl<'rt, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>>
"a pointer",
self.path,
format!(
"something that cannot possibly be outside the (wrapping) range {:?}",
layout.valid_range
"something that cannot possibly fail to be {}",
wrapping_range_format(&layout.valid_range, max_hi)
)
);
}
@ -440,33 +472,14 @@ impl<'rt, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>>
}
};
// Now compare. This is slightly subtle because this is a special "wrap-around" range.
use std::ops::RangeInclusive;
let in_range = |bound: RangeInclusive<u128>| bound.contains(&bits);
if lo > hi {
// wrapping around
if in_range(0..=hi) || in_range(lo..=max_hi) {
Ok(())
} else {
validation_failure!(
bits,
self.path,
format!("something in the range {:?} or {:?}", 0..=hi, lo..=max_hi)
)
}
if wrapping_range_contains(&layout.valid_range, bits) {
Ok(())
} else {
if in_range(layout.valid_range.clone()) {
Ok(())
} else {
validation_failure!(
bits,
self.path,
if hi == max_hi {
format!("something greater or equal to {}", lo)
} else {
format!("something in the range {:?}", layout.valid_range)
}
)
}
validation_failure!(
bits,
self.path,
format!("something {}", wrapping_range_format(&layout.valid_range, max_hi))
)
}
}

View file

@ -495,7 +495,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
let target = self.patch.new_block(BasicBlockData {
statements: vec![assign],
terminator: Some(Terminator {
kind: TerminatorKind::Goto { target: target },
kind: TerminatorKind::Goto { target },
..*terminator
}),
is_cleanup: false,

View file

@ -302,7 +302,7 @@ impl MirPass for SimplifyLocals {
let map = make_local_map(&mut mir.local_decls, marker.locals);
// Update references to all vars and tmps now
LocalUpdater { map: map }.visit_mir(mir);
LocalUpdater { map }.visit_mir(mir);
mir.local_decls.shrink_to_fit();
}
}

View file

@ -57,7 +57,7 @@ impl MirPass for SimplifyBranches {
TerminatorKind::Assert {
target, cond: Operand::Constant(ref c), expected, ..
} if (c.literal.assert_bool(tcx) == Some(true)) == expected => {
TerminatorKind::Goto { target: target }
TerminatorKind::Goto { target }
},
TerminatorKind::FalseEdges { real_target, .. } => {
TerminatorKind::Goto { target: real_target }

View file

@ -672,5 +672,5 @@ pub fn check_crate(session: &Session, krate: &Crate) {
is_banned: false,
}, krate);
visit::walk_crate(&mut AstValidator { session: session }, krate)
visit::walk_crate(&mut AstValidator { session }, krate)
}

View file

@ -4422,7 +4422,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
// declared as public (due to pruning, we don't explore
// outside crate private modules => no need to check this)
if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
candidates.push(ImportSuggestion { path: path });
candidates.push(ImportSuggestion { path });
}
}
}
@ -4519,7 +4519,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
span: name_binding.span,
segments: path_segments,
};
result = Some((module, ImportSuggestion { path: path }));
result = Some((module, ImportSuggestion { path }));
} else {
// add the module to the lookup
if seen_modules.insert(module.def_id().unwrap()) {

View file

@ -71,7 +71,7 @@ impl<'b> JsonDumper<CallbackOutput<'b>> {
config: Config,
) -> JsonDumper<CallbackOutput<'b>> {
JsonDumper {
output: CallbackOutput { callback: callback },
output: CallbackOutput { callback },
config: config.clone(),
result: Analysis::new(config),
}

View file

@ -595,7 +595,9 @@ fn compare_number_of_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
if num_impl_m_type_params != num_trait_m_type_params {
let impl_m_node_id = tcx.hir.as_local_node_id(impl_m.def_id).unwrap();
let impl_m_item = tcx.hir.expect_impl_item(impl_m_node_id);
let span = if impl_m_item.generics.params.is_empty() {
let span = if impl_m_item.generics.params.is_empty()
|| impl_m_item.generics.span.is_dummy() // impl Trait in argument position (#55374)
{
impl_m_span
} else {
impl_m_item.generics.span

View file

@ -993,7 +993,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
AdtField { ty: field_ty, span: field.span }
})
.collect();
AdtVariant { fields: fields }
AdtVariant { fields }
}
fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {

View file

@ -17,7 +17,7 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::hir;
pub fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let mut orphan = OrphanChecker { tcx: tcx };
let mut orphan = OrphanChecker { tcx };
tcx.hir.krate().visit_all_item_likes(&mut orphan);
}

View file

@ -16,7 +16,7 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::hir::{self, Unsafety};
pub fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let mut unsafety = UnsafetyChecker { tcx: tcx };
let mut unsafety = UnsafetyChecker { tcx };
tcx.hir.krate().visit_all_item_likes(&mut unsafety);
}

View file

@ -64,7 +64,7 @@ struct OnlySelfBounds(bool);
// Main entry point
pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let mut visitor = CollectItemTypesVisitor { tcx: tcx };
let mut visitor = CollectItemTypesVisitor { tcx };
tcx.hir
.krate()
.visit_all_item_likes(&mut visitor.as_deep_visitor());

View file

@ -62,7 +62,7 @@ pub fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
// We will tag this as part of the WF check -- logically, it is,
// but it's one that we must perform earlier than the rest of
// WfCheck.
tcx.hir.krate().visit_all_item_likes(&mut ImplWfCheck { tcx: tcx });
tcx.hir.krate().visit_all_item_likes(&mut ImplWfCheck { tcx });
}
struct ImplWfCheck<'a, 'tcx: 'a> {

View file

@ -2966,7 +2966,7 @@ impl<'tcx> Clean<Item> for ty::VariantDef {
source: cx.tcx.def_span(self.did).clean(cx),
visibility: Some(Inherited),
def_id: self.did,
inner: VariantItem(Variant { kind: kind }),
inner: VariantItem(Variant { kind }),
stability: get_stability(cx, self.did),
deprecation: get_deprecation(cx, self.did),
}

View file

@ -3418,7 +3418,7 @@ mod test_map {
slot.borrow_mut()[k] += 1;
});
Droppable { k: k }
Droppable { k }
}
}

View file

@ -877,7 +877,7 @@ impl OpenOptions {
fn _open(&self, path: &Path) -> io::Result<File> {
let inner = fs_imp::File::open(path, &self.0)?;
Ok(File { inner: inner })
Ok(File { inner })
}
}

View file

@ -150,7 +150,7 @@ pub struct Repeat { byte: u8 }
/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
pub fn repeat(byte: u8) -> Repeat { Repeat { byte } }
#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Repeat {

View file

@ -931,7 +931,7 @@ impl<T> fmt::Debug for Sender<T> {
impl<T> SyncSender<T> {
fn new(inner: Arc<sync::Packet<T>>) -> SyncSender<T> {
SyncSender { inner: inner }
SyncSender { inner }
}
/// Sends a value on this synchronous channel.

View file

@ -32,7 +32,7 @@ impl Instant {
let mut t = mem::uninitialized();
let ret = abi::clock_time_get(abi::clockid::MONOTONIC, 0, &mut t);
assert_eq!(ret, abi::errno::SUCCESS);
Instant { t: t }
Instant { t }
}
}
@ -71,7 +71,7 @@ impl SystemTime {
let mut t = mem::uninitialized();
let ret = abi::clock_time_get(abi::clockid::REALTIME, 0, &mut t);
assert_eq!(ret, abi::errno::SUCCESS);
SystemTime { t: t }
SystemTime { t }
}
}

View file

@ -21,7 +21,7 @@ pub struct FileDesc {
impl FileDesc {
pub fn new(fd: usize) -> FileDesc {
FileDesc { fd: fd }
FileDesc { fd }
}
pub fn raw(&self) -> usize { self.fd }

View file

@ -264,7 +264,7 @@ impl File {
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat = syscall::Stat::default();
cvt(syscall::fstat(self.0.raw(), &mut stat))?;
Ok(FileAttr { stat: stat })
Ok(FileAttr { stat })
}
pub fn fsync(&self) -> io::Result<()> {

View file

@ -19,7 +19,7 @@ pub type Result<T> = result::Result<T, Error>;
impl Error {
pub fn new(errno: i32) -> Error {
Error { errno: errno }
Error { errno }
}
pub fn mux(result: Result<usize>) -> usize {

View file

@ -38,7 +38,7 @@ impl Thread {
panic!("thread failed to exit");
} else {
mem::forget(p);
Ok(Thread { id: id })
Ok(Thread { id })
}
}

View file

@ -187,7 +187,7 @@ impl SystemTime {
impl From<syscall::TimeSpec> for SystemTime {
fn from(t: syscall::TimeSpec) -> SystemTime {
SystemTime { t: Timespec { t: t } }
SystemTime { t: Timespec { t } }
}
}

View file

@ -41,7 +41,7 @@ fn max_len() -> usize {
impl FileDesc {
pub fn new(fd: c_int) -> FileDesc {
FileDesc { fd: fd }
FileDesc { fd }
}
pub fn raw(&self) -> c_int { self.fd }

View file

@ -317,7 +317,7 @@ impl DirEntry {
cvt(unsafe {
fstatat64(fd, self.entry.d_name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW)
})?;
Ok(FileAttr { stat: stat })
Ok(FileAttr { stat })
}
#[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
@ -526,7 +526,7 @@ impl File {
cvt(unsafe {
fstat64(self.0.raw(), &mut stat)
})?;
Ok(FileAttr { stat: stat })
Ok(FileAttr { stat })
}
pub fn fsync(&self) -> io::Result<()> {
@ -807,7 +807,7 @@ pub fn stat(p: &Path) -> io::Result<FileAttr> {
cvt(unsafe {
stat64(p.as_ptr(), &mut stat)
})?;
Ok(FileAttr { stat: stat })
Ok(FileAttr { stat })
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
@ -816,7 +816,7 @@ pub fn lstat(p: &Path) -> io::Result<FileAttr> {
cvt(unsafe {
lstat64(p.as_ptr(), &mut stat)
})?;
Ok(FileAttr { stat: stat })
Ok(FileAttr { stat })
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {

View file

@ -217,7 +217,7 @@ mod inner {
impl From<libc::timespec> for SystemTime {
fn from(t: libc::timespec) -> SystemTime {
SystemTime { t: Timespec { t: t } }
SystemTime { t: Timespec { t } }
}
}
@ -332,7 +332,7 @@ mod inner {
impl From<libc::timespec> for SystemTime {
fn from(t: libc::timespec) -> SystemTime {
SystemTime { t: Timespec { t: t } }
SystemTime { t: Timespec { t } }
}
}

View file

@ -241,7 +241,7 @@ impl<'a> DropGuard<'a> {
fn new(lock: &'a Mutex) -> DropGuard<'a> {
unsafe {
lock.lock();
DropGuard { lock: lock }
DropGuard { lock }
}
}
}

View file

@ -170,7 +170,7 @@ impl fmt::Debug for SystemTime {
impl From<c::FILETIME> for SystemTime {
fn from(t: c::FILETIME) -> SystemTime {
SystemTime { t: t }
SystemTime { t }
}
}

View file

@ -174,7 +174,7 @@ impl<T> PoisonError<T> {
/// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
#[stable(feature = "sync_poison", since = "1.2.0")]
pub fn new(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
PoisonError { guard }
}
/// Consumes this error indicating that a lock is poisoned, returning the

View file

@ -67,7 +67,7 @@ impl CodePoint {
/// Only use when `value` is known to be less than or equal to 0x10FFFF.
#[inline]
pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
CodePoint { value: value }
CodePoint { value }
}
/// Creates a new `CodePoint` if the value is a valid code point.
@ -76,7 +76,7 @@ impl CodePoint {
#[inline]
pub fn from_u32(value: u32) -> Option<CodePoint> {
match value {
0 ..= 0x10FFFF => Some(CodePoint { value: value }),
0 ..= 0x10FFFF => Some(CodePoint { value }),
_ => None
}
}

View file

@ -455,6 +455,11 @@ pub fn find_by_name<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attrib
attrs.iter().find(|attr| attr.check_name(name))
}
pub fn filter_by_name<'a>(attrs: &'a [Attribute], name: &'a str)
-> impl Iterator<Item = &'a Attribute> {
attrs.iter().filter(move |attr| attr.check_name(name))
}
pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option<Symbol> {
attrs.iter()
.find(|at| at.check_name(name))

View file

@ -126,7 +126,7 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::T
}
}
Box::new(ExpandResult { p: p })
Box::new(ExpandResult { p })
}
// include_str! : read the given file, insert it as a literal string expr

View file

@ -1614,7 +1614,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
}
ast::ItemKind::Struct(..) => {
if let Some(attr) = attr::find_by_name(&i.attrs[..], "repr") {
for attr in attr::filter_by_name(&i.attrs[..], "repr") {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name("simd") {
gate_feature_post!(&self, repr_simd, attr.span,

View file

@ -945,7 +945,7 @@ pub fn noop_fold_item_kind<T: Folder>(i: ItemKind, folder: &mut T) -> ItemKind {
ItemKind::Enum(enum_definition, generics) => {
let generics = folder.fold_generics(generics);
let variants = enum_definition.variants.move_map(|x| folder.fold_variant(x));
ItemKind::Enum(ast::EnumDef { variants: variants }, generics)
ItemKind::Enum(ast::EnumDef { variants }, generics)
}
ItemKind::Struct(struct_def, generics) => {
let generics = folder.fold_generics(generics);

View file

@ -6929,7 +6929,7 @@ impl<'a> Parser<'a> {
_ => ()
}
Ok(ast::EnumDef { variants: variants })
Ok(ast::EnumDef { variants })
}
/// Parse an "enum" declaration

View file

@ -99,7 +99,7 @@
// lldb-command:print padded_tuple
// lldbg-check:[...]$4 = &[(6, 7), (8, 9)]
// lldbr-check:(&[(i32, i16)]) padded_tuple = { data_ptr = *0x555555555030 length = 2 }
// lldbr-check:(&[(i32, i16)]) padded_tuple = { data_ptr = *[...] length = 2 }
// lldb-command:print padded_struct
// lldbg-check:[...]$5 = &[AStruct { x: 10, y: 11, z: 12 }, AStruct { x: 13, y: 14, z: 15 }]

View file

@ -12,7 +12,8 @@
use std::mem::size_of;
// compile-flags: -Z fuel=foo=0
// (#55495: The --error-format is to sidestep an issue in our test harness)
// compile-flags: --error-format human -Z fuel=foo=0
struct S1(u8, u16, u8);
struct S2(u8, u16, u8);

View file

@ -12,7 +12,8 @@
use std::mem::size_of;
// compile-flags: -Z fuel=foo=1
// (#55495: The --error-format is to sidestep an issue in our test harness)
// compile-flags: --error-format human -Z fuel=foo=1
struct S1(u8, u16, u8);
struct S2(u8, u16, u8);

View file

@ -0,0 +1,40 @@
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub trait ScopeHandle<'scope> {}
// @has issue_54705/struct.ScopeFutureContents.html
// @has - '//*[@id="synthetic-implementations-list"]/*[@class="impl"]//*/code' "impl<'scope, S> \
// Send for ScopeFutureContents<'scope, S> where S: Sync"
//
// @has - '//*[@id="synthetic-implementations-list"]/*[@class="impl"]//*/code' "impl<'scope, S> \
// Sync for ScopeFutureContents<'scope, S> where S: Sync"
pub struct ScopeFutureContents<'scope, S>
where S: ScopeHandle<'scope>,
{
dummy: &'scope S,
this: Box<ScopeFuture<'scope, S>>,
}
struct ScopeFuture<'scope, S>
where S: ScopeHandle<'scope>,
{
contents: ScopeFutureContents<'scope, S>,
}
unsafe impl<'scope, S> Send for ScopeFuture<'scope, S>
where S: ScopeHandle<'scope>,
{}
unsafe impl<'scope, S> Sync for ScopeFuture<'scope, S>
where S: ScopeHandle<'scope>,
{}

View file

@ -2,7 +2,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/transmute-const.rs:15:1
|
LL | static FOO: bool = unsafe { mem::transmute(3u8) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3, but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3, but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior

View file

@ -17,39 +17,48 @@ enum Enum {
}
union TransmuteEnum {
a: &'static u8,
b: Enum,
out: Enum,
}
// A pointer is guaranteed non-null
const BAD_ENUM: Enum = unsafe { TransmuteEnum { a: &1 }.b };
const BAD_ENUM: Enum = unsafe { TransmuteEnum { a: &1 }.out };
//~^ ERROR is undefined behavior
// Invalid enum discriminant
// (Potentially) invalid enum discriminant
#[repr(usize)]
#[derive(Copy, Clone)]
enum Enum2 {
A = 2,
}
#[repr(transparent)]
#[derive(Copy, Clone)]
struct Wrap<T>(T);
union TransmuteEnum2 {
a: usize,
b: Enum2,
c: (),
in1: usize,
in2: &'static u8,
in3: (),
out1: Enum2,
out2: Wrap<Enum2>, // something wrapping the enum so that we test layout first, not enum
}
const BAD_ENUM2 : Enum2 = unsafe { TransmuteEnum2 { a: 0 }.b };
const BAD_ENUM2: Enum2 = unsafe { TransmuteEnum2 { in1: 0 }.out1 };
//~^ ERROR is undefined behavior
const BAD_ENUM3: Enum2 = unsafe { TransmuteEnum2 { in2: &0 }.out1 };
//~^ ERROR is undefined behavior
const BAD_ENUM4: Wrap<Enum2> = unsafe { TransmuteEnum2 { in2: &0 }.out2 };
//~^ ERROR is undefined behavior
// Undef enum discriminant. In an arry to avoid `Scalar` layout.
const BAD_ENUM3 : [Enum2; 2] = [unsafe { TransmuteEnum2 { c: () }.b }; 2];
const BAD_ENUM_UNDEF: [Enum2; 2] = [unsafe { TransmuteEnum2 { in3: () }.out1 }; 2];
//~^ ERROR is undefined behavior
// Invalid enum field content (mostly to test printing of apths for enum tuple
// Invalid enum field content (mostly to test printing of paths for enum tuple
// variants and tuples).
union TransmuteChar {
a: u32,
b: char,
}
// Need to create something which does not clash with enum layout optimizations.
const BAD_ENUM_CHAR : Option<(char, char)> = Some(('x', unsafe { TransmuteChar { a: !0 }.b }));
const BAD_ENUM_CHAR: Option<(char, char)> = Some(('x', unsafe { TransmuteChar { a: !0 }.b }));
//~^ ERROR is undefined behavior
fn main() {

View file

@ -1,35 +1,51 @@
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:24:1
|
LL | const BAD_ENUM: Enum = unsafe { TransmuteEnum { a: &1 }.b };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a pointer, but expected a valid enum discriminant
LL | const BAD_ENUM: Enum = unsafe { TransmuteEnum { a: &1 }.out };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a pointer, but expected a valid enum discriminant
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:38:1
--> $DIR/ub-enum.rs:43:1
|
LL | const BAD_ENUM2 : Enum2 = unsafe { TransmuteEnum2 { a: 0 }.b };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0, but expected a valid enum discriminant
LL | const BAD_ENUM2: Enum2 = unsafe { TransmuteEnum2 { in1: 0 }.out1 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0, but expected a valid enum discriminant
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:42:1
--> $DIR/ub-enum.rs:45:1
|
LL | const BAD_ENUM3 : [Enum2; 2] = [unsafe { TransmuteEnum2 { c: () }.b }; 2];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attempted to read undefined bytes
LL | const BAD_ENUM3: Enum2 = unsafe { TransmuteEnum2 { in2: &0 }.out1 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a pointer, but expected a valid enum discriminant
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:52:1
--> $DIR/ub-enum.rs:47:1
|
LL | const BAD_ENUM_CHAR : Option<(char, char)> = Some(('x', unsafe { TransmuteChar { a: !0 }.b }));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 4294967295 at .Some.0.1, but expected something in the range 0..=1114111
LL | const BAD_ENUM4: Wrap<Enum2> = unsafe { TransmuteEnum2 { in2: &0 }.out2 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a pointer, but expected something that cannot possibly fail to be in the range 2..=2
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error: aborting due to 4 previous errors
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:51:1
|
LL | const BAD_ENUM_UNDEF: [Enum2; 2] = [unsafe { TransmuteEnum2 { in3: () }.out1 }; 2];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attempted to read undefined bytes
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-enum.rs:61:1
|
LL | const BAD_ENUM_CHAR: Option<(char, char)> = Some(('x', unsafe { TransmuteChar { a: !0 }.b }));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 4294967295 at .Some.0.1, but expected something less or equal to 1114111
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error: aborting due to 6 previous errors
For more information about this error, try `rustc --explain E0080`.

View file

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(const_transmute)]
#![feature(rustc_attrs, const_transmute)]
#![allow(const_err)] // make sure we cannot allow away the errors tested here
use std::mem;
@ -23,4 +23,18 @@ const NULL_U8: NonZeroU8 = unsafe { mem::transmute(0u8) };
const NULL_USIZE: NonZeroUsize = unsafe { mem::transmute(0usize) };
//~^ ERROR it is undefined behavior to use this value
// Also test other uses of rustc_layout_scalar_valid_range_start
#[rustc_layout_scalar_valid_range_start(10)]
#[rustc_layout_scalar_valid_range_end(30)]
struct RestrictedRange1(u32);
const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) };
//~^ ERROR it is undefined behavior to use this value
#[rustc_layout_scalar_valid_range_start(30)]
#[rustc_layout_scalar_valid_range_end(10)]
struct RestrictedRange2(u32);
const BAD_RANGE2: RestrictedRange2 = unsafe { RestrictedRange2(20) };
//~^ ERROR it is undefined behavior to use this value
fn main() {}

View file

@ -22,6 +22,22 @@ LL | const NULL_USIZE: NonZeroUsize = unsafe { mem::transmute(0usize) };
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error: aborting due to 3 previous errors
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-nonnull.rs:31:1
|
LL | const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 42, but expected something in the range 10..=30
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error[E0080]: it is undefined behavior to use this value
--> $DIR/ub-nonnull.rs:37:1
|
LL | const BAD_RANGE2: RestrictedRange2 = unsafe { RestrictedRange2(20) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 20, but expected something less or equal to 10, or greater or equal to 30
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
error: aborting due to 5 previous errors
For more information about this error, try `rustc --explain E0080`.

View file

@ -66,7 +66,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/union-ub-fat-ptr.rs:117:1
|
LL | const G: &Trait = &unsafe { BoolTransmute { val: 3 }.bl };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.<dyn-downcast>, but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.<dyn-downcast>, but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
@ -74,7 +74,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/union-ub-fat-ptr.rs:121:1
|
LL | const H: &[bool] = &[unsafe { BoolTransmute { val: 3 }.bl }];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>[0], but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>[0], but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
@ -82,7 +82,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/union-ub-fat-ptr.rs:127:1
|
LL | const I2: &MySliceBool = &MySlice(unsafe { BoolTransmute { val: 3 }.bl }, [false]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.0, but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.0, but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
@ -90,7 +90,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/union-ub-fat-ptr.rs:130:1
|
LL | const I3: &MySliceBool = &MySlice(true, [unsafe { BoolTransmute { val: 3 }.bl }]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.1[0], but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .<deref>.1[0], but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior

View file

@ -2,7 +2,7 @@ error[E0080]: it is undefined behavior to use this value
--> $DIR/union-ub.rs:38:1
|
LL | const BAD_BOOL: bool = unsafe { DummyUnion { u8: 42 }.bool};
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 42, but expected something in the range 0..=1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 42, but expected something less or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior

View file

@ -11,4 +11,8 @@
#[repr(simd)] //~ error: SIMD types are experimental
struct Foo(u64, u64);
#[repr(C)]
#[repr(simd)] //~ error: SIMD types are experimental
struct Bar(u64, u64);
fn main() {}

View file

@ -6,6 +6,14 @@ LL | #[repr(simd)] //~ error: SIMD types are experimental
|
= help: add #![feature(repr_simd)] to the crate attributes to enable
error: aborting due to previous error
error[E0658]: SIMD types are experimental and possibly buggy (see issue #27731)
--> $DIR/feature-gate-repr-simd.rs:15:1
|
LL | #[repr(simd)] //~ error: SIMD types are experimental
| ^^^^^^^^^^^^^
|
= help: add #![feature(repr_simd)] to the crate attributes to enable
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0658`.

View file

@ -11,4 +11,8 @@
#[repr(packed(1))] //~ error: the `#[repr(packed(n))]` attribute is experimental
struct Foo(u64);
#[repr(C)]
#[repr(packed(1))] //~ error: the `#[repr(packed(n))]` attribute is experimental
struct Bar(u64);
fn main() {}

View file

@ -6,6 +6,14 @@ LL | #[repr(packed(1))] //~ error: the `#[repr(packed(n))]` attribute is experim
|
= help: add #![feature(repr_packed)] to the crate attributes to enable
error: aborting due to previous error
error[E0658]: the `#[repr(packed(n))]` attribute is experimental (see issue #33158)
--> $DIR/feature-gate-repr_packed.rs:15:1
|
LL | #[repr(packed(1))] //~ error: the `#[repr(packed(n))]` attribute is experimental
| ^^^^^^^^^^^^^^^^^^
|
= help: add #![feature(repr_packed)] to the crate attributes to enable
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0658`.

View file

@ -0,0 +1,17 @@
// compile-pass
#![crate_type = "lib"]
#![feature(linkage)]
// MergeFunctions will merge these via an anonymous internal
// backing function, which must be named if ThinLTO buffers are used
#[linkage = "weak"]
pub fn fn1(a: u32, b: u32, c: u32) -> u32 {
a + b + c
}
#[linkage = "weak"]
pub fn fn2(a: u32, b: u32, c: u32) -> u32 {
a + b + c
}

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