// of a macro that is not vendored by Rust and included in the toolchain. // See https://github.com/rust-analyzer/rust-analyzer/issues/6038. <ins> // On certain platforms right now the "main modules" modules that are // documented don't compile (missing things in `libc` which is empty), // so just omit them with an empty module and add the "unstable" attribute. // Unix, linux, wasi and windows are handled a bit differently. </ins> #[cfg(all( doc, <del> not(any( </del> <ins> any( </ins> all(target_arch = "wasm32", not(target_os = "wasi")), all(target_vendor = "fortanix", target_env = "sgx") <del> )) </del> <ins> ) </ins> ))] <del> #[path = "."] mod doc { // When documenting std we want to show the `unix`, `windows`, `linux` and `wasi` // modules as these are the "main modules" that are used across platforms, // so these modules are enabled when `cfg(doc)` is set. // This should help show platform-specific functionality in a hopefully cross-platform // way in the documentation. pub mod unix; pub mod linux; pub mod wasi; pub mod windows; } </del> <ins> #[unstable(issue = "none", feature = "std_internals")] pub mod unix {} </ins> #[cfg(all( doc, any(


None); // If the item has the name of a field, give a help note <del> if let (&ty::TyStruct(did, _), Some(_)) = (&rcvr_ty.sty, rcvr_expr) { </del> <ins> if let (&ty::TyStruct(did, substs), Some(expr)) = (&rcvr_ty.sty, rcvr_expr) { </ins> let fields = ty::lookup_struct_fields(cx, did); <del> if fields.iter().any(|f| f.name == item_name) { cx.sess.span_note(span, &format!("use `(s.{0})(...)` if you meant to call the  function stored in the `{0}` field", item_name)); </del> <ins> if let Some(field) = fields.iter().find(|f| f.name == item_name) { let expr_string = match cx.sess.codemap().span_to_snippet(expr.span) { Ok(expr_string) => expr_string, _ => "s".into() // Default to a generic placeholder for the // expression when we can't generate a string // snippet }; let span_stored_function = || { cx.sess.span_note(span, &format!("use `({0}.{1})(...)` if you meant to call  the function stored in the `{1}` field", expr_string, item_name)); }; let span_did_you_mean = || { cx.sess.span_note(span, &format!("did you mean to write `{0}.{1}`?", expr_string, item_name)); }; // Determine if the field can be used as a function in some way let field_ty = ty::lookup_field_type(cx, did, field.id, substs); if let Ok(fn_once_trait_did) = cx.lang_items.require(FnOnceTraitLangItem) { let infcx = fcx.infcx(); infcx.probe(|_| { let fn_once_substs = Substs::new_trait(vec![infcx.next_ty_var()], Vec::new(), field_ty); let trait_ref = ty::TraitRef::new(fn_once_trait_did, cx.mk_substs(fn_once_substs)); let poly_trait_ref = trait_ref.to_poly_trait_ref(); let obligation = Obligation::misc(span, fcx.body_id, poly_trait_ref.as_predicate()); let mut selcx = SelectionContext::new(infcx, fcx); if selcx.evaluate_obligation(&obligation) { span_stored_function(); } else { span_did_you_mean(); } }); } else { match field_ty.sty { // fallback to matching a closure or function pointer ty::TyClosure(..) | ty::TyBareFn(..) => span_stored_function(), _ => span_did_you_mean(), } } </ins> } }


debug!("overloaded_deref_ty({:?})", ty); let tcx = self.infcx.tcx; <ins> if ty.references_error() { return None; } </ins> // <ty as Deref> let trait_ref = ty::TraitRef::new(tcx, tcx.lang_items().deref_trait()?, [ty]); let cause = traits::ObligationCause::misc(self.span, self.body_id);


/// impl Gadget { ///     /// Construct a reference counted Gadget. ///     fn new() -> Arc<Self> { <del> ///         Arc::new_cyclic(|me| Gadget { me: me.clone() }) </del> <ins> ///         // `me` is a `Weak<Gadget>` pointing at the new allocation of the ///         // `Arc` we're constructing. ///         Arc::new_cyclic(|me| { ///             // Create the actual struct here. ///             Gadget { me: me.clone() } ///         }) </ins> ///     } /// ///     /// Return a reference counted pointer to Self.


<ins> // check-pass pub struct Bar<'a>(&'a Self) where Self: ; fn main() {} </ins>


fn f() -> bool { let c = false; <del> if(c) { </del> <ins> if(c) { //~ ERROR unnecessary parentheses </ins> println!("next"); } <del> if (c){ </del> <ins> if (c){ //~ ERROR unnecessary parentheses </ins> println!("prev"); } while (false && true){ <del> if (c) { </del> <ins> if (c) { //~ ERROR unnecessary parentheses </ins> println!("norm"); } } <del> while(true && false) { for _ in (0 .. 3){ </del> <ins> while(true && false) { //~ ERROR unnecessary parentheses for _ in (0 .. 3){ //~ ERROR unnecessary parentheses </ins> println!("e~") } } <del> for _ in (0 .. 3) { while (true && false) { </del> <ins> for _ in (0 .. 3) { //~ ERROR unnecessary parentheses while (true && false) { //~ ERROR unnecessary parentheses </ins> println!("e~") } }


<ins> // 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. // ignore-cloudabi no processes // ignore-emscripten no processes use std::io::ErrorKind; use std::process::Command; fn main() { assert_eq!(Command::new("nonexistent") .spawn() .unwrap_err() .kind(), ErrorKind::NotFound); } </ins>


} match kind { AstFragmentKind::Pat if macro_ident.name == sym::vec => { <del> let mut suggestion = None; if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) { if let Some(bang) = code.find('!') { suggestion = Some(code[bang + 1..].to_string()); } } if let Some(suggestion) = suggestion { e.span_suggestion( site_span, "use a slice pattern here instead", suggestion, Applicability::MachineApplicable, ); } else { e.span_label( site_span, "use a slice pattern here instead", ); } e.help("for more information, see https://doc.rust-lang.org/edition-guide/ rust-2018/slice-patterns.html"); </del> <ins> suggest_slice_pat(&mut e, site_span, parser); </ins> } _ => annotate_err_with_kind(&mut e, kind, site_span), };


debug!("region_bound: {:?}", region_bound); <del> ty::sort_bounds_list(&mut projection_bounds); ty::ExistentialBounds { region_bound: region_bound, builtin_bounds: builtin_bounds, projection_bounds: projection_bounds, } </del> <ins> ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds) </ins> } /// Given the bounds on an object, determines what single region bound


x => tcx.ty_error_with_message( DUMMY_SP, <del> &format!("unexpected const parent in type_of_def_id(): {:?}", x), </del> <ins> &format!("unexpected const parent in type_of(): {:?}", x), </ins> ), } }


<ins> // aux-build:issue-69725.rs extern crate issue_69725; use issue_69725::Struct; fn crash<A>() { let _ = Struct::<A>::new().clone(); //~^ ERROR: no method named `clone` found } fn main() {} </ins>


use core::mem::*; <ins> #[cfg(panic = "unwind")] </ins> use std::rc::Rc; #[test]


}).collect::<Result<Vec<_>, _>>() }).collect::<Result<Vec<_>, _>>()?; <del> let (inh_first, inh_second) = { let mut inh_variants = (0..variants.len()).filter(|&v| { variants[v].iter().all(|f| f.abi != Abi::Uninhabited) }); (inh_variants.next(), inh_variants.next()) }; if inh_first.is_none() { // Uninhabited because it has no variants, or only uninhabited ones. return Ok(tcx.intern_layout(LayoutDetails::uninhabited(0))); } </del> if def.is_union() { let packed = def.repr.packed(); if packed && def.repr.align > 0 {


<ins> error: expected at least one digit in exponent --> $DIR/issue-104390.rs:1:27 | LL | fn f1() -> impl Sized { & 2E } |                           ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:2:28 | LL | fn f2() -> impl Sized { && 2E } |                            ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:3:29 | LL | fn f3() -> impl Sized { &'a 2E } |                             ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:5:34 | LL | fn f4() -> impl Sized { &'static 2E } |                                  ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:7:28 | LL | fn f5() -> impl Sized { *& 2E } |                            ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:8:29 | LL | fn f6() -> impl Sized { &'_ 2E } |                             ^^ error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:3:25 | LL | fn f3() -> impl Sized { &'a 2E } |                         ^--^^^ |                          | |                          annotated with lifetime here |                          help: remove the lifetime annotation error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:5:25 | LL | fn f4() -> impl Sized { &'static 2E } |                         ^-------^^^ |                          | |                          annotated with lifetime here |                          help: remove the lifetime annotation error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:8:25 | LL | fn f6() -> impl Sized { &'_ 2E } |                         ^--^^^ |                          | |                          annotated with lifetime here |                          help: remove the lifetime annotation error: aborting due to 9 previous errors </ins>


} if target.contains("arm") && !target.contains("ios") { <ins> // (At least) udivsi3.S is broken for Thumb 1 which our gcc uses by // default, we don't want Thumb 2 since it isn't supported on some // devices, so disable thumb entirely. // Upstream bug: https://bugs.llvm.org/show_bug.cgi?id=32492 cfg.define("__ARM_ARCH_ISA_THUMB", Some("0")); </ins> sources.extend(&["arm/aeabi_cdcmp.S", "arm/aeabi_cdcmpeq_check_nan.c", "arm/aeabi_cfcmp.S",


<ins> error[E0080]: evaluation of `<A<()> as Foo<()>>::BAR` failed --> $DIR/issue-50814-2.rs:16:24 | LL |     const BAR: usize = [5, 6, 7][T::BOO]; |                        ^^^^^^^^^^^^^^^^^ index out of bounds: the length is 3 but the index is 42 note: erroneous constant encountered --> $DIR/issue-50814-2.rs:20:6 | LL |     &<A<T> as Foo<T>>::BAR |      ^^^^^^^^^^^^^^^^^^^^^ note: erroneous constant encountered --> $DIR/issue-50814-2.rs:20:5 | LL |     &<A<T> as Foo<T>>::BAR |     ^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. </ins>


} fn visit_ty(&mut self, ty: Ty<'tcx>) -> std::ops::ControlFlow<Self::BreakTy> { <del> if let ty::Alias(ty::Projection, alias_ty) = *ty.kind() && self.tcx.is_impl_trait_in_trait(alias_ty.def_id) && self.tcx.impl_trait_in_trait_parent_fn(alias_ty.def_id) == self.fn_def_id && self.seen.insert(alias_ty.def_id) </del> <ins> if let ty::Alias(ty::Projection, unshifted_alias_ty) = *ty.kind() && self.tcx.is_impl_trait_in_trait(unshifted_alias_ty.def_id) && self.tcx.impl_trait_in_trait_parent_fn(unshifted_alias_ty.def_id) == self.fn_def_id && self.seen.insert(unshifted_alias_ty.def_id) </ins> { // We have entered some binders as we've walked into the // bounds of the RPITIT. Shift these binders back out when // constructing the top-level projection predicate. <del> let alias_ty = self.tcx.fold_regions(alias_ty, |re, _| { </del> <ins> let shifted_alias_ty = self.tcx.fold_regions(unshifted_alias_ty, |re, depth| { </ins> if let ty::ReLateBound(index, bv) = re.kind() { <ins> if depth != ty::INNERMOST { return self.tcx.mk_re_error_with_message( DUMMY_SP, "we shouldn't walk non-predicate binders with `impl Trait`...", ); } </ins> self.tcx.mk_re_late_bound(index.shifted_out_to_binder(self.depth), bv) } else { re


a: ty::Region<'tcx>, bound: VerifyBound<'tcx>, ) { <ins> if let ty::ReEmpty = a { return; } </ins> let type_test = self.verify_to_type_test(kind, a, bound); self.add_type_test(type_test); }


<ins> // Copyright 2014 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. // aux-build:issue-11908-2.rs // no-prefer-dynamic // ignore-android this test is incompatible with the android test runner // error-pattern: multiple rlib candidates for `collections` found // see comments in issue-11908-1 for what's going on here extern crate collections; fn main() {} </ins>


| help: change the delimiters to curly braces | <del> LL | macro_rules! abc{ؼ} |                 ^ ^ </del> <ins> LL | macro_rules! abc { /* items */ } |                  ^^^^^^^^^^^^^^^ </ins> help: add a semicolon | LL | macro_rules! abc(ؼ;


linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { <del> features: "+strict-align,+v6,+vfp2".to_string(), </del> <ins> features: "+strict-align,+v6,+vfp2,-d32".to_string(), </ins> abi_blacklist: super::arm_base::abi_blacklist(), target_mcount: "u{1}__gnu_mcount_nc".to_string(), .. base


# Gotta do some hackery to tell python about our custom OpenSSL build, but other # than that fairly normal. CFLAGS='-I /rustroot/include' LDFLAGS='-L /rustroot/lib -L /rustroot/lib64'  <del> hide_output ../Python-3.9.1/configure --prefix=/rustroot </del> <ins> hide_output ../Python-2.7.12/configure --prefix=/rustroot </ins> hide_output make -j10 hide_output make install cd .. rm -rf python-build <del> rm -rf Python-3.9.1 </del> <ins> rm -rf Python-2.7.12 </ins>


<ins> #![deny(unused_must_use)] fn foo() -> (Result<(), ()>, ()) { (Ok::<(), ()>(()), ()) } fn main() { (Ok::<(), ()>(()),); //~ ERROR unused `std::result::Result` (Ok::<(), ()>(()), 0, Ok::<(), ()>(()), 5); //~^ ERROR unused `std::result::Result` //~^^ ERROR unused `std::result::Result` foo(); //~ ERROR unused `std::result::Result` ((Err::<(), ()>(()), ()), ()); //~ ERROR unused `std::result::Result` } </ins>


// Not in interpret to make sure we do not use private implementation details <del> use std::borrow::{Borrow, Cow}; use std::collections::hash_map::Entry; use std::convert::TryInto; use std::error::Error; use std::fmt; use std::hash::Hash; use crate::interpret::eval_nullary_intrinsic; use rustc::hir::def::DefKind; use rustc::hir::def_id::DefId; </del> use rustc::mir; <del> use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef}; use rustc::traits::Reveal; use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, VariantIdx}; use rustc::ty::{self, subst::Subst, Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use syntax::{ source_map::{Span, DUMMY_SP}, symbol::Symbol, }; use crate::interpret::{ self, intern_const_alloc_recursive, snapshot, AllocId, Allocation, AssertMessage, ConstValue, GlobalId, ImmTy, Immediate, InterpCx, InterpErrorInfo, InterpResult, MPlaceTy, Machine, Memory, MemoryKind, OpTy, PlaceTy, Pointer, RawConst, RefTracking, Scalar, StackPopCleanup, }; /// Number of steps until the detector even starts doing anything. /// Also, a warning is shown to the user when this number is reached. const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000; /// The number of steps between loop detector snapshots. /// Should be a power of two for performance reasons. const DETECTOR_SNAPSHOT_PERIOD: isize = 256; /// The `InterpCx` is only meant to be used to do field and index projections into constants for /// `simd_shuffle` and const patterns in match arms. /// /// The function containing the `match` that is currently being analyzed may have generic bounds /// that inform us about the generic bounds of the constant. E.g., using an associated constant /// of a function's generic parameter will require knowledge about the bounds on the generic /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { debug!("mk_eval_cx: {:?}", param_env); InterpCx::new( tcx.at(span), param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics }, ) } fn op_to_const<'tcx>( ecx: &CompileTimeEvalContext<'_, 'tcx>, op: OpTy<'tcx>, ) -> &'tcx ty::Const<'tcx> { // We do not have value optimizations for everything. // Only scalars and slices, since they are very common. // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result // from scalar unions that are initialized with one of their zero sized variants. We could // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all // the usual cases of extracting e.g. a `usize`, without there being a real use case for the // `Undef` situation. let try_as_immediate = match op.layout.abi { layout::Abi::Scalar(..) => true, layout::Abi::ScalarPair(..) => match op.layout.ty.kind { ty::Ref(_, inner, _) => match inner.kind { ty::Slice(elem) => elem == ecx.tcx.types.u8, ty::Str => true, _ => false, }, _ => false, }, _ => false, }; let immediate = if try_as_immediate { Err(ecx.read_immediate(op).expect("normalization works on validated constants")) } else { // It is guaranteed that any non-slice scalar pair is actually ByRef here. // When we come back from raw const eval, we are always by-ref. The only way our op here is // by-val is if we are in const_field, i.e., if this is (a field of) something that we // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or // structs containing such. op.try_as_mplace() }; let val = match immediate { Ok(mplace) => { let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } // see comment on `let try_as_immediate` above Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x { ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s), ScalarMaybeUndef::Undef => { // When coming out of "normal CTFE", we'll always have an `Indirect` operand as // argument and we will not need this. The only way we can already have an // `Immediate` is when we are called from `const_field`, and that `Immediate` // comes from a constant so it can happen have `Undef`, because the indirect // memory that was read had undefined bytes. let mplace = op.assert_mem_place(); let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } }, Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => { let (data, start) = match a.not_undef().unwrap() { Scalar::Ptr(ptr) => { (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes()) } Scalar::Raw { .. } => ( ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])), 0, ), }; let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap(); let start = start.try_into().unwrap(); let len: usize = len.try_into().unwrap(); ConstValue::Slice { data, start, end: start + len } } }; ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty }) } // Returns a pointer to where the result lives fn eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, cid: GlobalId<'tcx>, body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); let tcx = ecx.tcx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id())); let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p)); trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom); // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't // make sense if the body is expecting nontrivial arguments. // (The alternative would be to use `eval_fn_call` with an args slice.) for arg in body.args_iter() { let decl = body.local_decls.get(arg).expect("arg missing from local_decls"); let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?; assert!(layout.is_zst()) } ecx.push_stack_frame( cid.instance, body.span, body, Some(ret.into()), StackPopCleanup::None { cleanup: false }, )?; // The main interpreter loop. ecx.run()?; // Intern the result intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?; debug!("eval_body_using_ecx done: {:?}", *ret); Ok(ret) } #[derive(Clone, Debug)] pub enum ConstEvalError { NeedsRfc(String), ConstAccessesStatic, } impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError { fn into(self) -> InterpErrorInfo<'tcx> { err_unsup!(Unsupported(self.to_string())).into() } } impl fmt::Display for ConstEvalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::ConstEvalError::*; match *self { NeedsRfc(ref msg) => { write!(f, ""{}" needs an rfc before being allowed inside constants", msg) } ConstAccessesStatic => write!(f, "constant accesses static"), } } } impl Error for ConstEvalError {} // Extra machine state for CTFE, and the Machine instance pub struct CompileTimeInterpreter<'mir, 'tcx> { /// When this value is negative, it indicates the number of interpreter /// steps *until* the loop detector is enabled. When it is positive, it is /// the number of steps after the detector has been enabled modulo the loop /// detector period. pub(super) steps_since_detector_enabled: isize, /// Extra state to detect loops. pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>, } #[derive(Copy, Clone, Debug)] pub struct MemoryExtra { /// Whether this machine may read from statics can_access_statics: bool, } impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> { fn new() -> Self { CompileTimeInterpreter { loop_detector: Default::default(), steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED, } } } impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> { #[inline(always)] fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool where K: Borrow<Q>, { FxHashMap::contains_key(self, k) } #[inline(always)] fn insert(&mut self, k: K, v: V) -> Option<V> { FxHashMap::insert(self, k, v) } #[inline(always)] fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, { FxHashMap::remove(self, k) } #[inline(always)] fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> { self.iter().filter_map(move |(k, v)| f(k, &*v)).collect() } #[inline(always)] fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> { match self.get(&k) { Some(v) => Ok(v), None => { vacant()?; bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading") } } } #[inline(always)] fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> { match self.entry(k) { Entry::Occupied(e) => Ok(e.into_mut()), Entry::Vacant(e) => { let v = vacant()?; Ok(e.insert(v)) } } } } crate type CompileTimeEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>; </del> <ins> use rustc::ty::layout::VariantIdx; use rustc::ty::{self, TyCtxt}; </ins> <del> impl interpret::MayLeak for ! { #[inline(always)] fn may_leak(self) -> bool { // `self` is uninhabited self } } impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> { type MemoryKinds = !; type PointerTag = (); type ExtraFnVal = !; type FrameExtra = (); type MemoryExtra = MemoryExtra; type AllocExtra = (); type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>; const STATIC_KIND: Option<!> = None; // no copying of statics allowed // We do not check for alignment to avoid having to carry an `Align` // in `ConstValue::ByRef`. const CHECK_ALIGN: bool = false; #[inline(always)] fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool { false // for now, we don't enforce validity } fn find_mir_or_eval_fn( ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option<mir::BasicBlock>, // unwinding is not supported in consts ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> { debug!("find_mir_or_eval_fn: {:?}", instance); // Only check non-glue functions if let ty::InstanceDef::Item(def_id) = instance.def { // Execution might have wandered off into other crates, so we cannot do a stability- // sensitive check here.  But we can at least rule out functions that are not const // at all. if ecx.tcx.is_const_fn_raw(def_id) { // If this function is a `const fn` then as an optimization we can query this // evaluation immediately. // // For the moment we only do this for functions which take no arguments // (or all arguments are ZSTs) so that we don't memoize too much. // // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot // perform this optimization on items tagged with it. let no_implicit_args = !instance.def.requires_caller_location(ecx.tcx()); if args.iter().all(|a| a.layout.is_zst()) && no_implicit_args { let gid = GlobalId { instance, promoted: None }; ecx.eval_const_fn_call(gid, ret)?; return Ok(None); } } else { // Some functions we support even if they are non-const -- but avoid testing // that for const fn!  We certainly do *not* want to actually call the fn // though, so be sure we return here. return if ecx.hook_panic_fn(instance, args, ret)? { Ok(None) } else { throw_unsup_format!("calling non-const function `{}`", instance) }; } } // This is a const fn. Call it. Ok(Some(match ecx.load_mir(instance.def, None) { Ok(body) => *body, Err(err) => { if let err_unsup!(NoMirFor(ref path)) = err.kind { return Err(ConstEvalError::NeedsRfc(format!( "calling extern function `{}`", path )) .into()); } return Err(err); } })) } fn call_extra_fn( _ecx: &mut InterpCx<'mir, 'tcx, Self>, fn_val: !, _args: &[OpTy<'tcx>], _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { match fn_val {} } fn call_intrinsic( ecx: &mut InterpCx<'mir, 'tcx, Self>, span: Span, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { if ecx.emulate_intrinsic(span, instance, args, ret)? { return Ok(()); } // An intrinsic that we do not support let intrinsic_name = ecx.tcx.item_name(instance.def_id()); Err(ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()) } </del> <ins> use syntax::{source_map::DUMMY_SP, symbol::Symbol}; </ins> <del> fn assert_panic( ecx: &mut InterpCx<'mir, 'tcx, Self>, _span: Span, msg: &AssertMessage<'tcx>, _unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { use rustc::mir::interpret::PanicInfo::*; Err(match msg { BoundsCheck { ref len, ref index } => { let len = ecx .read_immediate(ecx.eval_operand(len, None)?) .expect("can't eval len") .to_scalar()? .to_machine_usize(&*ecx)?; let index = ecx .read_immediate(ecx.eval_operand(index, None)?) .expect("can't eval index") .to_scalar()? .to_machine_usize(&*ecx)?; err_panic!(BoundsCheck { len, index }) } Overflow(op) => err_panic!(Overflow(*op)), OverflowNeg => err_panic!(OverflowNeg), DivisionByZero => err_panic!(DivisionByZero), RemainderByZero => err_panic!(RemainderByZero), ResumedAfterReturn(generator_kind) => err_panic!(ResumedAfterReturn(*generator_kind)), ResumedAfterPanic(generator_kind) => err_panic!(ResumedAfterPanic(*generator_kind)), Panic { .. } => bug!("`Panic` variant cannot occur in MIR"), } .into()) } </del> <ins> use crate::interpret::{intern_const_alloc_recursive, ConstValue, InterpCx}; </ins> <del> fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> { Err(ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into()) } </del> <ins> mod error; mod eval_queries; </ins> <del> fn binary_ptr_op( _ecx: &InterpCx<'mir, 'tcx, Self>, _bin_op: mir::BinOp, _left: ImmTy<'tcx>, _right: ImmTy<'tcx>, ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> { Err(ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into()) } fn find_foreign_static( _tcx: TyCtxt<'tcx>, _def_id: DefId, ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> { throw_unsup!(ReadForeignStatic) } #[inline(always)] fn init_allocation_extra<'b>( _memory_extra: &MemoryExtra, _id: AllocId, alloc: Cow<'b, Allocation>, _kind: Option<MemoryKind<!>>, ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) { // We do not use a tag so we can just cheaply forward the allocation (alloc, ()) } #[inline(always)] fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag { () } fn box_alloc( _ecx: &mut InterpCx<'mir, 'tcx, Self>, _dest: PlaceTy<'tcx>, ) -> InterpResult<'tcx> { Err(ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into()) } fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { { let steps = &mut ecx.machine.steps_since_detector_enabled; *steps += 1; if *steps < 0 { return Ok(()); } *steps %= DETECTOR_SNAPSHOT_PERIOD; if *steps != 0 { return Ok(()); } } let span = ecx.frame().span; ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..]) } #[inline(always)] fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { Ok(()) } fn before_access_static( memory_extra: &MemoryExtra, _allocation: &Allocation, ) -> InterpResult<'tcx> { if memory_extra.can_access_statics { Ok(()) } else { Err(ConstEvalError::ConstAccessesStatic.into()) } } } </del> <ins> pub use error::*; pub use eval_queries::*; </ins> /// Extracts a field of a (variant of a) const. // this function uses `unwrap` copiously, because an already validated constant must have valid // fields and can thus never fail outside of compiler bugs <del> pub fn const_field<'tcx>( </del> <ins> pub(crate) fn const_field<'tcx>( </ins> tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, variant: Option<VariantIdx>,


return None; } <del> pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> { // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures. match self.hir().get_by_def_id(scope_def_id) { Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {} Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {} Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {} Node::Expr(&hir::Expr { kind: ExprKind::Closure { .. }, .. }) => {} _ => return None, } let ret_ty = self.type_of(scope_def_id).instantiate_identity(); match ret_ty.kind() { ty::FnDef(_, _) => { let sig = ret_ty.fn_sig(self); let output = self.erase_late_bound_regions(sig.output()); output.is_impl_trait().then(|| { let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id); let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap(); (output, fn_decl.output.span()) }) } _ => None, } } </del> /// Checks if the bound region is in Impl Item. pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool { let container_id = self.parent(suitable_region_binding_scope.to_def_id());


self.parent_cfg = new_cfg.clone(); item.cfg = new_cfg; <ins> let old_parent = if let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) { self.parent.replace(def_id) } else { self.parent.take() }; </ins> let result = self.fold_item_recur(item); self.parent_cfg = old_parent_cfg; <ins> self.parent = old_parent; </ins> Some(result) }


} PatKind::Binding { name, mutability, mode, var, ty, ref subpattern, is_primary: _ } => { <del> candidate.bindings.push(Binding { name, mutability, span: match_pair.pattern.span, source: match_pair.place.clone().into_place(self.tcx, self.typeck_results), var_id: var, var_ty: ty, binding_mode: mode, }); </del> <ins> if let Ok(place_resolved) = match_pair.place.clone().try_upvars_resolved(self.tcx, self.typeck_results) { candidate.bindings.push(Binding { name, mutability, span: match_pair.pattern.span, source: place_resolved.into_place(self.tcx, self.typeck_results), var_id: var, var_ty: ty, binding_mode: mode, }); } </ins> if let Some(subpattern) = subpattern.as_ref() { // this is the `x @ P` case; have to keep matching against `P` now


}; add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); <ins> // Special case for stage0, to make `rustup toolchain link` and `x dist --stage 0` // work for stage0-sysroot. We only do this if the stage0 compiler comes from beta, // and is not set to a custom path. if compiler.stage == 0 && builder .build .config .initial_rustc .starts_with(builder.out.join(&compiler.host.triple).join("stage0/bin")) { // Copy bin files from stage0/bin to stage0-sysroot/bin let sysroot = builder.out.join(&compiler.host.triple).join("stage0-sysroot"); let host = compiler.host.triple; let stage0_bin_dir = builder.out.join(&host).join("stage0/bin"); let sysroot_bin_dir = sysroot.join("bin"); t!(fs::create_dir_all(&sysroot_bin_dir)); builder.cp_r(&stage0_bin_dir, &sysroot_bin_dir); // Copy all *.so files from stage0/lib to stage0-sysroot/lib let stage0_lib_dir = builder.out.join(&host).join("stage0/lib"); if let Ok(files) = fs::read_dir(&stage0_lib_dir) { for file in files { let file = t!(file); let path = file.path(); if path.is_file() && is_dylib(&file.file_name().into_string().unwrap()) { builder.copy(&path, &sysroot.join("lib").join(path.file_name().unwrap())); } } } // Copy codegen-backends from stage0 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler); t!(fs::create_dir_all(&sysroot_codegen_backends)); let stage0_codegen_backends = builder .out .join(&host) .join("stage0/lib/rustlib") .join(&host) .join("codegen-backends"); builder.cp_r(&stage0_codegen_backends, &sysroot_codegen_backends); } </ins> } }


let source_map = self.tcx.sess.source_map(); let all_source_files = source_map.files(); <del> let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone(); </del> <ins> let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone(); </ins> let adapted = all_source_files.iter() .filter(|source_file| {


raise RuntimeError("failed to find config line for {}".format(key)) <del> for section_key in config: section_config = config[section_key] if section_key not in sections: raise RuntimeError("config key {} not in sections".format(section_key)) </del> <ins> def configure_top_level_key(lines, top_level_key, value): for i, line in enumerate(lines): if line.startswith('#' + top_level_key + ' = ') or line.startswith(top_level_key + ' = '): lines[i] = "{} = {}".format(top_level_key, value) return </ins> <del> if section_key == 'target': </del> <ins> raise RuntimeError("failed to find config line for {}".format(top_level_key)) for section_key, section_config in config.items(): if section_key not in sections and section_key not in top_level_keys: raise RuntimeError("config key {} not in sections or top_level_keys".format(section_key)) if section_key in top_level_keys: configure_top_level_key(sections[None], section_key, section_config) elif  section_key == 'target': </ins> for target in section_config: configure_section(targets[target], section_config[target]) else:


unsafe { self.__iterator_get_unchecked(index) } } } <ins> trait SpecFold: Iterator { fn spec_fold<B, F>(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B; } impl<A: Iterator, B: Iterator> SpecFold for Zip<A, B> { // Adapted from default impl from the Iterator trait #[inline] default fn spec_fold<Acc, F>(mut self, init: Acc, mut f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; while let Some(x) = ZipImpl::next(&mut self) { accum = f(accum, x); } accum } } impl<A: TrustedLen, B: TrustedLen> SpecFold for Zip<A, B> { #[inline] fn spec_fold<Acc, F>(mut self, init: Acc, mut f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; loop { let (upper, more) = if let Some(upper) = ZipImpl::size_hint(&self).1 { (upper, false) } else { // Per TrustedLen contract a None upper bound means more than usize::MAX items (usize::MAX, true) }; for _ in 0..upper { let pair = // SAFETY: TrustedLen guarantees that at least `upper` many items are available // therefore we know they can't be None unsafe { (self.a.next().unwrap_unchecked(), self.b.next().unwrap_unchecked()) }; accum = f(accum, pair); } if !more { break; } } accum } } </ins>


Some(field) => (field.ident.span, field.span), None => (base.span, base.span), }; <del> self.check_field(use_ctxt, span, adt, variant_field); </del> <ins> self.check_field(use_ctxt, span, adt, variant_field, true); </ins> } } else { for field in fields { let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.tables); <del> self.check_field(use_ctxt, field.span, adt, &variant.fields[index]); </del> <ins> self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); </ins> } } }


}).collect::<Result<Vec<_>, _>>()?; let offset = st[i].fields.offset(field_index) + offset; <del> let LayoutDetails { size, mut align, .. } = st[i]; </del> <ins> let LayoutDetails { mut size, mut align, .. } = st[i]; </ins> let mut niche_align = niche.value.align(dl); let abi = if offset.bytes() == 0 && niche.value.size(dl) == size {


<del> Subproject commit 3abdd2f1ced4cf3a44c7de88c5e39b3bb5037c4d </del> <ins> Subproject commit 86b8643586aa39f36fb7a02e98c8d64d31415e70 </ins>


self.register_unsize_obligations(span, &**u) } ty::UnsizeVtable(ref ty_trait, self_ty) => { <ins> // If the type is `Foo+'a`, ensures that the type // being cast to `Foo+'a` implements `Foo`: </ins> vtable2::register_object_cast_obligations(self, span, ty_trait, self_ty); <ins> // If the type is `Foo+'a`, ensures that the type // being cast to `Foo+'a` outlives `'a`: let origin = infer::RelateObjectBound(span); self.register_region_obligation(origin, self_ty, ty_trait.bounds.region_bound); </ins> } } }


} pub fn create_sysroot(build: &Build, compiler: &Compiler) { <del> // nothing to do in stage0 if compiler.stage == 0 { return } </del> let sysroot = build.sysroot(compiler); let _ = fs::remove_dir_all(&sysroot); t!(fs::create_dir_all(&sysroot));


if (!innerToggle) { return; } <del> let sectionIsCollapsed = false; </del> if (hasClass(innerToggle, "will-expand")) { <del> removeClass(innerToggle, "will-expand"); onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => { if (!hasClass(e, "type-contents-toggle")) { e.open = true; } }); innerToggle.title = "collapse all docs"; </del> <ins> expandAllDocs(); </ins> } else { <del> addClass(innerToggle, "will-expand"); onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => { if (e.parentNode.id !== "implementations-list" || (!hasClass(e, "implementors-toggle") && !hasClass(e, "type-contents-toggle")) ) { e.open = false; } }); sectionIsCollapsed = true; innerToggle.title = "expand all docs"; </del> <ins> collapseAllDocs(); </ins> } <del> innerToggle.children[0].innerText = labelForToggleButton(sectionIsCollapsed); </del> } (function() {


<ins> // Copyright 2014 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. // ignore-tidy-linelength #![deny(deprecated)] extern crate url; fn main() { let _ = url::Url::parse("http://example.com"); //~^ ERROR use of deprecated item: This is being removed. Use rust-url instead. http://servo.github.io/rust-url/ } </ins>


<ins> // This is a separate test from `issue-66693.rs` because array lengths are evaluated // in a separate stage before `const`s and `statics` and so the error below is hit and // the compiler exits before generating errors for the others. #![feature(const_panic)] fn main() { let _ = [0i32; panic!(2f32)]; //~^ ERROR: argument to `panic!()` in a const context must have type `&str` // ensure that conforming panics are handled correctly let _ = [false; panic!()]; //~^ ERROR: evaluation of constant value failed // typechecking halts before getting to this one let _ = ['a', panic!("panic in array len")]; } </ins>


mod remove_unneeded_drops; mod remove_zsts; mod required_consts; <ins> mod reveal_all; </ins> mod separate_const_switch; mod shim; mod simplify;


//~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out <ins> // capture fault with zero value const _: u32 = unsafe { std::intrinsics::ctlz_nonzero(0) }; //~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out const _: u32 = unsafe { std::intrinsics::cttz_nonzero(0) }; //~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out </ins> fn main() {}


<ins> error: `?` may only modify trait bounds, not lifetime bounds --> $DIR/issue-68890.rs:1:11 | LL | enum e{A((?'a a+?+l))} |           ^ error: expected one of `)`, `+`, or `,`, found `a` --> $DIR/issue-68890.rs:1:15 | LL | enum e{A((?'a a+?+l))} |               ^ expected one of `)`, `+`, or `,` error: expected trait bound, not lifetime bound --> $DIR/issue-68890.rs:1:11 | LL | enum e{A((?'a a+?+l))} |           ^^^ error: aborting due to 3 previous errors </ins>


<ins> // Regression test for #65553 // // `D::Error:` is lowered to `D::Error: ReEmpty` - check that we don't ICE in // NLL for the unexpected region. // check-pass trait Deserializer { type Error; } fn d1<D: Deserializer>() where D::Error: {} fn d2<D: Deserializer>() { d1::<D>(); } fn main() {} </ins>


let _ = StableTupleStruct (1); let _ = FrozenTupleStruct (1); let _ = LockedTupleStruct (1); <ins> // At the moment, the following just checks that the stability // level of expanded code does not trigger the // lint. Eventually, we will want to lint the contents of the // macro in the module *defining* it. Also, stability levels // on macros themselves are not yet linted. macro_test!(); </ins> } fn test_method_param<F: Trait>(foo: F) {


pat_src: PatternSource, bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, ) { <ins> // We walk the pattern before declaring the pattern's inner bindings, // so that we avoid resolving a literal expression to a binding defined // by the pattern. visit::walk_pat(self, pat); </ins> self.resolve_pattern_inner(pat, pat_src, bindings); // This has to happen *after* we determine which pat_idents are variants: self.check_consistent_bindings_top(pat); <del> visit::walk_pat(self, pat); </del> } /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.


} fn main() { <del> print_x(X);  //~error this function takes 2 parameters but 1 parameter was supplied //~^ NOTE the following parameter types were expected: &Foo<Item=bool>, &str </del> <ins> print_x(X); //~^ ERROR this function takes 2 parameters but 1 parameter was supplied //~| NOTE the following parameter types were expected: &Foo<Item=bool>, &str //~| NOTE expected 2 parameters </ins> }


}; let last_type_ascription_set = self.last_type_ascription.is_some(); <del> match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) { (true, None) => { self.last_type_ascription = None; // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071 return Ok(lhs); } (false, _) => {} // continue parsing the expression // An exhaustive check is done in the following block, but these are checked first // because they *are* ambiguous but also reasonable looking incorrect syntax, so we // want to keep their span info to improve diagnostics in these cases in a later stage. (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` (true, Some(AssocOp::Subtract)) | // `{ 42 } -5` (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) (true, Some(AssocOp::Add)) // `{ 42 } + 42 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect: // `if x { a } else { b } && if y { c } else { d }` if !self.look_ahead(1, |t| t.is_reserved_ident()) => { self.last_type_ascription = None; // These cases are ambiguous and can't be identified in the parser alone let sp = self.sess.source_map().start_point(self.token.span); self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); return Ok(lhs); } (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => { self.last_type_ascription = None; return Ok(lhs); } (true, Some(_)) => { // We've found an expression that would be parsed as a statement, but the next // token implies this should be parsed as an expression. // For example: `if let Some(x) = x { x } else { 0 } / 2` let mut err = self.struct_span_err(self.token.span, &format!( "expected expression, found `{}`", pprust::token_to_string(&self.token), )); err.span_label(self.token.span, "expected expression"); self.sess.expr_parentheses_needed( &mut err, lhs.span, Some(pprust::expr_to_string(&lhs), )); err.emit(); } </del> <ins> if !self.should_continue_as_assoc_expr(&lhs) { self.last_type_ascription = None; return Ok(lhs); </ins> } <del> self.expected_tokens.push(TokenType::Operator); while let Some(op) = AssocOp::from_token(&self.token) { </del> <ins> self.expected_tokens.push(TokenType::Operator); while let Some(op) = self.check_assoc_op() { </ins> // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what // it refers to. Interpolated identifiers are unwrapped early and never show up here // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process


<ins> // run-rustfix use std::any::Any; fn foo<T: Any>(value: &T) -> Box<dyn Any + '_> { Box::new(value) as Box<dyn Any> //~^ ERROR lifetime may not live long enough } fn main() { let _ = foo(&5); } </ins>


<ins> // check-pass #![deny(unused_lifetimes)] trait Trait2 { type As; } // we should not warn about an unused lifetime about code generated from this proc macro here #[derive(Clone)] struct ShimMethod4<T: Trait2 + 'static>(pub &'static dyn for<'s> Fn(&'s mut T::As)); pub fn main() {} </ins>


<ins> error: expected trait bound, found `impl Trait` type --> $DIR/issue-102182-impl-trait-recover.rs:1:11 | LL | fn foo<T: impl Trait>() {} |           ^^^^^^^^^^ not a trait | help: use the trait bounds directly | LL - fn foo<T: impl Trait>() {} LL + fn foo<T: Trait>() {} | error: aborting due to previous error </ins>


/// # Examples /// /// ```no_run <del> /// #![feature(buffered_io_capacity)] </del> /// use std::io::{BufReader, BufRead}; /// use std::fs::File; ///


- it is bound as an associated type, e.g. `impl<T, U> SomeTrait for T where T: AnotherTrait<AssocType=U>` <ins> Any unconstrained lifetime parameter of an `impl` is not supported if the lifetime parameter is used by an associated type. </ins> ### Error example 1 Suppose we have a struct `Foo` and we would like to define some methods for it.


= help: the trait `Sized` is not implemented for `[u8]` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature <ins> help: consider borrowing here | LL |     let _foo: &[u8] = *foo; |               + </ins> error: aborting due to 3 previous errors


element_ty } None => { <ins> // Attempt to *shallowly* search for an impl which matches, // but has nested obligations which are unsatisfied. for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() { if let Some((_, index_ty, element_ty)) = self.find_and_report_unsatisfied_index_impl(expr.hir_id, base, base_t) { self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No); return element_ty; } } </ins> let mut err = type_error_struct!( self.tcx.sess, expr.span,


.map(|param| tcx.type_of(param.def_id)) // This is no generic parameter associated with the arg. This is // probably from an extra arg where one is not needed. <del> .unwrap_or(tcx.types.err) </del> <ins> .unwrap_or_else(|| { tcx.sess.delay_span_bug( DUMMY_SP, &format!( "missing generic parameter for `AnonConst`, parent {:?}", parent_node ), ); tcx.types.err }) </ins> } else { tcx.sess.delay_span_bug( DUMMY_SP,


LL | use V; |     ^ ambiguous name | <del> = note: ambiguous because of multiple potential import sources </del> <ins> = note: ambiguous because of multiple glob imports of a name in the same module </ins> note: `V` could refer to the variant imported here --> $DIR/issue-105069.rs:1:5 | LL | use self::A::*; |     ^^^^^^^^^^ <ins> = help: consider adding an explicit import of `V` to disambiguate </ins> note: `V` could also refer to the variant imported here --> $DIR/issue-105069.rs:3:5 | LL | use self::B::*; |     ^^^^^^^^^^ <ins> = help: consider adding an explicit import of `V` to disambiguate </ins> error: aborting due to previous error


// (We do this separately from the above so that when the setup actually // happens we get some output.) // We re-use the `cargo` from above. <del> cargo.arg("--env"); </del> <ins> cargo.arg("--print-sysroot"); </ins> // FIXME: Is there a way in which we can re-use the usual `run` helpers? let miri_sysroot = if builder.config.dry_run {


<ins> // ... continued from ./min-choice.rs // check-fail trait Cap<'a> {} impl<T> Cap<'_> for T {} fn type_test<'a, T: 'a>() -> &'a u8 { &0 } // Make sure we don't pick `'b`. fn test_b<'a, 'b, 'c, T>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, T: 'b, { type_test::<'_, T>() // This should pass if we pick 'b. //~^ ERROR the parameter type `T` may not live long enough } // Make sure we don't pick `'c`. fn test_c<'a, 'b, 'c, T>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, T: 'c, { type_test::<'_, T>() // This should pass if we pick 'c. //~^ ERROR the parameter type `T` may not live long enough } // We need to pick min_choice from `['b, 'c]`, but it's ambiguous which one to pick because // they're incomparable. fn test_ambiguous<'a, 'b, 'c>(s: &'a u8) -> impl Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, { s //~^ ERROR captures lifetime that does not appear in bounds } fn main() {} </ins>


let verbose = std::env::var("MIRI_VERBOSE") .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer")); <del> // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here; // just default to a straight-forward invocation for now: let mut cmd = Command::new("rustdoc"); </del> <ins> // phase_cargo_miri sets the RUSTDOC env var to ourselves, and puts a backup // of the old value into MIRI_ORIG_RUSTDOC. So that's what we have to invoke now. let rustdoc = env::var("MIRI_ORIG_RUSTDOC").unwrap_or("rustdoc".to_string()); let mut cmd = Command::new(rustdoc); </ins> let extern_flag = "--extern"; let runtool_flag = "--runtool";


// option. This file may not be copied, modified, or distributed // except according to those terms. <del> use prelude::*; use std::rand; use std::rand::Rng; use test::{Bencher, black_box}; pub fn insert_rand_n<M, I, R>(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut remove: R) where I: FnMut(&mut M, usize), R: FnMut(&mut M, usize), { // setup let mut rng = rand::weak_rng(); for _ in 0..n { insert(map, rng.gen::<usize>() % n); } // measure b.iter(|| { let k = rng.gen::<usize>() % n; insert(map, k); remove(map, k); }); black_box(map); </del> <ins> macro_rules! map_insert_rand_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use std::rand; use std::rand::Rng; use test::black_box; let n: usize = $n; let mut map = $map::new(); // setup let mut rng = rand::weak_rng(); for _ in 0..n { let i = rng.gen() % n; map.insert(i, i); } // measure b.iter(|| { let k = rng.gen() % n; map.insert(k, k); map.remove(&k); }); black_box(map); } ) </ins> } <del> pub fn insert_seq_n<M, I, R>(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut remove: R) where I: FnMut(&mut M, usize), R: FnMut(&mut M, usize), { // setup for i in 0..n { insert(map, i * 2); } // measure let mut i = 1; b.iter(|| { insert(map, i); remove(map, i); i = (i + 2) % n; }); black_box(map); </del> <ins> macro_rules! map_insert_seq_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup for i in 0..n { map.insert(i * 2, i * 2); } // measure let mut i = 1; b.iter(|| { map.insert(i, i); map.remove(&i); i = (i + 2) % n; }); black_box(map); } ) </ins> } <del> pub fn find_rand_n<M, T, I, F>(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut find: F) where I: FnMut(&mut M, usize), F: FnMut(&M, usize) -> T, { // setup let mut rng = rand::weak_rng(); let mut keys: Vec<_> = (0..n).map(|_| rng.gen::<usize>() % n).collect(); for k in &keys { insert(map, *k); } rng.shuffle(&mut keys); // measure let mut i = 0; b.iter(|| { let t = find(map, keys[i]); i = (i + 1) % n; black_box(t); }) </del> <ins> macro_rules! map_find_rand_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use std::rand; use std::rand::Rng; use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup let mut rng = rand::weak_rng(); let mut keys: Vec<_> = (0..n).map(|_| rng.gen() % n).collect(); for &k in &keys { map.insert(k, k); } rng.shuffle(&mut keys); // measure let mut i = 0; b.iter(|| { let t = map.get(&keys[i]); i = (i + 1) % n; black_box(t); }) } ) </ins> } <del> pub fn find_seq_n<M, T, I, F>(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut find: F) where I: FnMut(&mut M, usize), F: FnMut(&M, usize) -> T, { // setup for i in 0..n { insert(map, i); } // measure let mut i = 0; b.iter(|| { let x = find(map, i); i = (i + 1) % n; black_box(x); }) </del> <ins> macro_rules! map_find_seq_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup for i in 0..n { map.insert(i, i); } // measure let mut i = 0; b.iter(|| { let x = map.get(&i); i = (i + 1) % n; black_box(x); }) } ) </ins> }


<ins> // unit-test: ConstProp // compile-flags: -O // Regression test for https://github.com/rust-lang/rust/issues/118328 #![allow(unused_assignments)] struct SizeOfConst<T>(std::marker::PhantomData<T>); impl<T> SizeOfConst<T> { const SIZE: usize = std::mem::size_of::<T>(); } // EMIT_MIR overwrite_with_const_with_params.size_of.ConstProp.diff fn size_of<T>() -> usize { // CHECK-LABEL: fn size_of( // CHECK: _1 = const 0_usize; // CHECK-NEXT: _1 = const _; // CHECK-NEXT: _0 = _1; let mut a = 0; a = SizeOfConst::<T>::SIZE; a } fn main() { assert_eq!(size_of::<u32>(), std::mem::size_of::<u32>()); } </ins>


<del> // no-prefer-dynamic </del> #![feature(unsized_tuple_coercion)] static mut DROP_RAN: isize = 0;


<ins> // Copyright 2014 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. // Test that moves of unsized values within closures are caught // and rejected. fn main() { (|| box *[0u].as_slice())(); //~^ ERROR cannot move a value of type [uint] } </ins>


struct GoodVoid(Void); fn main() { <del> let w = SingleUnused(42, [0, 1, 2, 3], "abc".to_string()); let _ = w.0; let _ = w.2; </del> <ins> let u1 = UnusedAtTheEnd(42, 3.14, [0, 1, 2, 3], "def".to_string(), 4u8); let _ = u1.0; let _ = UnusedJustOneField(42); let u2 = UnusedInTheMiddle(42, 3.14, "def".to_string(), 4u8, 5); let _ = u2.0; let _ = u2.3; </ins> <del> let m = MultipleUnused(42, 3.14, "def".to_string(), 4u8); </del> let gu = GoodUnit(()); let gp = GoodPhantom(PhantomData); let gv = GoodVoid(Void); <del> let _ = (gu, gp, gv, m); </del> <ins> let _ = (gu, gp, gv); </ins> }


let size = mem::size_of::<T>() .checked_mul(count) .expect("is_nonoverlapping: `size_of::<T>() * count` overflows a usize"); <del> let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; </del> <ins> let diff = src_usize.abs_diff(dst_usize); </ins> // If the absolute distance between the ptrs is at least as big as the size of the buffer, // they do not overlap. diff >= size


// discriminant. if !def.repr.c() && !def.repr.transparent() && def.repr.int.is_none() { // Special-case types like `Option<extern fn()>`. <del> if !is_repr_nullable_ptr(cx, ty, def, substs) { </del> <ins> if !self.is_repr_nullable_ptr(ty, def, substs) { </ins> return FfiUnsafe { ty, reason: "enum has no representation hint".into(),


// Associated types in traits don't necessarily have a type that we can visit try_visit!(visitor.visit(ty.span, tcx.type_of(item).instantiate_identity())); } <del> for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { </del> <ins> for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { </ins> try_visit!(visitor.visit(span, pred)); } }


/// let src = [1, 2, 3, 4]; /// let mut dst = [0, 0]; /// <ins> /// // Because the slices have to be the same length, /// // we slice the source slice from four elements /// // to two. It will panic if we don't do this. </ins> /// dst.clone_from_slice(&src[2..]); /// /// assert_eq!(src, [1, 2, 3, 4]);


<del> Subproject commit 7b8e8293d08d298579470f9d6c74731043c6601a </del> <ins> Subproject commit 7a943a9dfcdca98e5988da6d0b7d2f83a364b5ba </ins>


}); } <del> fn get_lint_level(&self, lint: &'static Lint, idx: u32) </del> <ins> fn get_lint_level(&self, lint: &'static Lint, idx: u32, aux: Option<&FxHashMap<LintId, (Level, LintSource)>>) </ins> -> (Level, LintSource) { <del> let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx); </del> <ins> let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux); </ins> // If `level` is none then we actually assume the default level for this // lint.


let fcx = FnCtxt::new(&inh, param_env, id); if !inh.tcx.features().trivial_bounds { // As predicates are cached rather than obligations, this <del> // needsto be called first so that they are checked with an </del> <ins> // needs to be called first so that they are checked with an </ins> // empty `param_env`. check_false_global_bounds(&fcx, span, id); }


//! `&foo()` or `match foo() { ref x => ... }`, where the user is //! implicitly requesting a temporary. //! <del> //! Somewhat surprisingly, not all lvalue expressions yield lvalue datums //! when trans'd. Ultimately the reason for this is to micro-optimize //! the resulting LLVM. For example, consider the following code: //! //!     fn foo() -> Box<int> { ... } //!     let x = *foo(); //! //! The expression `*foo()` is an lvalue, but if you invoke `expr::trans`, //! it will return an rvalue datum. See `deref_once` in expr.rs for //! more details. //! </del> //! ### Rvalues in detail //! //! Rvalues datums are values with no cleanup scheduled. One must be


f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R, ) -> R; <ins> fn evaluation_is_concurrent(&self) -> bool; </ins> fn expand_abstract_consts<T: TypeFoldable<Self>>(self, t: T) -> T; type GenericsOf: GenericsOf<Self>;


ignore_binding, ); <del> let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len; </del> <ins> let no_ambiguity = ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len; </ins> import.vis.set(orig_vis); let module = match path_res { PathResult::Module(module) => {


<del> #!/bin/bash # We use InnoSetup and its `iscc` program to also create combined installers. # Honestly at this point WIX above and `iscc` are just holdovers from # oh-so-long-ago and are required for creating installers on Windows. I think # one is MSI installers and one is EXE, but they're not used so frequently at # this point anyway so perhaps it's a wash! set -euo pipefail IFS=$'nt' source "$(cd "$(dirname "$0")" && pwd)/../shared.sh" if isWindows; then curl.exe -o is-install.exe "${MIRRORS_BASE}/2017-08-22-is.exe" cmd.exe //c "is-install.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-" ciCommandAddPath "C:Program Files (x86)Inno Setup 5" fi </del>


<ins> // compile-flags: -Z mir-opt-level=3 -Z inline-mir // ignore-wasm32-bare compiled with panic=abort by default #![crate_type = "lib"] // EMIT_MIR issue_78442.bar.RevealAll.diff // EMIT_MIR issue_78442.bar.Inline.diff pub fn bar<P>( // Error won't happen if "bar" is not generic _baz: P, ) { hide_foo()(); } fn hide_foo() -> impl Fn() { // Error won't happen if "iterate" hasn't impl Trait or has generics foo } fn foo() { // Error won't happen if "foo" isn't used in "iterate" or has generics } </ins>


<ins> // compile-flags: -Zdrop-tracking-mir // edition:2021 use std::future::Future; trait Client { type Connecting<'a>: Future + Send where Self: 'a; fn connect(&'_ self) -> Self::Connecting<'a>; //~^ ERROR use of undeclared lifetime name `'a` } fn call_connect<C>(c: &'_ C) -> impl '_ + Future + Send where C: Client + Send + Sync, { async move { c.connect().await } //~^ ERROR `C` does not live long enough } fn main() {} </ins>


font-size: 1.25rem; } <ins> /* This class only exists for users who want to draw attention to a particular element in their documentation. */ .content .docblock .warning { border-left: 2px solid var(--warning-border-color); padding: 14px; position: relative; /* The "!important" part is required because the rule is otherwise overruled in this CSS selector: ".docblock > :not(.more-examples-toggle):not(.example-wrap)" */ overflow-x: visible !important; } .content .docblock .warning::before { color: var(--warning-border-color); content: "ⓘ"; position: absolute; left: -25px; top: 5px; font-weight: bold; font-size: 1.25rem; } </ins> a.test-arrow { visibility: hidden; position: absolute;


use ext::tt::macro_parser::{parse, parse_failure_msg}; use ext::tt::quoted; use ext::tt::transcribe::transcribe; <del> use feature_gate::{self, emit_feature_err, Features, GateIssue}; </del> <ins> use feature_gate::Features; </ins> use parse::{Directory, ParseSess}; use parse::parser::Parser; use parse::token::{self, NtTT};


<ins> #![feature(staged_api)] #![stable(feature = "libfoo", since = "1.0.0")] #[unstable(feature = "foo", reason = "...", issue = "none")] pub fn foo() {} #[stable(feature = "libfoo", since = "1.0.0")] pub struct Foo; impl Foo { #[unstable(feature = "foo", reason = "...", issue = "none")] pub fn foo(&self) {} } </ins>


span } = *self; <del> hcx.hash_hir_item_like(attrs, |hcx| { </del> <ins> hcx.hash_hir_item_like(attrs, is_const, |hcx| { </ins> hcx.while_hashing_spans(hash_spans, |hcx| { name.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher);


was_remapped, Some(&unmapped_path)); <del> return match self.source_file_by_stable_id(file_id) { </del> <ins> let lrc_sf = match self.source_file_by_stable_id(file_id) { </ins> Some(lrc_sf) => lrc_sf, None => { let source_file = Lrc::new(SourceFile::new(


source_file: Lrc<rustc_span::SourceFile>, override_span: Option<Span>, ) -> Self { <del> // Make sure external source is loaded first, before accessing it. // While this can't show up during normal parsing, `retokenize` may // be called with a source file from an external crate. sess.source_map().ensure_source_file_source_present(Lrc::clone(&source_file)); let src = if let Some(src) = &source_file.src { Lrc::clone(&src) } else if let Some(src) = source_file.external_src.borrow().get_source() { Lrc::clone(&src) } else { </del> <ins> let src = source_file.src.clone().unwrap_or_else(|| { </ins> sess.span_diagnostic .bug(&format!("cannot lex `source_file` without source: {}", source_file.name)); <del> }; </del> <ins> }); </ins> StringReader { sess,


) => { eq_closure_binder(lb, rb) && lc == rc <del> && la.map_or(false, CoroutineKind::is_async) == ra.map_or(false, CoroutineKind::is_async) </del> <ins> && eq_coroutine_kind(*la, *ra) </ins> && lm == rm && eq_fn_decl(lf, rf) && eq_expr(le, re)


impl Foo { // @has async_fn/struct.Foo.html <del> // @has - '//*[@class="method"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar ) -> impl Iterator<Item = &usize>' </del> <ins> // @has - '//*[@class="method"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar, ) -> impl Iterator<Item = &usize>' </ins> pub async fn complicated_lifetimes(&self, context: &impl Bar) -> impl Iterator<Item = &usize> { [0].iter() }


with_interner(|interner| interner.gensymed(self)) } <ins> pub fn is_gensymed(self) -> bool { with_interner(|interner| interner.is_gensymed(self)) } </ins> pub fn as_str(self) -> LocalInternedString { with_interner(|interner| unsafe { LocalInternedString {


if let Res::Def(DefKind::Mod, ..) = child.res { self.resolve_doc_links_extern_inner(def_id); // Inner attribute scope } <del> // Traits are processed in `add_extern_traits_in_scope`. </del> <ins> // `DefKind::Trait`s are processed in `process_extern_impls`. </ins> if let Res::Def(DefKind::Mod | DefKind::Enum, ..) = child.res { self.process_module_children_or_reexports(def_id); } <ins> if let Res::Def(DefKind::Struct | DefKind::Union | DefKind::Variant, _) = child.res { let field_def_ids = Vec::from_iter( self.resolver .cstore() .associated_item_def_ids_untracked(def_id, self.sess), ); for field_def_id in field_def_ids { self.resolve_doc_links_extern_outer(field_def_id, scope_id); } } </ins> } } }


self.report_error_if_loan_conflicts_with_restriction( old_loan, new_loan, old_loan, new_loan) && self.report_error_if_loan_conflicts_with_restriction( <del> new_loan, old_loan, old_loan, new_loan); </del> <ins> new_loan, old_loan, old_loan, new_loan) </ins> } pub fn report_error_if_loan_conflicts_with_restriction(&self,


fn eof_err(&mut self) -> PErr<'psess> { let msg = "this file contains an unclosed delimiter"; let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg); <del> for &(_, sp) in &self.diag_info.open_braces { err.span_label(sp, "unclosed delimiter"); </del> <ins> let unclosed_delimiter_show_limit = 5; let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_braces.len()); for &(_, span) in &self.diag_info.open_braces[..len] { err.span_label(span, "unclosed delimiter"); </ins> self.diag_info.unmatched_delims.push(UnmatchedDelim { found_delim: None, found_span: self.token.span, <del> unclosed_span: Some(sp), </del> <ins> unclosed_span: Some(span), </ins> candidate_span: None, }); } <ins> if let Some((_, span)) = self.diag_info.open_braces.get(unclosed_delimiter_show_limit) && self.diag_info.open_braces.len() >= unclosed_delimiter_show_limit + 2 { err.span_label( *span, format!( "another {} unclosed delimiters begin from here", self.diag_info.open_braces.len() - unclosed_delimiter_show_limit ), ); } </ins> if let Some((delim, _)) = self.diag_info.open_braces.last() { report_suspicious_mismatch_block( &mut err,


<ins> 1|       |// Verify that the entry point injected by the test harness doesn't cause 2|       |// weird artifacts in the coverage report (e.g. issue #10749). 3|       | 4|       |// compile-flags: --test 5|       | 6|       |#[allow(dead_code)] 7|      0|fn unused() {} 8|       | 9|      1|#[test] 10|      1|fn my_test() {} </ins>


sym::coverage => self.check_coverage(hir_id, attr, span, target), sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target), sym::marker => self.check_marker(hir_id, attr, span, target), <del> sym::target_feature => self.check_target_feature(hir_id, attr, span, target), </del> <ins> sym::target_feature => self.check_target_feature(hir_id, attr, span, target, attrs), </ins> sym::thread_local => self.check_thread_local(attr, span, target), sym::track_caller => { self.check_track_caller(hir_id, attr.span, attrs, span, target)


}; } ast::UnNot => { <del> oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::get(oprnd_t).sty == ty::ty_bool) { oprnd_t = check_user_unop(fcx, "!", "not", tcx.lang_items.not_trait(), expr, &**oprnd, oprnd_t); </del> <ins> if !ty::type_is_bot(oprnd_t) { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::get(oprnd_t).sty == ty::ty_bool) { oprnd_t = check_user_unop(fcx, "!", "not", tcx.lang_items.not_trait(), expr, &**oprnd, oprnd_t); } </ins> } } ast::UnNeg => { <del> oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::type_is_fp(oprnd_t)) { oprnd_t = check_user_unop(fcx, "-", "neg", tcx.lang_items.neg_trait(), expr, &**oprnd, oprnd_t); </del> <ins> if !ty::type_is_bot(oprnd_t) { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::type_is_fp(oprnd_t)) { oprnd_t = check_user_unop(fcx, "-", "neg", tcx.lang_items.neg_trait(), expr, &**oprnd, oprnd_t); } </ins> } } }


#[unsafe_destructor] //~^ ERROR `#[unsafe_destructor]` does nothing anymore <del> //~| HELP: add #![feature(unsafe_destructor)] to the crate attributes to enable // (but of couse there is no point in doing so) </del> impl<'a> Drop for D<'a> { fn drop(&mut self) { } }


<ins> // Copyright 2015 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. #![feature(reflect_marker)] use std::any::TypeId; use std::marker::Reflect; use std::rc::Rc; type Fp<T> = Rc<T>; struct Engine; trait Component: 'static + Reflect {} impl Component for Engine {} trait Env { fn get_component_type_id(&self, type_id: TypeId) -> Option<Fp<Component>>; } impl<'a> Env+'a { fn get_component<T: Component>(&self) -> Option<Fp<T>> { let x = self.get_component_type_id(TypeId::of::<T>()); None } } trait Figment { fn init(&mut self, env: &Env); } struct MyFigment; impl Figment for MyFigment { fn init(&mut self, env: &Env) { let engine = env.get_component::<Engine>(); } } fn main() {} </ins>


<ins> // issue-52240: Can turn immutable into mut with `ref mut` enum Foo { Bar(i32), } fn main() { let arr = vec!(Foo::Bar(0)); if let (Some(Foo::Bar(ref mut val)), _) = (&arr.get(0), 0) { //~^ ERROR cannot borrow field of immutable binding as mutable *val = 9001; } match arr[0] { Foo::Bar(ref s) => println!("{}", s) } } </ins>


#![feature(nll)] #![feature(set_stdio)] #![feature(test)] <del> #![feature(vec_remove_item)] </del> #![feature(ptr_offset_from)] #![feature(crate_visibility_modifier)] #![feature(const_fn)]


} } <del> #[unstable(feature = "panic_info_message", issue = "66745")] </del> <ins> #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] </ins> impl Display for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {


<ins> // Copyright 2014 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. fn main() { (return)[0u]; //~ ERROR cannot index a value of type `!` } </ins>


<ins> // Regression test for https://github.com/rust-lang/rust/issues/70673. // run-pass #![feature(thread_local)] #[thread_local] static A: &u8 = &42; fn main() { dbg!(*A); } </ins>


} } <ins> fn eq_coroutine_kind(a: Option<CoroutineKind>, b: Option<CoroutineKind>) -> bool { match (a, b) { (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. })) | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. })) | (Some(CoroutineKind::AsyncGen { .. }), Some(CoroutineKind::AsyncGen { .. })) | (None, None) => true, _ => false, } } </ins> pub fn eq_field(l: &ExprField, r: &ExprField) -> bool { l.is_placeholder == r.is_placeholder && eq_id(l.ident, r.ident)


} None => { debug!(?param.ident, ?param.ident.span); let deletion_span = deletion_span(); <del> self.r.lint_buffer.buffer_lint_with_diagnostic( lint::builtin::UNUSED_LIFETIMES, param.id, param.ident.span, &format!("lifetime parameter `{}` never used", param.ident), lint::BuiltinLintDiagnostics::SingleUseLifetime { param_span: param.ident.span, use_span: None, deletion_span, }, ); </del> <ins> // the give lifetime originates from expanded code so we won't be able to remove it #104432 let lifetime_only_in_expanded_code = deletion_span.map(|sp| sp.in_derive_expansion()).unwrap_or(true); if !lifetime_only_in_expanded_code { self.r.lint_buffer.buffer_lint_with_diagnostic( lint::builtin::UNUSED_LIFETIMES, param.id, param.ident.span, &format!("lifetime parameter `{}` never used", param.ident), lint::BuiltinLintDiagnostics::SingleUseLifetime { param_span: param.ident.span, use_span: None, deletion_span, }, ); } </ins> } } }


multibyte_chars, non_narrow_chars, name_hash, <del> } </del> <ins> }) </ins> } /// Returns the `BytePos` of the beginning of the current line.


fn ilog10_u128() { ilog10_loop! { u128, 38 } } <ins> #[test] #[should_panic(expected = "argument of integer logarithm must be positive")] fn ilog2_of_0_panic() { let _ = 0u32.ilog2(); } #[test] #[should_panic(expected = "argument of integer logarithm must be positive")] fn ilog10_of_0_panic() { let _ = 0u32.ilog10(); } #[test] #[should_panic(expected = "argument of integer logarithm must be positive")] fn ilog3_of_0_panic() { let _ = 0u32.ilog(3); } #[test] #[should_panic(expected = "base of integer logarithm must be at least 2")] fn ilog0_of_1_panic() { let _ = 1u32.ilog(0); } #[test] #[should_panic(expected = "base of integer logarithm must be at least 2")] fn ilog1_of_1_panic() { let _ = 1u32.ilog(1); } </ins>


| LL |         MyEnum::Struct => "", |         ^^^^^^^^^^^^^^ not a unit struct, unit variant or constant <ins> | help: the struct variant's field is being ignored | LL |         MyEnum::Struct { s: _ } => "", |                        ++++++++ </ins> error: aborting due to 2 previous errors


<ins> error[E0308]: mismatched types --> $DIR/mut-mut-wont-coerce.rs:36:14 | LL |     make_foo(&mut &mut *result); |     -------- ^^^^^^^^^^^^^^^^^ expected `*mut *mut Foo`, found `&mut &mut Foo` |     | |     arguments to this function are incorrect | = note:    expected raw pointer `*mut *mut Foo` found mutable reference `&mut &mut Foo` note: function defined here --> $DIR/mut-mut-wont-coerce.rs:30:4 | LL | fn make_foo(_: *mut *mut Foo) { |    ^^^^^^^^ ---------------- error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0308`. </ins>


<ins> warning: unused variable: `props_2` --> $DIR/issue-87987.rs:11:9 | LL |     let props_2 = Props { |         ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_props_2` | = note: `#[warn(unused_variables)]` on by default warning: field is never read: `field_1` --> $DIR/issue-87987.rs:5:5 | LL |     field_1: u32, |     ^^^^^^^^^^^^ | = note: `#[warn(dead_code)]` on by default warning: field is never read: `field_2` --> $DIR/issue-87987.rs:6:5 | LL |     field_2: u32, |     ^^^^^^^^^^^^ warning: 3 warnings emitted </ins>


// of llvm-config, not the target that we're attempting to link. let mut cmd = Command::new(&llvm_config); cmd.arg("--libs"); <ins> // Force static linking with "--link-static" if available. let mut version_cmd = Command::new(&llvm_config); version_cmd.arg("--version"); let version_output = output(&mut version_cmd); let mut parts = version_output.split('.'); if let (Some(major), Some(minor)) = (parts.next().and_then(|s| s.parse::<u32>().ok()), parts.next().and_then(|s| s.parse::<u32>().ok())) { if major > 3 || (major == 3 && minor >= 8) { cmd.arg("--link-static"); } } </ins> if !is_crossed { cmd.arg("--system-libs"); }


<del> error: field `1` is never read --> $DIR/tuple-struct-field.rs:8:26 </del> <ins> error: fields `1`, `2`, `3`, and `4` are never read --> $DIR/tuple-struct-field.rs:8:28 </ins> | <del> LL | struct SingleUnused(i32, [u8; LEN], String); |        ------------      ^^^^^^^^^ </del> <ins> LL | struct UnusedAtTheEnd(i32, f32, [u8; LEN], String, u8); |        --------------      ^^^  ^^^^^^^^^  ^^^^^^  ^^ </ins> |        | <del> |        field in this struct </del> <ins> |        fields in this struct </ins> | <ins> = help: consider removing these fields </ins> note: the lint level is defined here --> $DIR/tuple-struct-field.rs:1:9 | LL | #![deny(dead_code)] |         ^^^^^^^^^ <del> help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field </del> <ins> error: field `0` is never read --> $DIR/tuple-struct-field.rs:13:27 | LL | struct UnusedJustOneField(i32); |        ------------------ ^^^ |        | |        field in this struct </ins> | <del> LL | struct SingleUnused(i32, (), String); |                          ~~ </del> <ins> = help: consider removing this field </ins> <del> error: fields `0`, `1`, `2`, and `3` are never read --> $DIR/tuple-struct-field.rs:13:23 </del> <ins> error: fields `1`, `2`, and `4` are never read --> $DIR/tuple-struct-field.rs:18:31 </ins> | <del> LL | struct MultipleUnused(i32, f32, String, u8); |        -------------- ^^^  ^^^  ^^^^^^  ^^ </del> <ins> LL | struct UnusedInTheMiddle(i32, f32, String, u8, u32); |        -----------------      ^^^  ^^^^^^      ^^^ </ins> |        | |        fields in this struct | help: consider changing the fields to be of unit type to suppress this warning while preserving the field numbering, or remove the fields | <del> LL | struct MultipleUnused((), (), (), ()); |                       ~~  ~~  ~~  ~~ </del> <ins> LL | struct UnusedInTheMiddle(i32, (), (), u8, ()); |                               ~~  ~~      ~~ </ins> <del> error: aborting due to 2 previous errors </del> <ins> error: aborting due to 3 previous errors </ins>


} } <del> return ty::ExistentialBounds { region_bound: region_bound, builtin_bounds: builtin_bounds, projection_bounds: projection_bounds }; </del> <ins> ty::ExistentialBounds::new( region_bound, builtin_bounds, projection_bounds) </ins> } fn parse_builtin_bounds(&mut self) -> ty::BuiltinBounds {


use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; <del> use crate::sync::atomic::{AtomicBool, Ordering}; </del> use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; <del> use libc::c_int; </del> //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes ////////////////////////////////////////////////////////////////////////////////


/// Basic usage: /// /// ``` <del> /// #![feature(nonzero_leading_trailing_zeros)] </del> #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", stringify!($LeadingTestExpr), ").unwrap();")] /// /// assert_eq!(n.leading_zeros(), 0); /// ``` <del> #[unstable(feature = "nonzero_leading_trailing_zeros", issue = "79143")] #[rustc_const_unstable(feature = "nonzero_leading_trailing_zeros", issue = "79143")] </del> <ins> #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")] #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")] </ins> #[inline] pub const fn leading_zeros(self) -> u32 { // SAFETY: since `self` can not be zero it is safe to call ctlz_nonzero


} if let ExprKind::StaticRef { def_id, .. } = expr.kind { let is_thread_local = this.hir.tcx().has_attr(def_id, sym::thread_local); <ins> local_decl.internal = true; </ins> local_decl.local_info = LocalInfo::StaticRef { def_id, is_thread_local }; } this.local_decls.push(local_decl)


// `dyn T:` is lowered to `dyn T: ReEmpty` - check that we don't ICE in NLL for // the unexpected region. <del> // build-pass (FIXME(62277): could be check-pass?) </del> <ins> // check-pass </ins> trait T {} fn f() where dyn T: {} <del> fn main() {} </del> <ins> fn main() { f(); } </ins>


const ENTRY_LIMIT: usize = 900; // FIXME: The following limits should be reduced eventually. <del> const ISSUES_ENTRY_LIMIT: usize = 1854; </del> <ins> const ISSUES_ENTRY_LIMIT: usize = 1852; </ins> const ROOT_ENTRY_LIMIT: usize = 867; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[


<ins> -include ../tools.mk all: $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc foo.rs $(HTMLDOCCK) $(TMPDIR)/doc foo.rs $(HTMLDOCCK) $(TMPDIR)/doc qux/mod.rs </ins>


<ins> // check-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash pub struct Tuple; pub trait Trait<const I: usize> { type Input: From<<Self as Trait<I>>::Input>; } fn main() {} </ins>


use astconv::AstConv; use check::{self, FnCtxt}; <del> use middle::ty::{self, Ty}; </del> <ins> use middle::ty::{self, Ty, ToPolyTraitRef, AsPredicate}; </ins> use middle::def; <ins> use middle::lang_items::FnOnceTraitLangItem; use middle::subst::Substs; use middle::traits::{Obligation, SelectionContext}; </ins> use metadata::{csearch, cstore, decoder}; use syntax::{ast, ast_util};


) .lines() .map(|s| s.trim().to_owned()) <ins> .filter(|f| Path::new(f).extension().map_or(false, |ext| ext == "rs")) </ins> .collect(), ) }


<ins> // check-pass // edition:2021 // compile-flags: -Zunstable-options fn main() { let _: u16 = 123i32.try_into().unwrap(); } </ins>


// originating from macros, since the segment's span might be from a macro arg. segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span) }; <del> if error { </del> <ins> if let LifetimeRes::Error = res { </ins> let sess = self.r.session; let mut err = rustc_errors::struct_span_err!( sess,


use std::alloc::{Global, Alloc, Layout, System}; <del> /// Issue #45955. </del> <ins> /// Issue #45955 and #62251. </ins> #[test] fn alloc_system_overaligned_request() { check_overalign_requests(System)


discr_index, .. } => { <del> if !dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index) { throw_ub!(InvalidDiscriminant(variant_scalar)); } </del> <ins> // No need to validate that the discriminant here because the // `TyLayout::for_variant()` call earlier already checks the variant is valid. </ins> let discr_val = dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;


if create_issue_for_status is not None: try: issue( <del> tool, create_issue_for_status, MAINTAINERS.get(tool, ''), relevant_pr_number, relevant_pr_user, LABELS.get(tool, ''), </del> <ins> tool, create_issue_for_status, MAINTAINERS.get(tool, ()), relevant_pr_number, relevant_pr_user, LABELS.get(tool, []), github_token, </ins> ) <del> except urllib2.HTTPError as e: </del> <ins> except HTTPError as e: </ins> # network errors will simply end up not creating an issue, but that's better # than failing the entire build job <del> print("HTTPError when creating issue for status regression: {0}n{1}" </del> <ins> print("HTTPError when creating issue for status regression: {0}n{1!r}" </ins> .format(e, e.read())) except IOError as e: print("I/O error when creating issue for status regression: {0}".format(e))


// stripping away any starting or ending parenthesis characters—hence this // test of the JSON error format. <del> #![warn(unused_parens)] </del> <ins> #![deny(unused_parens)] </ins> #![allow(unreachable_code)] fn main() { let _b = false; <del> if (_b) { </del> <ins> if (_b) { //~ ERROR unnecessary parentheses </ins> println!("hello"); }


]).decode(sys.getdefaultencoding()).strip() llvm_sha = subprocess.check_output([ "git", "rev-list", "--author=bors@rust-lang.org", "-n1", <del> "--merges", "--first-parent", "HEAD", </del> <ins> "--first-parent", "HEAD", </ins> "--", "{}/src/llvm-project".format(top_level), "{}/src/bootstrap/download-ci-llvm-stamp".format(top_level),


ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => { return visit::walk_item(self, i); } <del> ItemKind::Fn(_, FnHeader { asyncness: IsAsync::Async { closure_id, return_impl_trait_id, }, .. }, ..) => { </del> <ins> ItemKind::Fn( ref decl, ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. }, ref generics, ref body, ) => { </ins> return self.visit_async_fn( i.id, <del> closure_id, return_impl_trait_id, </del> i.ident.name, i.span, <del> |this| visit::walk_item(this, i) </del> <ins> header, generics, decl, body, </ins> ) } ItemKind::Mod(..) => DefPathData::Module(i.ident.as_interned_str()),


), .. }) => { <del> // We have a situation like `while Some(0) = value.get(0) {`, where `while let` // was more likely intended. err.span_suggestion_verbose( expr.span.shrink_to_lo(), "you might have meant to use pattern destructuring", "let ".to_string(), Applicability::MachineApplicable, ); </del> <ins> // Check if our lhs is a child of the condition of a while loop let expr_is_ancestor = std::iter::successors(Some(lhs.hir_id), |id| { self.tcx.hir().find_parent_node(*id) }) .take_while(|id| *id != parent) .any(|id| id == expr.hir_id); // if it is, then we have a situation like `while Some(0) = value.get(0) {`, // where `while let` was more likely intended. if expr_is_ancestor { err.span_suggestion_verbose( expr.span.shrink_to_lo(), "you might have meant to use pattern destructuring", "let ".to_string(), Applicability::MachineApplicable, ); } </ins> break; } hir::Node::Item(_)


<ins> // Checks that there is a suggestion for simple tuple index access expression (used where an // identifier is expected in a format arg) to use positional arg instead. // Issue: <https://github.com/rust-lang/rust/issues/122535>. //@ run-rustfix fn main() { let x = (1,); println!("{0}", x.0); //~^ ERROR invalid format string } </ins>


impl<CTX> HashStable<CTX> for InferTy { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { use InferTy::*; <ins> discriminant(self).hash_stable(ctx, hasher); </ins> match self { TyVar(v) => v.as_u32().hash_stable(ctx, hasher), IntVar(v) => v.index.hash_stable(ctx, hasher),


{ let result = local_s .try_with(|s| { <del> if let Ok(mut borrowed) = s.try_borrow_mut() { if let Some(w) = borrowed.as_mut() { return w.write_fmt(args); } </del> <ins> // Note that we completely remove a local sink to write to in case // our printing recursively panics/prints, so the recursive // panic/print goes to the global sink instead of our local sink. let prev = s.borrow_mut().take(); if let Some(mut w) = prev { let result = w.write_fmt(args); *s.borrow_mut() = Some(w); return result; </ins> } global_s().write_fmt(args) })


_ => tcx.def_span(item), }; try_visit!(visitor.visit(span, tcx.type_of(item).instantiate_identity())); <del> for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { </del> <ins> for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { </ins> try_visit!(visitor.visit(span, pred)); } } DefKind::TraitAlias | DefKind::Trait => { <del> for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { </del> <ins> for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { </ins> try_visit!(visitor.visit(span, pred)); } }


//     impl Foo for std::cell::Ref<u32> // note lack of '_ //     async fn foo(_: std::cell::Ref<u32>) { ... } LifetimeRibKind::AnonymousCreateParameter(_) => { <del> error = true; </del> break; } // `PassThrough` is the normal case.


pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> { fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> { <del> let mut maybe_result: Vec<u16> = s.encode_wide().collect(); </del> <ins> // Most paths are ASCII, so reserve capacity for as much as there are bytes // in the OsStr plus one for the null-terminating character. We are not // wasting bytes here as paths created by this function are primarily used // in an ephemeral fashion. let mut maybe_result = Vec::with_capacity(s.len() + 1); maybe_result.extend(s.encode_wide()); </ins> if unrolled_find_u16s(0, &maybe_result).is_some() { return Err(crate::io::const_io_error!( ErrorKind::InvalidInput,


return self.parse_if_expr(); } if try!(self.eat_keyword(keywords::For) ){ <del> return self.parse_for_expr(None); </del> <ins> let lo = self.last_span.lo; return self.parse_for_expr(None, lo); </ins> } if try!(self.eat_keyword(keywords::While) ){ <del> return self.parse_while_expr(None); </del> <ins> let lo = self.last_span.lo; return self.parse_while_expr(None, lo); </ins> } if self.token.is_lifetime() { let lifetime = self.get_lifetime(); <ins> let lo = self.span.lo; </ins> try!(self.bump()); try!(self.expect(&token::Colon)); if try!(self.eat_keyword(keywords::While) ){ <del> return self.parse_while_expr(Some(lifetime)) </del> <ins> return self.parse_while_expr(Some(lifetime), lo) </ins> } if try!(self.eat_keyword(keywords::For) ){ <del> return self.parse_for_expr(Some(lifetime)) </del> <ins> return self.parse_for_expr(Some(lifetime), lo) </ins> } if try!(self.eat_keyword(keywords::Loop) ){ <del> return self.parse_loop_expr(Some(lifetime)) </del> <ins> return self.parse_loop_expr(Some(lifetime), lo) </ins> } return Err(self.fatal("expected `while`, `for`, or `loop` after a label")) } if try!(self.eat_keyword(keywords::Loop) ){ <del> return self.parse_loop_expr(None); </del> <ins> let lo = self.last_span.lo; return self.parse_loop_expr(None, lo); </ins> } if try!(self.eat_keyword(keywords::Continue) ){ let lo = self.span.lo;


Abi::Aggregate { sized: true } }; align = align.max(niche_align); <ins> size = size.abi_align(align); </ins> return Ok(tcx.intern_layout(LayoutDetails { variants: Variants::NicheFilling {


|                            ^ help: remove this semicolon error[E0601]: `main` function not found in crate `issue_49040` <del> --> $DIR/issue-49040.rs:1:29 </del> <ins> --> $DIR/issue-49040.rs:2:12 </ins> | <del> LL | #![allow(unused_variables)]; |                             ^ consider adding a `main` function to `$DIR/issue-49040.rs` </del> <ins> LL | fn foo() {} |            ^ consider adding a `main` function to `$DIR/issue-49040.rs` </ins> error: aborting due to 2 previous errors


/// # Examples /// /// ``` <del> /// #![feature(mutex_unpoison)] /// </del> /// use std::sync::{Arc, Mutex}; /// use std::thread; ///


<ins> //! This test checks that types of up to 128 bits are returned by-value instead of via out-pointer. // compile-flags: -C no-prepopulate-passes -O // only-x86_64 #![crate_type = "lib"] pub struct S { a: u64, b: u32, c: u32, } // CHECK: define i128 @modify(%S* noalias nocapture dereferenceable(16) %s) #[no_mangle] pub fn modify(s: S) -> S { S { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c } } #[repr(packed)] pub struct TooBig { a: u64, b: u32, c: u32, d: u8, } // CHECK: define void @m_big(%TooBig* [[ATTRS:.*sret.*]], %TooBig* [[ATTRS2:.*]] %s) #[no_mangle] pub fn m_big(s: TooBig) -> TooBig { TooBig { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c, d: s.d + s.d } } </ins>


} } } <del> self.sess.abort_if_errors(); </del> None } } } <del> fn add_existing_rlib(&self, libs: &mut [Library], path: &Path, file: &str) -> bool { let (prefix, suffix) = self.dylibname(); let file = file.slice_from(3); // chop off 'lib' let file = file.slice_to(file.len() - 5); // chop off '.rlib' let file = format!("{}{}{}", prefix, file, suffix); for lib in libs.mut_iter() { match lib.dylib { Some(ref p) if p.filename_str() == Some(file.as_slice()) => { assert!(lib.rlib.is_none()); // FIXME: legit compiler error lib.rlib = Some(path.clone()); return true; } Some(..) | None => {} } </del> <ins> // Attempts to match the requested version of a library against the file // specified. The prefix/suffix are specified (disambiguates between // rlib/dylib). // // The return value is `None` if `file` doesn't look like a rust-generated // library, or if a specific version was requested and it doens't match the // apparent file's version. // // If everything checks out, then `Some(hash)` is returned where `hash` is // the listed hash in the filename itself. fn try_match(&self, file: &str, prefix: &str, suffix: &str) -> Option<~str>{ let middle = file.slice(prefix.len(), file.len() - suffix.len()); debug!("matching -- {}, middle: {}", file, middle); let mut parts = middle.splitn('-', 1); let hash = match parts.next() { Some(h) => h, None => return None }; debug!("matching -- {}, hash: {}", file, hash); let vers = match parts.next() { Some(v) => v, None => return None }; debug!("matching -- {}, vers: {}", file, vers); if !self.version.is_empty() && self.version.as_slice() != vers { return None } debug!("matching -- {}, vers ok (requested {})", file, self.version); // hashes in filenames are prefixes of the "true hash" if self.hash.is_empty() || self.hash.starts_with(hash) { debug!("matching -- {}, hash ok (requested {})", file, self.hash); Some(hash.to_owned()) } else { None </ins> } <del> return false; </del> } <del> fn add_existing_dylib(&self, libs: &mut [Library], path: &Path, file: &str) -> bool { let (prefix, suffix) = self.dylibname(); let file = file.slice_from(prefix.len()); let file = file.slice_to(file.len() - suffix.len()); let file = format!("lib{}.rlib", file); </del> <ins> // Attempts to extract *one* library from the set `m`. If the set has no // elements, `None` is returned. If the set has more than one element, then // the errors and notes are emitted about the set of libraries. // // With only one library in the set, this function will extract it, and then // read the metadata from it if `*slot` is `None`. If the metadata couldn't // be read, it is assumed that the file isn't a valid rust library (no // errors are emitted). // // FIXME(#10786): for an optimization, we only read one of the library's //                metadata sections. In theory we should read both, but //                reading dylib metadata is quite slow. fn extract_one(&self, m: HashSet<Path>, flavor: &str, slot: &mut Option<MetadataBlob>) -> Option<Path> { if m.len() == 0 { return None } if m.len() > 1 { self.sess.span_err(self.span, format!("multiple {} candidates for `{}`  found", flavor, self.name)); for (i, path) in m.iter().enumerate() { self.sess.span_note(self.span, format!(r"candidate #{}: {}", i + 1, path.display())); } return None } </ins> <del> for lib in libs.mut_iter() { match lib.rlib { Some(ref p) if p.filename_str() == Some(file.as_slice()) => { assert!(lib.dylib.is_none()); // FIXME: legit compiler error lib.dylib = Some(path.clone()); return true; </del> <ins> let lib = m.move_iter().next().unwrap(); if slot.is_none() { info!("{} reading meatadata from: {}", flavor, lib.display()); match get_metadata_section(self.os, &lib) { Some(blob) => { if crate_matches(blob.as_slice(), self.name, self.version, self.hash) { *slot = Some(blob); } else { info!("metadata mismatch"); return None; } } None => { info!("no metadata found"); return None </ins> } <del> Some(..) | None => {} </del> } } <del> return false; </del> <ins> return Some(lib); </ins> } // Returns the corresponding (prefix, suffix) that files need to have for


} } <del> /// External iterator for a string's characters and their byte offsets. /// Use with the `std::iter` module. </del> <ins> /// Iterator for a string's characters and their byte offsets. </ins> #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CharIndices<'a> {


<ins> // Test that associated type bounds are correctly normalized when checking // default associated type values. // check-pass #![allow(incomplete_features)] #![feature(specialization)] #[derive(PartialEq)] enum Never {} trait Foo { type Assoc: PartialEq; // PartialEq<<Self as Foo>::Assoc> } impl<T> Foo for T { default type Assoc = Never; } trait Trait1 { type Selection: PartialEq; } trait Trait2: PartialEq<Self> {} impl<T: Trait2> Trait1 for T { default type Selection = T; } fn main() {} </ins>


// FIXME (#2397): At some point we want to rpath our guesses as to // where extern libraries might live, based on the // addl_lib_search_paths <del> args.push_all(rpath::get_rpath_flags(sess, out_filename)); </del> <ins> if !sess.opts.no_rpath { args.push_all(rpath::get_rpath_flags(sess, out_filename)); } </ins> // Finally add all the linker arguments provided on the command line along // with any #[link_args] attributes found inside the crate


impl<'tcx> GATSubstCollector<'tcx> { fn visit<T: TypeFoldable<'tcx>>( <ins> tcx: TyCtxt<'tcx>, </ins> gat: DefId, t: T, ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) { <del> let mut visitor = GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() }; </del> <ins> let mut visitor = GATSubstCollector { tcx, gat, regions: FxHashSet::default(), types: FxHashSet::default(), }; </ins> t.visit_with(&mut visitor); (visitor.regions, visitor.types) }


fn poll_write( self, cx: &mut Option<String>,  buf: &mut [usize]   buf: &mut [usize],  ) -> Option<Result<usize, Error>>;     fn poll_flush(self, cx: &mut Option<String>) -> Option<Result<(), Error>>;     fn poll_close(self, cx: &mut Option<String>) -> Option<Result<(), Error>>;


fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> { let mut ty = self.typeck_results.node_type(pat.hir_id); <del> if let ty::Error(_) = ty.kind { // Avoid ICEs (e.g., #50577 and #50585). return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) }; } </del> let kind = match pat.kind { hir::PatKind::Wild => PatKind::Wild,


to `int`s, though. We can make it usable by any type, but we haven't quite gotten there yet! <del> You can have any number of values in an enum: </del> <ins> You can also have any number of values in an enum: </ins> ```{rust} enum OptionalColor {


// Regression test for issue #4935 fn foo(a: usize) {} <del> fn main() { foo(5, 6) } //~ ERROR this function takes 1 parameter but 2 parameters were supplied //~^ NOTE the following parameter type was expected </del> <ins> fn main() { foo(5, 6) } //~^ ERROR this function takes 1 parameter but 2 parameters were supplied //~| NOTE the following parameter type was expected //~| NOTE expected 1 parameter </ins>


<ins> // check-pass // This is currently stable behavior, which was almost accidentally made an // error in #102161 since there is no test exercising it. I am not sure if // this _should_ be the desired behavior, but at least we should know if it // changes. fn main() {} trait Foo { fn fn_with_type_named_same_as_local_in_param(b: i32, b: i32); } </ins>